@sendbird/ai-agent-messenger-react 1.21.3 → 1.23.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/BBssumix.cjs +1 -0
- package/dist/cjs/BCDZXq61.cjs +1 -0
- package/dist/cjs/Bz2jHC-Z.cjs +1 -0
- package/dist/cjs/CFY_588Z.cjs +1 -0
- package/dist/cjs/CHz4H01e.cjs +1 -0
- package/dist/cjs/CfhYXtgc.cjs +1 -0
- package/dist/cjs/Jlh8RyJW.cjs +1 -0
- package/dist/cjs/RKaCusvu.cjs +1 -0
- package/dist/cjs/Sz9ta-fi.cjs +1 -0
- package/dist/es/{DuNYicWu.js → 5tV340wv.js} +78 -21
- package/dist/es/{BtQecLIw.js → 7vCh5QlQ.js} +78 -21
- package/dist/es/{IxuoSGGX.js → BEqaF3DV.js} +78 -21
- package/dist/es/{PQi1lji5.js → BUKDIngh.js} +76 -19
- package/dist/es/{BxxBjc14.js → CKLYurhd.js} +78 -21
- package/dist/es/{g-NLyB8N.js → CXt8kUk8.js} +78 -21
- package/dist/es/{QVU1iD0e.js → CkoDhLul.js} +78 -21
- package/dist/es/{KPAYWEjC.js → CsqVHJCI.js} +76 -19
- package/dist/es/{B7zqM9VD.js → ZdYGAJn_.js} +78 -21
- package/dist/index.cjs +306 -137
- package/dist/index.d.ts +230 -18
- package/dist/index.js +6556 -3621
- package/package.json +2 -2
- package/dist/cjs/B8e5M4M9.cjs +0 -1
- package/dist/cjs/Ba_JKDGK.cjs +0 -1
- package/dist/cjs/BqsoHLlP.cjs +0 -1
- package/dist/cjs/CSOR33ij.cjs +0 -1
- package/dist/cjs/Cdz9XkkI.cjs +0 -1
- package/dist/cjs/DR4bCizU.cjs +0 -1
- package/dist/cjs/DW6lSsOu.cjs +0 -1
- package/dist/cjs/cDxb_gcv.cjs +0 -1
- package/dist/cjs/zu820q6g.cjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
"use strict";var rs=Object.defineProperty;var os=(e,t,n)=>t in e?rs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var C=(e,t,n)=>os(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("@sendbird/chat"),d=require("react"),M=require("styled-components"),Be=require("date-fns"),ss=require("date-fns/locale/en-US"),ee=require("@sendbird/chat/aiAgent"),we=require("@sendbird/chat/message"),ot=require("@sendbird/chat/groupChannel"),$e=require("@sendbird/uikit-tools"),is=require("react-dom"),as=require("date-fns/isSameDay"),mn=require("@sendbird/react-uikit-message-template-view"),ls=require("@sendbird/uikit-message-template"),cs=require("dompurify"),ds=require("@emotion/is-prop-valid"),Pt=e=>e&&e.__esModule?e:{default:e};function us(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 ms=Pt(X),s=us(d),h=Pt(M),Ur=Pt(cs),hs=Pt(ds),je="sb-agent",Hr="KEY_IMG_ASPECT_RATIO",hn="*/*",H={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 It=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(It||{}),nt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(nt||{});const Vr=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},gs=e=>e===nt.COMPLETED||e===nt.CANCELED?e:nt.IN_PROGRESS,en=e=>Le(e)&&!Vr(e),Le=e=>!!e&&"sender"in e,fs=e=>Le(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),ps=(e,t,n,r=!0)=>{if(!r||!en(e))return"single";const o=()=>{if(!en(t))return!1;const c=t.sender.userId===e.sender.userId,u=Be.isSameMinute(t.createdAt,e.createdAt);return c&&u},i=()=>{if(!en(n))return!1;const c=n.sender.userId===e.sender.userId,u=Be.isSameMinute(n.createdAt,e.createdAt);return c&&u},a=o(),l=i();return a&&l?"middle":a?"bottom":l?"top":"single"},it=(e,t)=>(()=>{var r;return Le(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Pe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Vr(e),isIncoming:(e,t)=>Le(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Le(e)&&(e.sender.userId===t||e.sendingStatus===we.SendingStatus.PENDING)},Ie=e=>e.startsWith("image/"),zr=e=>e.startsWith("video/"),In=(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"},Gr=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},Ft=e=>{switch(e){case"top":case"middle":return H.GAP_GROUPED;default:return H.GAP_UNGROUPED}},Es=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(i,...a)=>{const[l,c,u]=a;return o<u&&r.push({type:"text",value:e.slice(o,u).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),o=u+i.length,i}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),t?r.map(i=>i.type!=="text"?i:{...i,value:t(i.value)}):r},_s=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),bs=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Cs=e=>e.replace(/~~/g,"\\~\\~"),xs=e=>{let t=e;return t=_s(t),t=bs(t),t=Cs(t),t},vs=typeof navigator<"u"&&navigator.product==="ReactNative",Xn=(e,t)=>{const n=r=>!t||t.length===0?!0:Le(r)&&t.includes(r.sendingStatus);return vs?e.find(n):e.findLast(n)};function be(){}function ys(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Ss(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const gn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},ke={isStreaming(e){const t=gn(e.data);return typeof t=="object"&&!!t.stream},isWelcomeMessage(e,t){var n;if(((n=e.extendedMessagePayload)==null?void 0:n.bot_message_type)==="welcome")return!0;if(it(e,t)){const r=gn(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},tn=`@${je}`,As=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${tn}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const i=Ss(`${e}/${t}/${o}`);return`${tn}-udata/${i}`},anonUserSession:()=>`${tn}-session/${e}/${t}`};return{template:{set:(o,i)=>n.set(r.template(o),i),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 i=n.get(r.messengerSession(o));return i?JSON.parse(i):null}catch{return null}},setSettings:(o,i)=>{try{delete i.auto_created_user;const a=JSON.stringify(i);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 i=JSON.stringify(o);n.set(r.anonUserSession(),i)}catch{return}},clear:o=>{try{o&&n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}},Wr=(e,t,n={})=>{let r=null,o=null,i=null;const{leading:a=!0,trailing:l=!0}=n,c=(...u)=>{const g=Date.now();if(i===null||g-i>=t)a?(e(...u),i=g):(o=u,i=g);else if(o=u,l&&!r){const p=t-(g-i);r=setTimeout(()=>{o&&l&&(e(...o),i=Date.now()),r=null,o=null},p)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,i=null},c};class qr{constructor(t,{filter:n,limit:r=20}){C(this,"filter");C(this,"_sdk");C(this,"_pinnedChannels");C(this,"_channels");C(this,"_isDisposed",!1);C(this,"_handlerId",`handler-id-${Date.now()}`);C(this,"_order",ot.GroupChannelListOrder.LATEST_LAST_MESSAGE);C(this,"_limit");C(this,"_query");C(this,"_token");C(this,"_timestamp");C(this,"_isSyncing");C(this,"_channelHandler");C(this,"_connectionHandler");C(this,"_collectionEventHandler");C(this,"_throttledOnChannelChanged");var o,i,a,l,c,u,g;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(o=this.filter)==null?void 0:o.aiAgentChannelFilter,aiAgentConversationStatusFilter:(i=this.filter)==null?void 0:i.aiAgentConversationStatusFilter,aiAgentIds:(a=this.filter)==null?void 0:a.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.pinnedChannelUrls,copilotConversationOnly:(u=this.filter)==null?void 0:u.copilotConversationOnly,copilotSupportChannelUrl:(g=this.filter)==null?void 0:g.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=Wr(p=>{this._query.belongsTo(p)?this._addChannelsToView([p],!1):this._removeChannelsFromView([p.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new ot.GroupChannelHandler({onChannelChanged:p=>{p.isGroupChannel()&&this._throttledOnChannelChanged(p)},onChannelDeleted:p=>{this._removeChannelsFromView([p])}}),this._connectionHandler=new X.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var i,a;const n=new Set(((i=this.filter)==null?void 0:i.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let o;r?o=((a=r.lastMessage)==null?void 0:a.createdAt)??r.createdAt:o=this._query.lastResponseAt,this._timestamp>o&&(this._timestamp=o)}async _syncChannelChangelogs(){if(this._isDisposed)return[];if(this._isSyncing)return[];try{this._isSyncing=!0;let t;for(this._token?t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter):t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByTimestamp(this._timestamp,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls);t.hasMore&&t.token;)t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls)}catch{}finally{this._isSyncing=!1}return[]}_upsertPinnedChannelsToArray(t){var l;const n=((l=this.filter)==null?void 0:l.pinnedChannelUrls)??[],r=new Map(n.map((c,u)=>[c,u])),o=[],i=[],a=[];for(const c of t){if(!this._query.belongsTo(c)){a.push(c.url);continue}const u=r.get(c.url);if(u===void 0)continue;const g=fn(this._pinnedChannels,c);g>=0?(this._pinnedChannels.splice(g,1),i.push(c)):o.push(c);const E=this._pinnedChannels.findIndex(x=>(r.get(x.url)??1/0)>u),v=E===-1?this._pinnedChannels.length:E;this._pinnedChannels.splice(v,0,c)}return{addedChannels:o,updatedChannels:i,unmatchedChannelUrls:a}}_upsertRegularChannelsToArray(t,n=!1){const r=[],o=[],i=[];for(const a of t){if(!this._query.belongsTo(a)){r.push(a.url);continue}const l=fn(this._channels,a),c=l<0;!c&&this._channels.splice(l,1);const g=Ts(this._channels,a,this._order).place,p=g===this._channels.length;c?p?(n||!this.hasMore)&&(this._channels.push(a),o.push(a)):(this._channels.splice(g,0,a),o.push(a)):(this._channels.splice(g,0,a),i.push(a))}return{addedChannels:o,updatedChannels:i,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var p,E,v,x,_;const r=new Set(((p=this.filter)==null?void 0:p.pinnedChannelUrls)??[]),o=[],i=[];for(const f of t)r.has(f.url)?o.push(f):i.push(f);const a=this._upsertPinnedChannelsToArray(o),l=this._upsertRegularChannelsToArray(i,n),c=a.addedChannels.concat(l.addedChannels),u=a.updatedChannels.concat(l.updatedChannels),g=a.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((v=(E=this._collectionEventHandler)==null?void 0:E.onChannelsAdded)==null||v.call(E,{},c)),u.length>0&&((_=(x=this._collectionEventHandler)==null?void 0:x.onChannelsUpdated)==null||_.call(x,{},u)),g.length>0&&this._removeChannelsFromView(g)}_removeChannelsFromView(t){var o,i,a;const n=new Set(((o=this.filter)==null?void 0:o.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(u=>u.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(u=>u.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((a=(i=this._collectionEventHandler)==null?void 0:i.onChannelsDeleted)==null||a.call(i,{},r))}get channels(){return this._isDisposed?[]:[...this._pinnedChannels,...this._channels]}get hasMore(){return this._isDisposed?!1:this._query.hasNext}async loadMore(){if(this._isDisposed)return[];if(this.hasMore){const t=await this._query.next();return this._setDefaultChangelogsSyncTimestamp(t),this._addChannelsToView(t,!0),t}return[]}setConversationListCollectionHandler(t){this._collectionEventHandler=t}dispose(){this._isDisposed||(this._isDisposed=!0,this._throttledOnChannelChanged.cancel(),this._collectionEventHandler=void 0,this._sdk.removeConnectionHandler(this._handlerId),this._sdk.groupChannel.removeGroupChannelHandler(this._handlerId),this._pinnedChannels.length=0,this._channels.length=0)}}const fn=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Ts=(e,t,n)=>{if(e.length>0){const r=fn(e,t);let o=0,i=e.length-1,a=Math.floor((o+i)/2);for(;o<i;){const c=Jn(e[a],t,n);if(c>0)i=a,a=Math.floor((o+i)/2);else if(c<0)o=a+1,a=Math.floor((o+i)/2);else return{place:a,oldPosition:r}}return{place:Jn(e[a],t,n)>=0?a:a+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},Jn=(e,t,n)=>{switch(n){case ot.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const r=t.lastMessage.createdAt-e.lastMessage.createdAt;return r===0?t.createdAt-e.createdAt:r}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};class Kr{constructor(t){C(this,"subscribers",{});this.logger=t}async send(t){const n=Is(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(i=>i(t.payload));await Promise.all(o).catch(i=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,i)})}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 Is=()=>{let e=be,t=be;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var ue=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e))(ue||{});class at{constructor(t={}){C(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Ue={CloseConversation:e=>new ws(e),MessengerSettingsUpdated:e=>new ks(e),ActiveChannelUpdated:e=>new Ms(e),AnonymousSessionTokenExpired:()=>new $s,AuthTokenRefreshed:()=>new Ls};class ws extends at{constructor(){super(...arguments);C(this,"type","conv.close")}}class ks extends at{constructor(){super(...arguments);C(this,"type","messenger.settings.updated")}}class Ms extends at{constructor(){super(...arguments);C(this,"type","active.channel.updated")}}class $s extends at{constructor(){super(...arguments);C(this,"type","anon.token.expired")}}class Ls extends at{constructor(){super(...arguments);C(this,"type","auth.token.refreshed")}}var wn=(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))(wn||{});class jr{constructor(t){C(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${je}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${je}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${je}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${je}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${je}/error]`,...t)}}class Yr{constructor({userId:t,authToken:n,sessionHandler:r}){C(this,"userId");C(this,"authToken");C(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class pn{constructor(){C(this,"userId");C(this,"authToken");C(this,"sessionHandler")}}const Rs=e=>({onSessionTokenRequired:t=>{t(null),e.send(Ue.AnonymousSessionTokenExpired())}}),Os="ai_agent:stats",Ds="conversation_initial_render",Ns=800220;var Z=(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))(Z||{});class Ps{constructor(){C(this,"timers",new Map);C(this,"committed",!1);C(this,"commitCallback",null);C(this,"conversationId",null);C(this,"channelUrl",null);C(this,"errorCode",null);C(this,"errorDescription",null);C(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??Ns,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(Os,t)):!1}}class Fs extends Ps{constructor(){super(...arguments);C(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Ds}buildPayload(){const n=this.getDuration(Z.AUTH),r=this.getDuration(Z.GET_CHANNEL),o=this.getDuration(Z.GET_MESSAGES),i=this.getDuration(Z.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(Z.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},...i!==null&&{total_duration_from_cache:i}},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 Bs{constructor(t){C(this,"commitCallback");C(this,"presentMethod","direct_present");C(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Fs().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(Z.TOTAL_DURATION).startTimer(Z.TOTAL_DURATION_FROM_CACHE).startTimer(Z.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(Z.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(Z.AUTH).setError(t instanceof X.SendbirdError?t.code:void 0,t.message).stopTimer(Z.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(Z.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(Z.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(Z.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(Z.GET_CHANNEL).setError(t instanceof X.SendbirdError?t.code:void 0,t.message).stopTimer(Z.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof X.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(Z.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof X.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(Z.TOTAL_DURATION).stopTimer(Z.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 Us(){let e=null,t=0;const n=(r,o)=>{if((e==null?void 0:e.key)===r)return e.promise;const i=++t,l=(e?e.promise.catch(()=>{}).then(()=>o()):o()).finally(()=>{(e==null?void 0:e.id)===i&&(e=null)});return e={key:r,id:i,promise:l},l};return n.isPending=()=>e!==null,n}const Te={conversation:{isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0,messageAlertSoundEnabled:!1,header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Qn=e=>{var t,n,r,o,i,a,l,c,u,g,p,E,v,x;return e?{...Te,...e,conversation:{...Te.conversation,...e==null?void 0:e.conversation,header:{...(t=Te.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=Te.conversation)==null?void 0:r.input,...(o=e==null?void 0:e.conversation)==null?void 0:o.input,camera:{...(a=(i=Te.conversation)==null?void 0:i.input)==null?void 0:a.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(g=(u=Te.conversation)==null?void 0:u.input)==null?void 0:g.gallery,...(E=(p=e==null?void 0:e.conversation)==null?void 0:p.input)==null?void 0:E.gallery}},fileViewer:{...(v=Te.conversation)==null?void 0:v.fileViewer,...(x=e==null?void 0:e.conversation)==null?void 0:x.fileViewer}}}:Te},me=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===ee.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},kn=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===ee.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function He(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 Hs(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!He(e):!1}function Vs(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function er(e){return!!e&&e<Date.now()}function zs(e){return!e.title}function Gs(e,t){var n;if(e)return zs(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 Ws{constructor(){C(this,"_channelHandlerId",null);C(this,"_connectionHandlerId",null);C(this,"_handleActiveChannelChangedThrottled",null);C(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Wr(o=>{var i,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:me(o)?"closed":"open",conversationStatus:(i=o.conversation)==null?void 0:i.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",o.url)},250,{leading:!0,trailing:!1});const n=new ot.GroupChannelHandler({onChannelChanged:o=>{var i,a;o.isGroupChannel()&&o.url===((i=this._session)==null?void 0:i.activeChannel.url)&&((a=this._handleActiveChannelChangedThrottled)==null||a.call(this,o))}}),r=new X.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})});C(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")});C(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:me(a)?"closed":"open",conversationStatus:(r=a.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",a.url))}catch(i){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",i)}});C(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)}});C(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(ue.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(ue.MessengerSettingsUpdated,t)}));C(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(ue.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(ue.ActiveChannelUpdated,t)}));C(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(ue.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(ue.AuthTokenRefreshed,t)}))}}class qs{constructor(t){C(this,"_sdkUser");C(this,"_userSession");C(this,"_dispatcher");C(this,"_activeChannel");C(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Ue.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});C(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Ue.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 Zr=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)}},lt=e=>JSON.parse(e),Bt=e=>JSON.parse(e);function Ks(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function js(e){const t={};function n(r,o=""){for(const[i,a]of Object.entries(r)){const l=o?`${o}.${i}`:i;a&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t[l]=a}}return n(e),t}function Mn({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((o,[i,a])=>{if(!r&&!["number","boolean","string"].includes(typeof a))throw new Error(`If transformer is not provided, value(${i}:${a}) must be a {string, number, or boolean}`);const l=r?r(a):String(a),c=n(i);return o.replace(c,Zr(l))},e)}async function Ys({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([i,a])=>{const l=await r(a);return{regex:n(i),transformedValue:l}}))).reduce((i,{regex:a,transformedValue:l})=>i.replace(a,Zr(l)),e)}var En=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(En||{});const Xr=e=>typeof e=="object"&&e!==null,tr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Zs=e=>!Xr(e)||!tr(e,"channel_url")||!tr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Xs={1:Zs};function Js(e){if(!Xr(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Xs[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Qs(e,t,n,r){const o=ms.default.init({appId:e,modules:[new ot.GroupChannelModule,new ee.AIAgentModule],localCacheEnabled:!0,options:new X.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:X.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function ei(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 ti=[400300,400301,400302,400310];class $n{constructor(t,n,r){C(this,"chatSDK");C(this,"_logger");C(this,"_cache");C(this,"connect",async(t,n,r,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const i=new X.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(i),this.chatSDK.aiAgent.addEventHandler(En.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=Js(a);(l==null?void 0:l.category)===En.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(i){const a=i;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}});C(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")});C(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));C(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));C(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));C(this,"requestMessengerSettings",async t=>{var o;if(t.userId===""){const i=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",i),i}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});C(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(o,i)=>{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(),i(a)})}});C(this,"_isCacheRestrictedError",t=>ti.some(n=>t.code===n));C(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:i,token:a}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of i){const{key:c}=lt(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(a),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(i){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",i)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(ei(t.chatSDK),n=t.chatSDK):n=Qs(t.appId,t.extensions,t.messengerVersion,t.chatParams),new $n(n,t.logger,t.cache)}}const Et=new Map,Jr={set:(e,t)=>{Et.set(e,t)},get:e=>{if(Et.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=Et.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Et.entries().next().value;return{platform:t[0],...t[1]}}},ni=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class nr extends Error{constructor(n,r){const o=(r==null?void 0:r.detail)??"";super(o||`Desk API error (${n})`);C(this,"status");C(this,"code");C(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=o}}var Ln=(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))(Ln||{}),Rn=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Rn||{}),Qr=(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))(Qr||{});const ri=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class oi{constructor(t){C(this,"_appId");C(this,"_apiHost");C(this,"_logger");C(this,"_credential",null);C(this,"_authRefreshPromise",null);C(this,"_onDeskTokenRefreshRequired",async()=>!1);C(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 i=await this._fetch(o,n);return r&&i.status===401?this._handleUnauthorized(i,o,n):this._toResult(i)});C(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});C(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});C(this,"_handleUnauthorized",async(t,n,r)=>{const o=await this._parseErrorCode(t);if(!ri(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)});C(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}});C(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))}:{}}));C(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));C(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));C(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));C(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new nr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new nr(t.status,{})}});C(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 wt{constructor(t,n){C(this,"id");C(this,"title");C(this,"status");C(this,"agent");C(this,"priority");C(this,"group");C(this,"firstResponseTime");C(this,"issuedAt");C(this,"customFields");C(this,"_client");C(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 wt({id:t.id,title:t.channelName??null,status:t.status2??Ln.INITIALIZED,agent:(()=>{var i;const o=(i=t.recentAssignment)==null?void 0:i.agent;return o?{userId:o.sendbirdId??"",name:o.displayName??"",profileUrl:o.photoThumbnailUrl??""}:null})(),priority:t.priority??Rn.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 On{constructor(t){C(this,"_logger");C(this,"_apiClient");C(this,"_onDeskTokenRefreshRequired");C(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);C(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}});C(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});C(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")});C(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return wt._fromResponse(n,this)});C(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:ni({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 wt._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new oi(t)}static init(t){return new On(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function si(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 ii=1440*60*1e3;function Fe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function ai(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class kt extends Ws{constructor(n){super();C(this,"appId");C(this,"aiAgentId");C(this,"_chatClient");C(this,"_deskClient");C(this,"_cache");C(this,"_logger");C(this,"_dispatcher");C(this,"_session",null);C(this,"language");C(this,"countryCode");C(this,"context");C(this,"queryParams");C(this,"_config");C(this,"_networkStateAdapter");C(this,"_forceCreateChannel");C(this,"_agentVersion");C(this,"_statsTrackers");C(this,"_operationQueue",Us());C(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"))});C(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));C(this,"authenticate",n=>{const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var a,l,c,u,g;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const o=this._getSessionCandidate(n),i=(a=o.userSessionCandidate)!=null&&a.userId?this._cache.messenger.getSettings(o.userSessionCandidate.userId):null;i!=null&&i.bot&&this._dispatcher.send(Ue.MessengerSettingsUpdated({settings:i,source:"cache"}));try{const p=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=i==null?void 0:i.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let E;if(p.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."),E={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:_,session_token:f,expire_at:b}=p.auto_created_user;this._cache.messenger.setAnonUser({userId:_,authToken:f,expireAt:b}),E={userId:_,authToken:f},this._logger.debug("AIAgent.authenticate: anonymous user created",_)}else E={userId:((u=o.userSessionCandidate)==null?void 0:u.userId)??"",authToken:((g=o.userSessionCandidate)==null?void 0:g.authToken)??""};this._cache.messenger.setSettings(E.userId,p),this._dispatcher.send(Ue.MessengerSettingsUpdated({settings:p,source:"server"}));const v=(()=>{var _;return o.type==="anonymous"?Rs(this._dispatcher):(_=o.userSessionCandidate)==null?void 0:_.sessionHandler})(),x=await this._chatClient.connect(E,v,_=>{var f;this._logger.debug("AIAgent: session token refreshed"),(f=this._session)==null||f._updateAuthToken(_),this._deskClient.refreshDeskAuthToken(_)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:E.userId,accessToken:E.authToken,onDeskTokenRefreshRequired:async({reason:_})=>{var f;if(_===Qr.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,2e3));const b=(f=this._session)==null?void 0:f.userSession.authToken;return b?await this._deskClient.refreshDeskAuthToken(b):!1}return!1}}),(i==null?void 0:i.language)!==p.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new qs({sdkUser:x,userSession:E,activeChannel:{url:p.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:E.userId}),p}catch(p){throw this._statsTrackers.initialRender.onAuthError(p),p}})});C(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")}));C(this,"createConversation",async n=>{Fe(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});C(this,"searchConversation",async n=>{if(Fe(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:ee.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const i=await r.next();for(const a of i)ai(a.context??{},n.context)&&o.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:o.length}),o});C(this,"closeConversation",async n=>{var o;Fe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===ee.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:ee.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});C(this,"createConversationListCollection",n=>new qr(this.chatSDK,n??{}));C(this,"patchContext",async(n,r)=>{Fe(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??{}}});C(this,"updateContext",async(n,r)=>{Fe(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??{}}});C(this,"getContextObject",async n=>{Fe(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??{}}});C(this,"refreshActiveChannel",async n=>{var l,c,u;Fe(this._session);const r=this._session,o=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:o});const i=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"),((u=this._session)==null?void 0:u.activeChannel.url)??i.active_channel.channel_url;const a=i.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,i),this._session._updateActiveChannel({url:a,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",a),a});C(this,"_getSessionCandidate",n=>n instanceof Yr?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof pn?{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});C(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-ii<=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});C(this,"_getManualSessionInfo",n=>{if(!n||n instanceof pn)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=Qn(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 Bs((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var p;const r=Jr.get(n.platform),o=n.logger??new jr(n.logLevel??wn.WARN),i=n.dispatcher??new Kr(o),a=n.useMMKVStorage?si(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=As({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),u=$n.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}),g=On.init({appId:n.appId,logger:o,customApiHost:(p=n.deskParams)==null?void 0:p.customApiHost});return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new kt({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:u,deskClient:g,cache:c,logger:o,dispatcher:i})}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=Qn(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 te=(e,t)=>{const n=d.createContext(null),r=({children:a,value:l})=>s.createElement(n.Provider,{value:l},typeof a=="function"?a(l):a),o=({children:a})=>s.createElement(n.Consumer,null,l=>l?typeof a=="function"?a(l):a:null),i=()=>{const a=d.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`,i.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:i}};function fe(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:i}){const[a,l]=d.useState(()=>e.template),[c,u]=d.useState(e.components),g={Template:a,updateTemplate:p=>l(()=>p),components:c,updateComponent:(p,E)=>u(v=>({...v,[p]:E}))};return s.createElement(t.Provider,{value:g},i)}function r({template:i,children:a}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{i&&l(i)},[i]),s.createElement(s.Fragment,null,a)}function o({children:i}){return s.createElement(n,null,i)}return o.defaults=e,o.useContext=()=>d.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(i=>{o[i]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(i,l)},[l]),null}}),o}function li(...e){return function({children:n}){return e.reduce((r,o)=>s.createElement(o,null,r),n)}}function ci(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage()||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 di(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),i=Be.differenceInMinutes(r,o);return i<1?n.justNow:i<60?n.minutesAgo(i):Be.isToday(o)?n.hoursAgo(Be.differenceInHours(r,o)):t(o,n.dateShortFormat)}const ui=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},_t=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),rr=(e,t)=>{const n=_t(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=ui(e);return r?`#${_t(r[0])}${_t(r[1])}${_t(r[2])}${n}`:e},eo=te("AIAgent"),mi=eo.Provider,de=eo.useContext;function hi(e){const t=gi(e);return s.createElement(mi,{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}},e.children)}function gi(e){const t=d.useRef(null),n=d.useRef(null);if(!t.current||!n.current)t.current=kt.init(e);else{const o=fi(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=kt.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,d.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 fi(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 pi=(e,t,n)=>$e.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),st={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function to(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Ei(e){const t=to(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function _i(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function bi(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),i=r-o;let a=0,l=0;const c=(r+o)/2;return r!==o&&(l=c>.5?i/(2-r-o):i/(r+o)),r===e?a=(t-n)/i+(t<n?6:0):r===t?a=(n-e)/i+2:r===n&&(a=(e-t)/i+4),a/=6,[a,l,c]}function Ci(e,t,n){let r,o,i;if(t===0)r=o=i=n;else{const a=function(g,p,E){return E<0&&(E+=1),E>1&&(E-=1),E<.16666666666666666?g+(p-g)*6*E:E<.5?p:E<.6666666666666666?g+(p-g)*(.6666666666666666-E)*6:g},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),i=a(c,l,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(i*255)]}function bt(e,t,n){const[r,o,i]=Ei(e),[a,l,c]=bi(r,o,i),u=Math.max(0,Math.min(1,c*t)),g=Math.max(0,Math.min(1,l*n)),[p,E,v]=Ci(a,g,u);return _i([Math.round(p),Math.round(E),Math.round(v)])}function xi(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 _n(e){const t=to(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,i=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+i*.114>n?st.BLACK:st.WHITE}function vi(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}}}const yi=(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}}),Ct={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, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},nn={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 or(e){const t=Si(e),{colors:n,aiAgentColorVariables:r}=Ai(e,t),o=Ii(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:o}}function Si({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ct.primary.main?Ct.primary:xi(n,e):Ct.primary;return{...Ct,primary:r,...t}}function Ai({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const i=o.primary.main,a=t??_n(i),l=n??st.DEFAULT_BOT_MSG_BG,c=r??_n(l);return{colors:(e==="light"?vi:yi)(o,i,a,l,c),aiAgentColorVariables:{primary_color:i,bot_message_bg_color:l,primary_contrast_color:a,bot_message_bg_contrast_color:c}}}function Ti(e,t,n){const r={...e};return n.forEach(o=>{const i=t[o];i!=null&&(r[o]=i)}),r}function Ii({typography:e}){if(!e)return nn;const t={...nn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=nn[n],i=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Ti(o,r,i)}}),t}const{Provider:wi,useContext:Dn}=te("AIAgentTheme");function ki({logger:e,palette:t,typography:n,appearance:r,children:o}){const i=d.useRef(null),[a,l]=d.useState(()=>or({selectedTheme:(r==null?void 0:r.theme)??"light",palette:t,typography:n,primary:r==null?void 0:r.primaryColor,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor})),c=d.useCallback((u,g)=>{g&&(i.current=g);const p=(r==null?void 0:r.theme)??u,E=i.current?i.current.themes[p]:null,v={primary:r==null?void 0:r.primaryColor,primaryContrast:void 0,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!v.primary&&(E!=null&&E.primary_color)&&(v.primary=E.primary_color,v.primaryContrast=E.primary_contrast_color),!v.botMessageBackground&&(E!=null&&E.bot_message_bg_color)&&(v.botMessageBackground=E.bot_message_bg_color,v.botMessageBackgroundContrast=E.bot_message_bg_contrast_color);const x=or({selectedTheme:p,palette:t,typography:n,...v});l(x),e==null||e.info("theme.update:",p)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor,t,n,e]);return d.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&c(a.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),s.createElement(wi,{value:{theme:a,updateTheme:c}},o)}const rn=25*1024*1024,sr=1,ir=new Set(["image/png","image/jpeg","image/jpg"]),ar=new Set(["application/pdf"]),Mi={off:"off",always:"always",handed_off_only:"handed_off_only"},$i=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:sr,attachmentMode:"handed_off_only",defaultUploadSizeLimit:rn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:ir,supportedFileMimeTypes:ar})),n=d.useCallback(({active_channel:o,upload_restriction:i})=>{t({maxAttachmentCount:(i==null?void 0:i.max_attachment_count)??sr,attachmentMode:Mi[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(i==null?void 0:i.default_upload_size_limit)??rn,uploadSizeLimitPerType:new Map(Object.entries((i==null?void 0:i.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((i==null?void 0:i.supported_image_mime_types)??ir),supportedFileMimeTypes:new Set((i==null?void 0:i.supported_file_mime_types)??ar)})},[]),r=d.useCallback(o=>{const{channel:i,uploadSizeLimit:a=rn}=o,l=(u=!0)=>i!=null&&i.isAIAgent?u?He(i):!1:!0,c=u=>{if(l())return e.defaultUploadSizeLimit??a;const g=e.defaultUploadSizeLimit??a,p=e.uploadSizeLimitPerType.get(u)??g;return Math.min(g,p)};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 He(i);default:return!0}},get supportedMimeTypes(){return l()?[hn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:u=>l()?!0:e.supportedImageMimeTypes.has(u)||e.supportedFileMimeTypes.has(u),getUploadSizeLimit:c,getUploadSizeLimitInMB:u=>c(u)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},lr=(...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)")},Qe=e=>({...e,context:e.context??{}}),{Provider:Li,useContext:ct}=te("AIAgentMessengerSession"),Ri=d.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:i,logger:a}=de(),{updateTheme:l}=Dn(),[c,u]=d.useState(void 0),[g,p]=d.useState(void 0),[E,v]=d.useState(null),[x,_]=d.useState(null),[f,b]=d.useState(null),[y,w]=d.useState(null),{updateBaseAttachmentRules:A,createAttachmentRules:L}=$i();d.useEffect(()=>{const I=r.onMessengerSettingsUpdated(({settings:z})=>{const{appearance:Y,bot:G,launcher:ve}=z;l(Y.selected_theme,Y),b({userId:G.bot_userid,profileUrl:G.bot_profile_url,nickname:G.bot_nickname,replyToFile:G.reply_to_file,specialNotice:G.special_notice,specialNoticeEnabled:G.is_special_notice_enabled,showHandoffButton:G.show_handoff_button??!0,isMultipleActiveConversationsEnabled:G.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:G.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:G.is_user_feedback_comment_option_enabled??!1}),w({type:ve.image_type||"default_icon",imageUrl:ve.image_url}),A(z)}),U=r.onActiveChannelUpdated(({channelUrl:z,status:Y,conversationStatus:G})=>{p({url:z,status:Y,conversationStatus:G})}),N=r.onAuthTokenRefreshed(()=>{var Y;const z=(Y=r.session)==null?void 0:Y.userSession.authToken;z&&_(G=>G?{...G,authToken:z}:null)});return()=>{I(),U(),N()}},[r,l,A]);const $=d.useCallback(async()=>{u(void 0);try{const I=await r.authenticate(e),U=r.session;return v(U.sdkUser),_(U.userSession),p(U.activeChannel),I}catch(I){throw u(I),I}},[r,e]),S=d.useCallback(async()=>{await r.deauthenticate(),v(null),p(void 0),_(null),b(null),w(null)},[r]),R=d.useCallback(async()=>{if(!r.session){if(x)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!==(x==null?void 0:x.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(p(void 0),await r.refreshActiveChannel())},[r,a,x]),P=d.useCallback(async I=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(I)},[r]),O=d.useCallback(async I=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(I)},[r]);return d.useImperativeHandle(n,()=>{const I=async()=>{if(!g)throw new Error("No active conversation. Please start a conversation first.");return await o.groupChannel.getChannel(g.url)};return{activeChannel:g,chatSDK:o,authenticate:$,deauthenticate:S,updateContext:async(...U)=>{const N=lr(...U);if(N.type==="active"){const G=await(await I()).updateContext(i,N.context);return Qe(G)}const z=await o.aiAgent.updateContext(N.aiAgentId,N.channelUrl,N.context);return Qe(z)},patchContext:async(...U)=>{const N=lr(...U);if(N.type==="active"){const G=await(await I()).patchContext(i,N.context);return Qe(G)}const z=await o.aiAgent.patchContext(N.aiAgentId,N.channelUrl,N.context);return Qe(z)},getContextObject:async()=>{const N=await(await I()).getContextObject(i);return Qe(N)}}},[$,S,g,o,i,a]),s.createElement(Li,{value:{sdkUser:E,userSessionInfo:e,userSession:x,activeChannel:g,setActiveChannel:p,refreshActiveChannel:R,createConversation:P,searchConversation:O,connectionError:c,aiAgentInfo:f,launcherInfo:y,authenticate:$,deauthenticate:S,createAttachmentRules:L,statsTrackers:r.statsTrackers}},t)}),Nn=(e,t)=>{const n=d.useId(),r=d.useRef(t);d.useLayoutEffect(()=>{r.current=t}),d.useEffect(()=>{const o=new X.ConnectionHandler({onDisconnected:i=>{var a,l;return(l=(a=r.current).onDisconnected)==null?void 0:l.call(a,i)},onConnected:i=>{var a,l;return(l=(a=r.current).onConnected)==null?void 0:l.call(a,i)},onReconnectStarted:()=>{var i,a;return(a=(i=r.current).onReconnectStarted)==null?void 0:a.call(i)},onReconnectSucceeded:()=>{var i,a;return(a=(i=r.current).onReconnectSucceeded)==null?void 0:a.call(i)},onReconnectFailed:()=>{var i,a;return(a=(i=r.current).onReconnectFailed)==null?void 0:a.call(i)},onConnectionLost:()=>{var i,a;return(a=(i=r.current).onConnectionLost)==null?void 0:a.call(i)},onConnectionDelayed:i=>{var a,l;return(l=(a=r.current).onConnectionDelayed)==null?void 0:l.call(a,i)}});return e.addConnectionHandler(n,o),()=>{e.removeConnectionHandler(n)}},[e,n])};function Oi(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=de(),{sdkUser:i,statsTrackers:a}=ct(),l=$e.useForceUpdate(),[c,u]=d.useState(void 0),[g,p]=d.useState(void 0),[E,v]=d.useState(!1);function x(f){f.isAIAgent&&!f.conversation&&(v(!0),o.initConversationIfNeeded(f).finally(()=>v(!1)))}async function _(){var f,b,y;if(!i){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),u(void 0),p(void 0),v(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const w=await t.groupChannel.getChannel(e);x(w),u(w),a.initialRender.onGetChannelComplete((f=w.conversation)==null?void 0:f.id),w.url===((b=o.session)==null?void 0:b.activeChannel.url)&&o.session._updateActiveChannel({url:w.url,status:me(w)?"closed":"open",conversationStatus:(y=w.conversation)==null?void 0:y.status}),n.debug("useChannel.getChannel: fetched channel",w)}catch(w){a.initialRender.onGetChannelError(w),w instanceof X.SendbirdError&&p(w),n.error("useChannel.getChannel: error",w)}}}return d.useEffect(()=>{_()},[t,i,e,r]),Nn(t,{async onReconnectSucceeded(){if(!c)return;const f=await c.refresh();x(f),u(f)}}),$e.useGroupChannelHandler(t,{onChannelChanged:f=>{f.isGroupChannel()&&f.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",f.url),u(f),l())}}),{channel:c,channelFetchError:g,getChannel:_,isInitializingConversation:E}}const Di=new Set(["suggested_replies","steward","system"]),Ni=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||!Di.has(r)))return r},Pi=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,i=e.isAIAgent&&!!((a=e.conversation)!=null&&a.handedOverAt);return o&&!i},Fi=()=>{const{chatSDK:e,networkStateAdapter:t}=de(),[n,r]=d.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Nn(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),d.useEffect(()=>{if(t)return t.subscribe(o=>{if(!o){r("reconnecting");return}r(i=>i==="reconnecting"&&e.connectionState===X.ConnectionState.OPEN?"connected":i)})},[t,e]),n},Bi=3e4,Ui=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,i]=d.useState(!1),a=d.useRef(null),l=t&&it(t,r)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),i(!1)},u=E=>{a.current&&clearTimeout(a.current),i(!0),a.current=setTimeout(()=>{i(!1),a.current=null},E)},g=Date.now()-l,p=Bi-g;return n||p<=0?c():u(p),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},no=e=>{const{chatSDK:t}=de(),[n,r]=d.useState([]);return $e.useGroupChannelHandler(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const i=o.getTypingUsers();r(i)}}}),n},Hi=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,i]=d.useState(!1),a=no(e);return d.useEffect(()=>{if(!t)return;const l=a.some(u=>u.userId===n),c=it(t,n)&&(ke.isStreaming(t)||r);i(c||l)},[a,t,n,r]),o},Vi=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:i}=ct(),a=Fi(),l=Hi({channel:e,lastMessage:Xn(t,[we.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=Ui({shouldApply:!!(e!=null&&e.isAIAgent)&&!He(e),isBlockedWhileAIResponding:l,lastMessage:Xn(t,[we.SendingStatus.PENDING,we.SendingStatus.SUCCEEDED]),currentUserId:(i==null?void 0:i.userId)??""});if(!e||a==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(a==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(me(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Hs(e))return{disabled:!0,disabledBy:"handoff_pending"};if(Pi(e))return{disabled:!0,disabledBy:"form_active"};const u=Ni(e);return u?{disabled:!0,disabledBy:u}:l||c||r?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},zi=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(o=>{t(i=>{if(i.has(o))return i;const a=new Set(i);return a.add(o),a})},[]),r=d.useCallback(o=>{t(i=>{if(!i.has(o))return i;const a=new Set(i);return a.delete(o),a})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Gi}=te("AIAgentConversation");function Wi({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:i,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=be,shouldMarkAsRead:u=!0,shouldCountNewMessages:g=()=>!1,sortComparator:p}){var O;const E=()=>u&&(f==null?void 0:f.markAsRead()),{chatSDK:v,logger:x,dispatcher:_}=de(),{channel:f,channelFetchError:b,getChannel:y,isInitializingConversation:w}=Oi(t),{statsTrackers:A}=ct();d.useEffect(()=>{if(t)return A.initialRender.setChannelUrl(t),()=>{A.initialRender.cleanup()}},[t,A]);const L=pi(v,f,{replyType:we.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:g,onChannelDeleted:n,onMessagesReceived:I=>r==null?void 0:r(I),onMessagesUpdated:I=>o==null?void 0:o(I),onCacheResult:I=>A.initialRender.onCacheResult(I),onApiResult:I=>A.initialRender.onApiResult(I),logger:x,markAsRead:E,sortComparator:p}),$=zi(),S=Vi({channel:f,messages:L.messages,isStreamAnimating:$.isAnimating,isInitializingConversation:w});d.useEffect(()=>{E()},[u,f]);const R=me(f);d.useEffect(()=>{i==null||i(R)},[R,i]),d.useEffect(()=>{const I=async U=>{const N=typeof(U==null?void 0:U.channelUrl)=="string";f&&N&&U.channelUrl!==f.url||(x.debug("conversation.dispatcher: try to close conversation",f),f!=null&&f.conversation&&f.conversation.status===ee.ConversationStatus.OPEN&&(await f.closeConversation(),a==null||a()))};return _.subscribe(ue.ConversationClose,I),()=>{_.unsubscribe(ue.ConversationClose,I)}},[_,f,x,(O=f==null?void 0:f.conversation)==null?void 0:O.status,a]);const P={conversation:(f==null?void 0:f.conversation)??void 0,channelSource:{channel:f,error:b,refetch:()=>y(),closeConversation:async()=>{me(f)||await(f==null?void 0:f.closeConversation())}},messageSource:{messages:L.messages,newMessages:L.newMessages,initialized:L.initialized,loadPrevious:()=>L.loadPrevious(),loadNext:()=>L.loadNext(),deleteMessage:I=>L.deleteMessage(I),resendMessage:I=>L.resendMessage(I),resetNewMessages:()=>L.resetNewMessages(),sendUserMessage:async I=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(I=await l(I));const U=await L.sendUserMessage(I,c);return c==null||c(U),U},sendFileMessage:async I=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(I=await l(I));const U=await L.sendFileMessage(I,c);return c==null||c(U),U},sendMultipleFilesMessage:async I=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(I=await l(I));const U=await L.sendMultipleFilesMessage(I,c);return c==null||c(U),U}},state:{streamAnimation:$,input:S}};return s.createElement(Gi,{value:P},e)}function qi(e,t){var v,x,_,f,b,y,w,A,L,$;const[n,r]=d.useState(!1),[o,i]=d.useState(null),[a,l]=d.useState([]),[c,u]=d.useState(null),g=d.useRef(!1),p=d.useCallback(async()=>{if(!g.current&&e.currentUser){g.current=!0,r(!1),i(null),l([]);try{c==null||c.dispose();const S=new qr(e,t);S.setConversationListCollectionHandler({onChannelsAdded:()=>{l(S.channels)},onChannelsUpdated:()=>{l(S.channels)},onChannelsDeleted:()=>{l(S.channels)}}),await S.loadMore(),u(S),i(null)}catch(S){u(null),i(S)}finally{r(!0),g.current=!1}}},[e,e.currentUser,(v=t.filter)==null?void 0:v.aiAgentChannelFilter,(_=(x=t.filter)==null?void 0:x.aiAgentConversationStatusFilter)==null?void 0:_.join(),(b=(f=t.filter)==null?void 0:f.aiAgentIds)==null?void 0:b.join(),(y=t.filter)==null?void 0:y.deskChannelFilter,(A=(w=t.filter)==null?void 0:w.pinnedChannelUrls)==null?void 0:A.join(),(L=t.filter)==null?void 0:L.copilotConversationOnly,($=t.filter)==null?void 0:$.copilotSupportChannelUrl,t.limit]),E=d.useCallback(async()=>{if(c)try{await c.loadMore()}catch(S){i(S)}},[c]);return Nn(e,{onConnected:()=>p()}),d.useEffect(()=>{p()},[p]),d.useEffect(()=>()=>{g.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:o,channels:a,loadMore:E}}const{Provider:Ki}=te("AIAgentConversationList");function ji({conversationListLimit:e,conversationListFilter:t,children:n}){var p,E;const{chatSDK:r,aiAgentId:o,queryParams:i}=de(),a={aiAgentIds:[o],aiAgentConversationStatusFilter:[ee.ConversationStatus.CLOSED,ee.ConversationStatus.OPEN]},l=e??((p=i==null?void 0:i.conversationListParams)==null?void 0:p.limit),c={...a,...(E=i==null?void 0:i.conversationListParams)==null?void 0:E.filter,...t},u=qi(r,{limit:l,filter:c}),g={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return s.createElement(Ki,{value:g},n)}function Yi(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:Zi,useContext:ro}=te("MessageTemplateFetching");function Xi({children:e,internalVariables:t}){const n=d.useRef({}),r=d.useRef({}),[o,i]=d.useState({}),a=d.useCallback((u,g)=>{i(p=>({...p,[u]:{fetching:!1,error:!1,...p[u],...g}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:g,templateKey:p,suspense:E=!1})=>{const v=g(p);if(v)return v;const x=r.current[p];if(x)return x;E||a(p,{fetching:!0});const _=u(p).catch(f=>{throw E||a(p,{error:!0}),f}).finally(()=>{E||a(p,{fetching:!1}),delete r.current[p]});return r.current[p]=_,_},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(u,g)=>{if(n.current[u])return n.current[u];const p=Yi(g());return n.current[u]=p,p},getIsFetching:u=>{var g;return((g=o[u])==null?void 0:g.fetching)??!1},getHasError:u=>{var g;return((g=o[u])==null?void 0:g.error)??!1}};return s.createElement(Zi,{value:c},e)}const Ut={VARIABLE:e=>new RegExp(`\\{${e}\\}`,"g"),VIEW_VARIABLE:e=>new RegExp(`"{@${e}}"`,"g")};function Re({uiTemplateString:e,variables:t={}}){const n=js(t);return Mn({template:e,variables:n,variableKeyPattern:r=>Ut.VARIABLE(r)})}function Oe({theme:e,uiTemplateString:t,colorVariables:n={}}){return Mn({template:t,variables:n,variableKeyPattern:r=>Ut.VARIABLE(r),variableValueTransformer:r=>Ks(e,r)})}function Ji({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:o,onRequestTemplate:i}){const l=Object.values(n).flat().map(u=>u.key);return[...new Set(l)].some(u=>!i(u))?null:Mn({template:t,variables:n,variableKeyPattern:u=>Ut.VIEW_VARIABLE(u),variableValueTransformer:u=>{const g=u.map(({key:p,variables:E})=>{const v=i(p),{ui_template:x,color_variables:_}=lt(v);let f=JSON.stringify(x);return f=Re({uiTemplateString:f,variables:o}),f=Oe({theme:e,uiTemplateString:f,colorVariables:_}),f=Oe({theme:e,uiTemplateString:f,colorVariables:r}),f=Re({uiTemplateString:f,variables:E}),Bt(f)});return JSON.stringify(g)}})}async function Qi({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:o,onRequestTemplate:i}){return Ys({template:t,variables:n,variableKeyPattern:a=>Ut.VIEW_VARIABLE(a),variableValueTransformer:async a=>{const l=a.map(async({key:u,variables:g})=>{const p=await i(u),{ui_template:E,color_variables:v}=lt(p);let x=JSON.stringify(E);return x=Re({uiTemplateString:x,variables:o}),x=Oe({theme:e,uiTemplateString:x,colorVariables:v}),x=Oe({theme:e,uiTemplateString:x,colorVariables:r}),x=Re({uiTemplateString:x,variables:g}),Bt(x)}),c=await Promise.all(l);return JSON.stringify(c)}})}const ea=({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:o,color_variables:i}=lt(e);let a=JSON.stringify(o);if(Object.keys(r.viewVariables??{}).length>0){const c=Ji({...r,uiTemplateString:a,aiAgentColorVariables:t,internalVariables:n});if(c===null)return null;a=c}return a=Re({...r,uiTemplateString:a,variables:n}),a=Oe({...r,uiTemplateString:a,colorVariables:i}),a=Oe({...r,uiTemplateString:a,colorVariables:t}),a=Re({...r,uiTemplateString:a}),Bt(a)},ta=async({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:o,color_variables:i}=lt(e);let a=JSON.stringify(o);return Object.keys(r.viewVariables??{}).length>0&&(a=await Qi({...r,uiTemplateString:a,aiAgentColorVariables:t,internalVariables:n})),a=Re({...r,uiTemplateString:a,variables:n}),a=Oe({...r,uiTemplateString:a,colorVariables:i}),a=Oe({...r,uiTemplateString:a,colorVariables:t}),a=Re({...r,uiTemplateString:a}),Bt(a)},na=e=>{const{aiAgentColorVariables:t={}}=e,{internalVariables:n}=ro();return d.useState(()=>{const r=e.onGetCachedTemplate(e.templateKey);return r?ea({...e,rawTemplate:r,aiAgentColorVariables:t,internalVariables:n,onRequestTemplate:e.onGetCachedTemplate}):null})},ra=e=>{const[t]=na(e);if(t)return t;const{aiAgentColorVariables:n={}}=e,{internalVariables:r,fetchTemplate:o,suspend:i}=ro();return i(e.templateKey,async()=>{const l=await o({...e,suspense:!0});return await ta({...e,rawTemplate:l,aiAgentColorVariables:n,internalVariables:r})}).value},oa="remove_powered_by",Pn=(e,t)=>{var o,i;const{chatSDK:n}=de(),{aiAgentInfo:r}=ct();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&&kn(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const a=(i=n==null?void 0:n.appInfo)==null?void 0:i.applicationAttributes;return d.useMemo(()=>!(Array.isArray(a)&&a.includes(oa)),[a])}throw new Error("Unsupported feature")},sa={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"},ia={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}}},aa={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}}},la={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}}},ca={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:i}=e;if(i){if(i.min_select!==void 0&&r.length<i.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(i.min_select):n.minSelect};if(i.max_select!==void 0&&r.length>i.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(i.max_select):n.maxSelect}}return{isValid:!0}}},da={text:ia,number:aa,"single-select":la,"multi-select":ca},ua={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function oo(e){return da[e.type]||ua}function cr(e){return oo(e).getValueOrDefault(e)}function ma(e,t,n={}){const r={...sa,...n};return oo(e).validate(e,t,r)}const ha=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[i,a]=d.useState({}),[l,c]=d.useState(()=>{const _={};return e.fields.forEach(f=>{_[f.key]=cr(f)}),_}),u=d.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);d.useEffect(()=>{if(u==="submitted"||u==="canceled"){const _={};let f=!1;e.fields.forEach(b=>{const y=cr(b);JSON.stringify(l[b.key])!==JSON.stringify(y)&&(f=!0),_[b.key]=y}),f&&c(_)}},[u]);const g=(_,f)=>{c(b=>({...b,[_]:f})),a(b=>({...b,[_]:void 0}))},p=e.fields.map(_=>{var y,w,A;const f=l[_.key]??null,b={key:_.key,label:_.label,error:i[_.key],required:_.required};return _.type==="text"?{...b,type:"text",layout:_.layout,value:f,..._.placeholder&&{placeholder:_.placeholder},...((y=_.rules)==null?void 0:y.max_length)&&{maxLength:_.rules.max_length}}:_.type==="number"?{...b,type:"number",layout:_.layout,value:f,..._.placeholder&&{placeholder:_.placeholder},...((w=_.rules)==null?void 0:w.max)&&{max:_.rules.max}}:_.type==="single-select"?{...b,type:"single-select",layout:_.layout,value:f,options:_.options}:_.type==="multi-select"?{...b,type:"multi-select",layout:_.layout,value:f,options:_.options,...((A=_.rules)==null?void 0:A.max_select)&&{maxSelect:_.rules.max_select}}:{...b,type:"unknown",layout:"default",value:null}});return{state:u,fields:p,getField:_=>p.find(f=>f.key===_),updateFieldValue:g,submit:async()=>{const _={};let f=!1;for(const b of e.fields){const y=l[b.key]??null,w=ma(b,y,n);w.isValid||(_[b.key]=w.error,f=!0)}if(a(_),!f&&r){const b={};e.fields.forEach(y=>{b[y.key]=l[y.key]??null}),await r(b)}},cancel:async()=>{await(o==null?void 0:o())}}},ga=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},fa=e=>{const{aiAgentInfo:t}=ct(),r=no(e)[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),i=o?ga(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:i}},so=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[i]=e.members.filter(a=>a.userId!==t.userId);return i})(),o={ai(i){return{fallbackIcon:i,url:n.profileUrl,title:n.nickname}},human(i){return{fallbackIcon:i,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(i){return{fallbackIcon:i,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?He(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},dr=e=>d.useReducer((t,n)=>({...t,...n}),e);var he=(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))(he||{});const pa=new Set(["free_text","single_choice"]),Ea=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[i,a]=dr({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=dr({followUpItem:!1}),u=d.useMemo(()=>{var f;const v=i.csat,x=typeof v=="number",_=(f=e.follow_up)==null?void 0:f.find(b=>x?b.scores.includes(v):b.always_visible??!1);if(pa.has(_==null?void 0:_.response_type))return _},[i.csat,e.follow_up]),g=(()=>{var v;if(typeof n=="number")return"submitted";if((t===he.AI_AGENT_CSAT_5||t===he.HELPDESK_CSAT_5)&&typeof i.csat=="number")return"submittable";if(t===he.AI_AGENT_CSAT_5_WITH_CRE){const x=typeof i.csat=="number",_=!((v=e.cre)!=null&&v.required)||typeof i.isResolved=="boolean";if(x&&_)return"submittable"}return"unsubmittable"})(),p=d.useCallback(()=>typeof i.csat>"u"?!1:u!=null&&u.required&&!i.csatReason?(c({followUpItem:!0}),!1):!0,[i,u,c]);return d.useEffect(()=>{r||(a({csatReason:""}),c({followUpItem:!1}))},[r,u,a,c]),{params:i,setParams:a,error:l,setError:c,followUpItem:u,state:g,validateParams:p,itemProps:{csatPayload:e,state:g,submitted:g==="submitted"}}},on=5,_a=250,ba=50,ur=e=>Math.max(0,e-ba),Ca=e=>e<1e3?{speed:on*.5,chunkSize:2}:e<2e3?{speed:on*.8,chunkSize:2}:{speed:on*.6,chunkSize:3},xa=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:o,onAnimationComplete:i}=e,[a,l]=d.useState(()=>ur(t.length)),c=d.useRef(null),u=d.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,g=d.useRef({onStart:r,onProgress:o,onComplete:i}).current,p=d.useRef({startCalled:!1,completeCalled:!1}).current,E=d.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,v=n,x=a<t.length,_=E.initialEnabled&&(v||x);return d.useLayoutEffect(()=>{g.onStart=r,g.onProgress=o,g.onComplete=i,E.textLength=t.length,E.enabled=n}),d.useLayoutEffect(()=>{var f;E.initialEnabled&&(p.startCalled||(p.startCalled=!0,(f=g.onStart)==null||f.call(g)),l(b=>t.length<b?t.length:b))},[t]),d.useEffect(()=>{if(!E.initialEnabled)return;let f=ur(t.length);u.lastUpdate=0,u.startTime=0,u.lastProgressCall=0;const b=y=>{var O;u.lastUpdate===0&&(u.lastUpdate=y,u.startTime=y,u.lastProgressCall=y);const w=E.textLength,A=y-u.lastUpdate,L=y-u.startTime,{speed:$,chunkSize:S}=Ca(L),R=$*S;A>=R&&f<w&&(f=Math.min(f+S,w),l(f),u.lastUpdate=y),y-u.lastProgressCall>=_a&&(u.lastProgressCall=y,(O=g.onProgress)==null||O.call(g)),(f<w||E.enabled)&&(c.current=requestAnimationFrame(b))};return c.current=requestAnimationFrame(b),()=>{var y;c.current&&cancelAnimationFrame(c.current),p.startCalled&&!p.completeCalled&&(p.completeCalled=!0,(y=g.onComplete)==null||y.call(g))}},[]),d.useEffect(()=>{var w;const f=E.initialEnabled&&p.startCalled,b=!n,y=a>=t.length&&t.length>0;f&&b&&y&&!p.completeCalled&&(p.completeCalled=!0,(w=g.onComplete)==null||w.call(g))},[n,a,t.length]),{streamText:E.initialEnabled?t.slice(0,a):t,isAnimating:_}},va="1.21.3",ce="sb-agent",ae={ENTRY:`${ce}-entry`,MODAL_ROOT:`${ce}-modal-root`,WINDOW:`${ce}-window`,LAUNCHER:`${ce}-launcher`},xt=2147483647,ze={MODAL:xt-1,TOOLTIP:xt-2,WINDOW:xt-3,LAUNCHER:xt-4},io=36,ya=100,Sa=va,Fn="noopener noreferrer nofollow";function Aa(){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 vt={};function Ta(){return{get:e=>{try{return localStorage.getItem(e)}catch{return vt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{vt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete vt[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(vt).filter(t=>t.startsWith(e))}}}}const Ia='@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}',wa={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.",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"},conversation_list:{header_title:"Conversations",ended:"Ended",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`},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."},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"},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"}},bn={language:"en",strings:wa,dateLocale:ss.enUS},ao=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__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,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,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,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}),ka=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Ht},Ht="en",Ma=new Set([Ht,"ko","es","pt","fr","hi","it","de","tr","ja"]),$a=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((o,i)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(i.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},mr=ao(bn.strings),La={...mr,HEADER_BUTTON__AGENT_HANDOFF:"Connect with an agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__CANCEL:"Cancel",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_UPLOAD_FILES:"Files",FILE_VIEWER__UNSUPPORT:"Unsupported message",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",A11Y_ATTACH_FILE:"Attach file",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:mr.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",BUTTON__OK:"OK",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},Mt={language:bn.language,dateLocale:bn.dateLocale,stringSet:La},Ra=Object.freeze(Object.defineProperty({__proto__:null,default:Mt},Symbol.toStringTag,{value:"Module"})),Cn=new Map([[Ht,Mt]]);async function Oa(e){const t=Cn.get(e);if(t)return t;try{if(Ma.has(e)){const{default:n}=await $a(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/cDxb_gcv.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Ra),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/CSOR33ij.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/Cdz9XkkI.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/zu820q6g.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/BqsoHLlP.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/Ba_JKDGK.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/DR4bCizU.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/DW6lSsOu.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/B8e5M4M9.cjs"))}),`./languages/${e}.ts`,3);return Cn.set(e,n),n}return Mt}catch{return Mt}}const{Provider:Da,useContext:K}=te("Localization"),Na=({language:e=navigator.language,logger:t,stringSet:n,children:r})=>{const[o,i]=d.useState(Cn.get(Ht));return d.useEffect(()=>{const a=ka(e);o.language!==a&&(t==null||t.debug("localization.useEffect: update language",{from:o.language,to:a}),Oa(a).then(i))},[e,t]),s.createElement(Da,{value:{language:o.language,stringSet:{...o.stringSet,...n},dateLocale:o.dateLocale,format:(a,l,c)=>Be.format(a,l,{locale:o.dateLocale,...c})}},r)},$t="data-sb-agent-theme",hr=e=>(t,...n)=>{let r="";return t.forEach((o,i)=>{r+=o+(n[i]??"")}),`[${$t}='${e}'] & { ${r} }`},B={light:hr("light"),dark:hr("dark")},Pa=M.css(({theme:e})=>{const{palette:t}=e;return`
|
|
1
|
+
"use strict";var yi=Object.defineProperty;var Si=(e,t,n)=>t in e?yi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var A=(e,t,n)=>Si(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("@sendbird/chat"),c=require("react"),R=require("styled-components"),We=require("date-fns"),Ai=require("date-fns/locale/en-US"),qe=require("@sendbird/chat/message"),Ee=require("@sendbird/chat/aiAgent"),gt=require("@sendbird/chat/groupChannel"),Ye=require("@sendbird/uikit-tools"),xi=require("react-dom"),Ti=require("date-fns/isSameDay"),Fn=require("@sendbird/react-uikit-message-template-view"),Ii=require("@sendbird/uikit-message-template"),wi=require("dompurify"),ki=require("@emotion/is-prop-valid"),dn=e=>e&&e.__esModule?e:{default:e};function Li(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 Mi=dn(ie),i=Li(c),_=dn(R),Fo=dn(wi),Oi=dn(ki),ut="sb-agent",Bo="KEY_IMG_ASPECT_RATIO",Bn="*/*",Y={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 Qt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Qt||{}),St=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(St||{});const Ho=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Ri=e=>e===St.COMPLETED||e===St.CANCELED?e:St.IN_PROGRESS,Sn=e=>Oe(e)&&!Ho(e),Oe=e=>!!e&&"sender"in e,Ni=e=>Oe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),kr=(e,t)=>!e||!t?!1:Oe(e)&&Oe(t)?e.messageId>0&&t.messageId>0?e.messageId===t.messageId:e.reqId.length>0&&e.reqId===t.reqId:e.messageId>0&&e.messageId===t.messageId,Di=(e,t,n,r=!0)=>{if(!r||!Sn(e))return"single";const o=()=>{if(!Sn(t))return!1;const u=t.sender.userId===e.sender.userId,d=We.isSameMinute(t.createdAt,e.createdAt);return u&&d},s=()=>{if(!Sn(n))return!1;const u=n.sender.userId===e.sender.userId,d=We.isSameMinute(n.createdAt,e.createdAt);return u&&d},a=o(),l=s();return a&&l?"middle":a?"bottom":l?"top":"single"},Tt=(e,t)=>(()=>{var r;return Oe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,pe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Ho(e),isIncoming:(e,t)=>Oe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Oe(e)&&(e.sender.userId===t||e.sendingStatus===qe.SendingStatus.PENDING)},ze=e=>e.startsWith("image/"),Uo=e=>e.startsWith("video/"),Qn=(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"},Vo=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},mn=e=>{switch(e){case"top":case"middle":return Y.GAP_GROUPED;default:return Y.GAP_UNGROUPED}},$i=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(s,...a)=>{const[l,u,d]=a;return o<d&&r.push({type:"text",value:e.slice(o,d).trim()}),r.push({type:"code",value:u.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},Pi=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Fi=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Bi=e=>e.replace(/~~/g,"\\~\\~"),Hi=e=>{let t=e;return t=Pi(t),t=Fi(t),t=Bi(t),t},Ui=typeof navigator<"u"&&navigator.product==="ReactNative",Lr=(e,t)=>{const n=r=>!t||t.length===0?!0:Oe(r)&&t.includes(r.sendingStatus);return Ui?e.find(n):e.findLast(n)};function oe(){}function Vi(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Gi(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 Hn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},$e={isStreaming(e){const t=Hn(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(Tt(e,t)){const r=Hn(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=`@${ut}`,zi=({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=Gi(`${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}}}}},Go=(e,t,n={})=>{let r=null,o=null,s=null;const{leading:a=!0,trailing:l=!0}=n,u=(...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 h=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},u};class zo{constructor(t,{filter:n,limit:r=20}){A(this,"filter");A(this,"_sdk");A(this,"_pinnedChannels");A(this,"_channels");A(this,"_isDisposed",!1);A(this,"_handlerId",`handler-id-${Date.now()}`);A(this,"_order",gt.GroupChannelListOrder.LATEST_LAST_MESSAGE);A(this,"_limit");A(this,"_query");A(this,"_token");A(this,"_timestamp");A(this,"_isSyncing");A(this,"_channelHandler");A(this,"_connectionHandler");A(this,"_collectionEventHandler");A(this,"_throttledOnChannelChanged");var o,s,a,l,u,d,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(o=this.filter)==null?void 0:o.aiAgentChannelFilter,aiAgentConversationStatusFilter:(s=this.filter)==null?void 0:s.aiAgentConversationStatusFilter,aiAgentIds:(a=this.filter)==null?void 0:a.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(u=this.filter)==null?void 0:u.pinnedChannelUrls,copilotConversationOnly:(d=this.filter)==null?void 0:d.copilotConversationOnly,copilotSupportChannelUrl:(m=this.filter)==null?void 0:m.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=Go(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new gt.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new ie.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var s,a;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let o;r?o=((a=r.lastMessage)==null?void 0:a.createdAt)??r.createdAt:o=this._query.lastResponseAt,this._timestamp>o&&(this._timestamp=o)}async _syncChannelChangelogs(){if(this._isDisposed)return[];if(this._isSyncing)return[];try{this._isSyncing=!0;let t;for(this._token?t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter):t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByTimestamp(this._timestamp,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls);t.hasMore&&t.token;)t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls)}catch{}finally{this._isSyncing=!1}return[]}_upsertPinnedChannelsToArray(t){var l;const n=((l=this.filter)==null?void 0:l.pinnedChannelUrls)??[],r=new Map(n.map((u,d)=>[u,d])),o=[],s=[],a=[];for(const u of t){if(!this._query.belongsTo(u)){a.push(u.url);continue}const d=r.get(u.url);if(d===void 0)continue;const m=Un(this._pinnedChannels,u);m>=0?(this._pinnedChannels.splice(m,1),s.push(u)):o.push(u);const g=this._pinnedChannels.findIndex(b=>(r.get(b.url)??1/0)>d),C=g===-1?this._pinnedChannels.length:g;this._pinnedChannels.splice(C,0,u)}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:a}}_upsertRegularChannelsToArray(t,n=!1){const r=[],o=[],s=[];for(const a of t){if(!this._query.belongsTo(a)){r.push(a.url);continue}const l=Un(this._channels,a),u=l<0;!u&&this._channels.splice(l,1);const m=Wi(this._channels,a,this._order).place,h=m===this._channels.length;u?h?(n||!this.hasMore)&&(this._channels.push(a),o.push(a)):(this._channels.splice(m,0,a),o.push(a)):(this._channels.splice(m,0,a),s.push(a))}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var h,g,C,b,v;const r=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),o=[],s=[];for(const f of t)r.has(f.url)?o.push(f):s.push(f);const a=this._upsertPinnedChannelsToArray(o),l=this._upsertRegularChannelsToArray(s,n),u=a.addedChannels.concat(l.addedChannels),d=a.updatedChannels.concat(l.updatedChannels),m=a.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);u.length>0&&((C=(g=this._collectionEventHandler)==null?void 0:g.onChannelsAdded)==null||C.call(g,{},u)),d.length>0&&((v=(b=this._collectionEventHandler)==null?void 0:b.onChannelsUpdated)==null||v.call(b,{},d)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var o,s,a;const n=new Set(((o=this.filter)==null?void 0:o.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const u=this._pinnedChannels.findIndex(d=>d.url===l);u>=0&&(r.push(l),this._pinnedChannels.splice(u,1))}else{const u=this._channels.findIndex(d=>d.url===l);u>=0&&(r.push(l),this._channels.splice(u,1))}r.length>0&&((a=(s=this._collectionEventHandler)==null?void 0:s.onChannelsDeleted)==null||a.call(s,{},r))}get channels(){return this._isDisposed?[]:[...this._pinnedChannels,...this._channels]}get hasMore(){return this._isDisposed?!1:this._query.hasNext}async loadMore(){if(this._isDisposed)return[];if(this.hasMore){const t=await this._query.next();return this._setDefaultChangelogsSyncTimestamp(t),this._addChannelsToView(t,!0),t}return[]}setConversationListCollectionHandler(t){this._collectionEventHandler=t}dispose(){this._isDisposed||(this._isDisposed=!0,this._throttledOnChannelChanged.cancel(),this._collectionEventHandler=void 0,this._sdk.removeConnectionHandler(this._handlerId),this._sdk.groupChannel.removeGroupChannelHandler(this._handlerId),this._pinnedChannels.length=0,this._channels.length=0)}}const Un=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Wi=(e,t,n)=>{if(e.length>0){const r=Un(e,t);let o=0,s=e.length-1,a=Math.floor((o+s)/2);for(;o<s;){const u=Mr(e[a],t,n);if(u>0)s=a,a=Math.floor((o+s)/2);else if(u<0)o=a+1,a=Math.floor((o+s)/2);else return{place:a,oldPosition:r}}return{place:Mr(e[a],t,n)>=0?a:a+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},Mr=(e,t,n)=>{switch(n){case gt.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const r=t.lastMessage.createdAt-e.lastMessage.createdAt;return r===0?t.createdAt-e.createdAt:r}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};class Wo{constructor(t){A(this,"subscribers",{});this.logger=t}async send(t){const n=qi(),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 qi=()=>{let e=oe,t=oe;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var Me=(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))(Me||{});class It{constructor(t={}){A(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const rt={CloseConversation:e=>new Ki(e),MessengerSettingsUpdated:e=>new Yi(e),ActiveChannelUpdated:e=>new ji(e),AnonymousSessionTokenExpired:()=>new Xi,AuthTokenRefreshed:()=>new Zi};class Ki extends It{constructor(){super(...arguments);A(this,"type","conv.close")}}class Yi extends It{constructor(){super(...arguments);A(this,"type","messenger.settings.updated")}}class ji extends It{constructor(){super(...arguments);A(this,"type","active.channel.updated")}}class Xi extends It{constructor(){super(...arguments);A(this,"type","anon.token.expired")}}class Zi extends It{constructor(){super(...arguments);A(this,"type","auth.token.refreshed")}}var er=(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))(er||{});class qo{constructor(t){A(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${ut}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${ut}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${ut}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${ut}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${ut}/error]`,...t)}}class Ko{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 Vn{constructor(){A(this,"userId");A(this,"authToken");A(this,"sessionHandler")}}const Ji=e=>({onSessionTokenRequired:t=>{t(null),e.send(rt.AnonymousSessionTokenExpired())}}),Qi="ai_agent:stats",ea="conversation_initial_render",ta=800220;var ae=(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))(ae||{});class na{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??ta,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(Qi,t)):!1}}class ra extends na{constructor(){super(...arguments);A(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return ea}buildPayload(){const n=this.getDuration(ae.AUTH),r=this.getDuration(ae.GET_CHANNEL),o=this.getDuration(ae.GET_MESSAGES),s=this.getDuration(ae.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(ae.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}},u={key:this.getMetricKey(),value:a!==null?String(a):"0"};return this.conversationId!==null&&(u.conversation_id=this.conversationId),this.errorCode!==null&&(u.error_code=this.errorCode),this.errorDescription!==null&&(u.error_description=this.errorDescription),Object.keys(l).length>0&&(u.extra=l),u}}class oa{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 ra().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(ae.TOTAL_DURATION).startTimer(ae.TOTAL_DURATION_FROM_CACHE).startTimer(ae.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(ae.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ae.AUTH).setError(t instanceof ie.SendbirdError?t.code:void 0,t.message).stopTimer(ae.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(ae.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(ae.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(ae.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ae.GET_CHANNEL).setError(t instanceof ie.SendbirdError?t.code:void 0,t.message).stopTimer(ae.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ie.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ae.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ie.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ae.TOTAL_DURATION).stopTimer(ae.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 sa(){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 Ge={conversation:{isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0,messageAlertSoundEnabled:!1,header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Or=e=>{var t,n,r,o,s,a,l,u,d,m,h,g,C,b;return e?{...Ge,...e,conversation:{...Ge.conversation,...e==null?void 0:e.conversation,header:{...(t=Ge.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=Ge.conversation)==null?void 0:r.input,...(o=e==null?void 0:e.conversation)==null?void 0:o.input,camera:{...(a=(s=Ge.conversation)==null?void 0:s.input)==null?void 0:a.camera,...(u=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:u.camera},gallery:{...(m=(d=Ge.conversation)==null?void 0:d.input)==null?void 0:m.gallery,...(g=(h=e==null?void 0:e.conversation)==null?void 0:h.input)==null?void 0:g.gallery}},fileViewer:{...(C=Ge.conversation)==null?void 0:C.fileViewer,...(b=e==null?void 0:e.conversation)==null?void 0:b.fileViewer}}}:Ge},Se=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ee.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},tr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ee.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function je(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 ia(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!je(e):!1}function aa(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Rr(e){return!!e&&e<Date.now()}function la(e){return!e.title}function ca(e,t){var n;if(e)return la(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 ua{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=Go(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:Se(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 gt.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 ie.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:Se(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(Me.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Me.MessengerSettingsUpdated,t)}));A(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Me.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Me.ActiveChannelUpdated,t)}));A(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Me.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Me.AuthTokenRefreshed,t)}))}}class da{constructor(t){A(this,"_sdkUser");A(this,"_userSession");A(this,"_dispatcher");A(this,"_activeChannel");A(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(rt.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});A(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(rt.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 Yo=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)}},wt=e=>JSON.parse(e),hn=e=>JSON.parse(e);function ma(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function ha(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 nr({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),u=n(s);return o.replace(u,Yo(l))},e)}async function ga({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,Yo(l)),e)}var Gn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Gn||{});const jo=e=>typeof e=="object"&&e!==null,Nr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",fa=e=>!jo(e)||!Nr(e,"channel_url")||!Nr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},pa={1:fa};function _a(e){if(!jo(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=pa[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Ea(e,t,n,r){const o=Mi.default.init({appId:e,modules:[new gt.GroupChannelModule,new Ee.AIAgentModule],localCacheEnabled:!0,options:new ie.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:ie.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function ba(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 Ca=[400300,400301,400302,400310];class rr{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 ie.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 u;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=_a(a);(l==null?void 0:l.category)===Gn.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(u=n==null?void 0:n.onExternalAuthTokenExpired)==null||u.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,"_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=>Ca.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:u}=wt(l);this._cache.template.set(u,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?(ba(t.chatSDK),n=t.chatSDK):n=Ea(t.appId,t.extensions,t.messengerVersion,t.chatParams),new rr(n,t.logger,t.cache)}}const Pt=new Map,Xo={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]}}},va=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class Dr 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 or=(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))(or||{}),sr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(sr||{}),Zo=(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))(Zo||{});const ya=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Sa{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(!ya(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 Dr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Dr(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 en{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 en({id:t.id,title:t.channelName??null,status:t.status2??or.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??sr.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 ir{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 en._fromResponse(n,this)});A(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:va({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return en._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Sa(t)}static init(t){return new ir(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function Aa(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 xa=1440*60*1e3;function tt(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Ta(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class tn extends ua{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",sa());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,u,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(rt.MessengerSettingsUpdated({settings:s,source:"cache"}));try{const h=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:(u=s==null?void 0:s.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let g;if(h.auto_created_user)if(o.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),g={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:v,session_token:f,expire_at:y}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:f,expireAt:y}),g={userId:v,authToken:f},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else g={userId:((d=o.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=o.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,h),this._dispatcher.send(rt.MessengerSettingsUpdated({settings:h,source:"server"}));const C=(()=>{var v;return o.type==="anonymous"?Ji(this._dispatcher):(v=o.userSessionCandidate)==null?void 0:v.sessionHandler})(),b=await this._chatClient.connect(g,C,v=>{var f;this._logger.debug("AIAgent: session token refreshed"),(f=this._session)==null||f._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:g.userId,accessToken:g.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var f;if(v===Zo.ERR_SESSION_KEY_EXPIRED){await new Promise(E=>setTimeout(E,2e3));const y=(f=this._session)==null?void 0:f.userSession.authToken;return y?await this._deskClient.refreshDeskAuthToken(y):!1}return!1}}),(s==null?void 0:s.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new da({sdkUser:b,userSession:g,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:g.userId}),h}catch(h){throw this._statsTrackers.initialRender.onAuthError(h),h}})});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=>{tt(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),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(tt(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:Ee.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const s=await r.next();for(const a of s)Ta(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;tt(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===Ee.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Ee.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});A(this,"createConversationListCollection",n=>new zo(this.chatSDK,n??{}));A(this,"patchContext",async(n,r)=>{tt(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)=>{tt(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=>{tt(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,"refreshActiveChannel",async n=>{var l,u,d;tt(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?(u=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??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 Ko?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Vn?{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-xa<=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 Vn)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=Or(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 oa((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var h;const r=Xo.get(n.platform),o=n.logger??new qo(n.logLevel??er.WARN),s=n.dispatcher??new Wo(o),a=n.useMMKVStorage?Aa(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=zi({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=rr.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:u}),m=ir.init({appId:n.appId,logger:o,customApiHost:(h=n.deskParams)==null?void 0:h.customApiHost});return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new tn({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:u,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=Or(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 me=(e,t)=>{const n=c.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=c.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 Pe(e){const t=c.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){const[a,l]=c.useState(()=>e.template),[u,d]=c.useState(e.components),m={Template:a,updateTemplate:h=>l(()=>h),components:u,updateComponent:(h,g)=>d(C=>({...C,[h]:g}))};return i.createElement(t.Provider,{value:m},s)}function r({template:s,children:a}){const{updateTemplate:l}=c.useContext(t);return c.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=()=>c.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(s=>{o[s]=function({component:l}){const{updateComponent:u}=c.useContext(t);return c.useLayoutEffect(()=>{l&&u(s,l)},[l]),null}}),o}function Ia(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function wa(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Jo(e,t)}function Jo(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 ka(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=We.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):We.isToday(o)?n.hoursAgo(We.differenceInHours(r,o)):t(o,n.dateShortFormat)}const La=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"),$r=(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=La(e);return r?`#${Ft(r[0])}${Ft(r[1])}${Ft(r[2])}${n}`:e},Qo=me("AIAgent"),Ma=Qo.Provider,ke=Qo.useContext;function Oa(e){const t=Ra(e);return i.createElement(Ma,{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}},e.children)}function Ra(e){const t=c.useRef(null),n=c.useRef(null);if(!t.current||!n.current)t.current=tn.init(e);else{const o=Na(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=tn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,c.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 Na(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 Pr=Symbol("conversationMessageEventBridge"),bt=Symbol("conversationMessageEventPublisher"),Da=(e,t)=>{const n=e;if(n[bt]=t,n[Pr])return e;n[Pr]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=s=>{r({...s,onMessagesAdded:(a,l,u)=>{var d,m;(d=s.onMessagesAdded)==null||d.call(s,a,l,u),(m=n[bt])==null||m.call(n,{kind:"messagesAdded",source:a.source,messages:u})},onMessagesUpdated:(a,l,u)=>{var d,m;(d=s.onMessagesUpdated)==null||d.call(s,a,l,u),(m=n[bt])==null||m.call(n,{kind:"messagesUpdated",source:a.source,messages:u})}})};const o=e.initialize.bind(e);return e.initialize=s=>{const a=o(s),l=a.onCacheResult.bind(a),u=a.onApiResult.bind(a);return a.onCacheResult=d=>l((m,h)=>{var g;d(m,h),(g=n[bt])==null||g.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),a.onApiResult=d=>u((m,h)=>{var g;d(m,h),(g=n[bt])==null||g.call(n,{kind:"initialized",source:"api",messages:h??[]})}),a},e},$a=(e,t,n)=>{const r=c.useRef(0),o=c.useRef(new Set),s=c.useCallback(d=>{const m={id:r.current+=1,...d};o.current.forEach(h=>{h(m)})},[]),a=c.useCallback(d=>{var h;const m=((h=n==null?void 0:n.collectionCreator)==null?void 0:h.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new gt.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return Da(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=Ye.useGroupChannelMessages(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),u=c.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:u}},xt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function es(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Pa(e){const t=es(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Fa(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Ba(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 u=(r+o)/2;return r!==o&&(l=u>.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,u]}function Ha(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const a=function(m,h,g){return g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(h-m)*6*g:g<.5?h:g<.6666666666666666?m+(h-m)*(.6666666666666666-g)*6:m},l=n<.5?n*(1+t):n+t-n*t,u=2*n-l;r=a(u,l,e+1/3),o=a(u,l,e),s=a(u,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]=Pa(e),[a,l,u]=Ba(r,o,s),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,l*n)),[h,g,C]=Ha(a,m,d);return Fa([Math.round(h),Math.round(g),Math.round(C)])}function Ua(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=es(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?xt.BLACK:xt.WHITE}function Va(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}}}const Ga=(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}}),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, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",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 Fr(e){const t=za(e),n=Wa(e,t),r=Ka(n,e.colors,e.selectedTheme),o=ja(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 za({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ht.primary.main?Ht.primary:Ua(n,e):Ht.primary;return{...Ht,primary:r,...t}}function Wa({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??zn(s),l=n??xt.DEFAULT_BOT_MSG_BG,u=r??zn(l);return(e==="light"?Va:Ga)(o,s,a,l,u)}function qa(e,t,n){return typeof e=="string"?e:e[t]??n}function Ka(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 u=t[l];if(u){o[l]={...o[l]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((a=s[l])==null?void 0:a[d])??"";o[l][d]=qa(m,n,h)}}}return r}function Ya(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function ja({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]=Ya(o,r,s)}}),t}const{Provider:Xa,useContext:ar}=me("AIAgentTheme");function Za({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=c.useRef(null),[l,u]=c.useState(()=>Fr({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=c.useCallback((m,h)=>{h&&(a.current=h);const g=(o==null?void 0:o.theme)??m,C=a.current?a.current.themes[g]:null,b={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!b.primary&&(C!=null&&C.primary_color)&&(b.primary=C.primary_color,b.primaryContrast=C.primary_contrast_color),!b.botMessageBackground&&(C!=null&&C.bot_message_bg_color)&&(b.botMessageBackground=C.bot_message_bg_color,b.botMessageBackgroundContrast=C.bot_message_bg_contrast_color);const v=Fr({selectedTheme:g,palette:t,typography:n,colors:r,...b});u(v),e==null||e.info("theme.update:",g)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor,t,n,r,e]);return c.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(Xa,{value:{theme:l,updateTheme:d}},s)}const Tn=25*1024*1024,Br=1,Hr=new Set(["image/png","image/jpeg","image/jpg"]),Ur=new Set(["application/pdf"]),Ja={off:"off",always:"always",handed_off_only:"handed_off_only"},Qa=()=>{const[e,t]=c.useState(()=>({maxAttachmentCount:Br,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Tn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Hr,supportedFileMimeTypes:Ur})),n=c.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??Br,attachmentMode:Ja[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)??Hr),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??Ur)})},[]),r=c.useCallback(o=>{const{channel:s,uploadSizeLimit:a=Tn}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?je(s):!1:!0,u=d=>{if(l())return e.defaultUploadSizeLimit??a;const m=e.defaultUploadSizeLimit??a,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};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 je(s);default:return!0}},get supportedMimeTypes(){return l()?[Bn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},Vr=(...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:el,useContext:kt}=me("AIAgentMessengerSession"),tl=c.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=ke(),{updateTheme:l}=ar(),[u,d]=c.useState(void 0),[m,h]=c.useState(void 0),[g,C]=c.useState(null),[b,v]=c.useState(null),[f,y]=c.useState(null),[E,x]=c.useState(null),{updateBaseAttachmentRules:S,createAttachmentRules:I}=Qa();c.useEffect(()=>{const L=r.onMessengerSettingsUpdated(({settings:w})=>{const{appearance:$,bot:O,launcher:q}=w;l($.selected_theme,$),y({userId:O.bot_userid,profileUrl:O.bot_profile_url,nickname:O.bot_nickname,replyToFile:O.reply_to_file,specialNotice:O.special_notice,specialNoticeEnabled:O.is_special_notice_enabled,showHandoffButton:O.show_handoff_button??!0,isMultipleActiveConversationsEnabled:O.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:O.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:O.is_user_feedback_comment_option_enabled??!1}),x({type:q.image_type||"default_icon",imageUrl:q.image_url}),S(w)}),P=r.onActiveChannelUpdated(({channelUrl:w,status:$,conversationStatus:O})=>{h({url:w,status:$,conversationStatus:O})}),N=r.onAuthTokenRefreshed(()=>{var $;const w=($=r.session)==null?void 0:$.userSession.authToken;w&&v(O=>O?{...O,authToken:w}:null)});return()=>{L(),P(),N()}},[r,l,S]);const k=c.useCallback(async()=>{try{const L=await r.authenticate(e),P=r.session;return C(P.sdkUser),v(P.userSession),h(P.activeChannel),d(void 0),L}catch(L){throw C(null),v(null),h(void 0),d(L),L}},[r,e]),M=c.useCallback(async()=>{await r.deauthenticate(),C(null),h(void 0),v(null),y(null),x(null)},[r]),U=c.useCallback(async()=>{if(!r.session){if(b)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!==(b==null?void 0:b.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,a,b]),F=c.useCallback(async L=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(L)},[r]),G=c.useCallback(async L=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(L)},[r]);return c.useImperativeHandle(n,()=>{const L=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:k,deauthenticate:M,updateContext:async(...P)=>{const N=Vr(...P);if(N.type==="active"){const O=await(await L()).updateContext(s,N.context);return Ct(O)}const w=await o.aiAgent.updateContext(N.aiAgentId,N.channelUrl,N.context);return Ct(w)},patchContext:async(...P)=>{const N=Vr(...P);if(N.type==="active"){const O=await(await L()).patchContext(s,N.context);return Ct(O)}const w=await o.aiAgent.patchContext(N.aiAgentId,N.channelUrl,N.context);return Ct(w)},getContextObject:async()=>{const N=await(await L()).getContextObject(s);return Ct(N)}}},[k,M,m,o,s,a]),i.createElement(el,{value:{sdkUser:g,userSessionInfo:e,userSession:b,activeChannel:m,setActiveChannel:h,refreshActiveChannel:U,createConversation:F,searchConversation:G,connectionError:u,aiAgentInfo:f,launcherInfo:E,authenticate:k,deauthenticate:M,createAttachmentRules:I,statsTrackers:r.statsTrackers}},t)}),lr=(e,t)=>{const n=c.useId(),r=c.useRef(t);c.useLayoutEffect(()=>{r.current=t}),c.useEffect(()=>{const o=new ie.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 nl(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=ke(),{sdkUser:s,statsTrackers:a}=kt(),l=Ye.useForceUpdate(),[u,d]=c.useState(void 0),[m,h]=c.useState(void 0),[g,C]=c.useState(!1);function b(f){f.isAIAgent&&!f.conversation&&(C(!0),o.initConversationIfNeeded(f).finally(()=>C(!1)))}async function v(){var f,y,E;if(!s){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),h(void 0),C(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const x=await t.groupChannel.getChannel(e);b(x),d(x),a.initialRender.onGetChannelComplete((f=x.conversation)==null?void 0:f.id),x.url===((y=o.session)==null?void 0:y.activeChannel.url)&&o.session._updateActiveChannel({url:x.url,status:Se(x)?"closed":"open",conversationStatus:(E=x.conversation)==null?void 0:E.status}),n.debug("useChannel.getChannel: fetched channel",x)}catch(x){a.initialRender.onGetChannelError(x),x instanceof ie.SendbirdError&&h(x),n.error("useChannel.getChannel: error",x)}}}return c.useEffect(()=>{v()},[t,s,e,r]),lr(t,{async onReconnectSucceeded(){if(!u)return;const f=await u.refresh();b(f),d(f)}}),Ye.useGroupChannelHandler(t,{onChannelChanged:f=>{f.isGroupChannel()&&f.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",f.url),d(f),l())}}),{channel:u,channelFetchError:m,getChannel:v,isInitializingConversation:g}}const rl=new Set(["suggested_replies","steward","system"]),ol=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||!rl.has(r)))return r},sl=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},il=()=>{const{chatSDK:e,networkStateAdapter:t}=ke(),[n,r]=c.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return lr(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),c.useEffect(()=>{if(t)return t.subscribe(o=>{if(!o){r("reconnecting");return}r(s=>s==="reconnecting"&&e.connectionState===ie.ConnectionState.OPEN?"connected":s)})},[t,e]),n},al=3e4,ll=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,s]=c.useState(!1),a=c.useRef(null),l=t&&Tt(t,r)?t.createdAt:0;return c.useEffect(()=>{const u=()=>{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,h=al-m;return n||h<=0?u():d(h),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},ts=e=>{const{chatSDK:t}=ke(),[n,r]=c.useState([]);return Ye.useGroupChannelHandler(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},cl=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=c.useState(!1),a=ts(e);return c.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),u=Tt(t,n)&&($e.isStreaming(t)||r);s(u||l)},[a,t,n,r]),o},ul=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=kt(),a=il(),l=cl({channel:e,lastMessage:Lr(t,[qe.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),u=ll({shouldApply:!!(e!=null&&e.isAIAgent)&&!je(e),isBlockedWhileAIResponding:l,lastMessage:Lr(t,[qe.SendingStatus.PENDING,qe.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""}),d=(h,g)=>({_mode:h,disabled:h!=="enabled",disabledBy:g});if(!e||a==="disconnected")return d("disabled","unavailable");if(a==="reconnecting")return d("disabled","reconnecting");if(Se(e))return d("disabled","conversation_closed");if(ia(e))return d("disabled","handoff_pending");if(sl(e))return d("disabled","form_active");const m=ol(e);return m?d("disabled",m):l||u||r?d("readOnly","ai_responding"):d("enabled","")},dl=()=>{const[e,t]=c.useState(new Set),n=c.useCallback(o=>{t(s=>{if(s.has(o))return s;const a=new Set(s);return a.add(o),a})},[]),r=c.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:ml}=me("AIAgentConversation");function hl({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:u=oe,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var G;const g=()=>d&&(f==null?void 0:f.markAsRead()),{chatSDK:C,logger:b,dispatcher:v}=ke(),{channel:f,channelFetchError:y,getChannel:E,isInitializingConversation:x}=nl(t),{statsTrackers:S}=kt();c.useEffect(()=>{if(t)return S.initialRender.setChannelUrl(t),()=>{S.initialRender.cleanup()}},[t,S]);const I=$a(C,f,{replyType:qe.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:L=>r==null?void 0:r(L),onMessagesUpdated:L=>o==null?void 0:o(L),onCacheResult:L=>S.initialRender.onCacheResult(L),onApiResult:L=>S.initialRender.onApiResult(L),logger:b,markAsRead:g,sortComparator:h}),k=dl(),M=ul({channel:f,messages:I.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:x});c.useEffect(()=>{g()},[d,f]);const U=Se(f);c.useEffect(()=>{s==null||s(U)},[U,s]),c.useEffect(()=>{const L=async P=>{const N=typeof(P==null?void 0:P.channelUrl)=="string";f&&N&&P.channelUrl!==f.url||(b.debug("conversation.dispatcher: try to close conversation",f),f!=null&&f.conversation&&f.conversation.status===Ee.ConversationStatus.OPEN&&(await f.closeConversation(),a==null||a()))};return v.subscribe(Me.ConversationClose,L),()=>{v.unsubscribe(Me.ConversationClose,L)}},[v,f,b,(G=f==null?void 0:f.conversation)==null?void 0:G.status,a]);const F={conversation:(f==null?void 0:f.conversation)??void 0,channelSource:{channel:f,error:y,refetch:()=>E(),closeConversation:async()=>{Se(f)||await(f==null?void 0:f.closeConversation())}},messageSource:{messages:I.messages,newMessages:I.newMessages,initialized:I.initialized,subscribeMessageEvents:I.subscribeMessageEvents,loadPrevious:()=>I.loadPrevious(),loadNext:()=>I.loadNext(),deleteMessage:L=>I.deleteMessage(L),resendMessage:L=>I.resendMessage(L),resetNewMessages:()=>I.resetNewMessages(),sendUserMessage:async L=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const P=await I.sendUserMessage(L,u);return u==null||u(P),P},sendFileMessage:async L=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const P=await I.sendFileMessage(L,u);return u==null||u(P),P},sendMultipleFilesMessage:async L=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const P=await I.sendMultipleFilesMessage(L,u);return u==null||u(P),P}},state:{streamAnimation:k,input:M}};return i.createElement(ml,{value:F},e)}function gl(e,t){var C,b,v,f,y,E,x,S,I,k;const[n,r]=c.useState(!1),[o,s]=c.useState(null),[a,l]=c.useState([]),[u,d]=c.useState(null),m=c.useRef(!1),h=c.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),s(null),l([]);try{u==null||u.dispose();const M=new zo(e,t);M.setConversationListCollectionHandler({onChannelsAdded:()=>{l(M.channels)},onChannelsUpdated:()=>{l(M.channels)},onChannelsDeleted:()=>{l(M.channels)}}),await M.loadMore(),d(M),s(null)}catch(M){d(null),s(M)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(C=t.filter)==null?void 0:C.aiAgentChannelFilter,(v=(b=t.filter)==null?void 0:b.aiAgentConversationStatusFilter)==null?void 0:v.join(),(y=(f=t.filter)==null?void 0:f.aiAgentIds)==null?void 0:y.join(),(E=t.filter)==null?void 0:E.deskChannelFilter,(S=(x=t.filter)==null?void 0:x.pinnedChannelUrls)==null?void 0:S.join(),(I=t.filter)==null?void 0:I.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),g=c.useCallback(async()=>{if(u)try{await u.loadMore()}catch(M){s(M)}},[u]);return lr(e,{onConnected:()=>h()}),c.useEffect(()=>{h()},[h]),c.useEffect(()=>()=>{m.current=!1,u==null||u.dispose()},[u]),{initialized:n,error:o,channels:a,loadMore:g}}const{Provider:fl}=me("AIAgentConversationList");function pl({conversationListLimit:e,conversationListFilter:t,children:n}){var h,g;const{chatSDK:r,aiAgentId:o,queryParams:s}=ke(),a={aiAgentIds:[o],aiAgentConversationStatusFilter:[Ee.ConversationStatus.CLOSED,Ee.ConversationStatus.OPEN]},l=e??((h=s==null?void 0:s.conversationListParams)==null?void 0:h.limit),u={...a,...(g=s==null?void 0:s.conversationListParams)==null?void 0:g.filter,...t},d=gl(r,{limit:l,filter:u}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return i.createElement(fl,{value:m},n)}function _l(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:El,useContext:ns}=me("MessageTemplateFetching");function bl({children:e,internalVariables:t}){const n=c.useRef({}),r=c.useRef({}),[o,s]=c.useState({}),a=c.useCallback((d,m)=>{s(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),l=c.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const C=m(h);if(C)return C;const b=r.current[h];if(b)return b;g||a(h,{fetching:!0});const v=d(h).catch(f=>{throw g||a(h,{error:!0}),f}).finally(()=>{g||a(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[a]),u={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=_l(m());return n.current[d]=h,h},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(El,{value:u},e)}const gn={VARIABLE:e=>new RegExp(`\\{${e}\\}`,"g"),VIEW_VARIABLE:e=>new RegExp(`"{@${e}}"`,"g")};function Xe({uiTemplateString:e,variables:t={}}){const n=ha(t);return nr({template:e,variables:n,variableKeyPattern:r=>gn.VARIABLE(r)})}function Ze({theme:e,uiTemplateString:t,colorVariables:n={}}){return nr({template:t,variables:n,variableKeyPattern:r=>gn.VARIABLE(r),variableValueTransformer:r=>ma(e,r)})}function Cl({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:o,onRequestTemplate:s}){const l=Object.values(n).flat().map(d=>d.key);return[...new Set(l)].some(d=>!s(d))?null:nr({template:t,variables:n,variableKeyPattern:d=>gn.VIEW_VARIABLE(d),variableValueTransformer:d=>{const m=d.map(({key:h,variables:g})=>{const C=s(h),{ui_template:b,color_variables:v}=wt(C);let f=JSON.stringify(b);return f=Xe({uiTemplateString:f,variables:o}),f=Ze({theme:e,uiTemplateString:f,colorVariables:v}),f=Ze({theme:e,uiTemplateString:f,colorVariables:r}),f=Xe({uiTemplateString:f,variables:g}),hn(f)});return JSON.stringify(m)}})}async function vl({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:o,onRequestTemplate:s}){return ga({template:t,variables:n,variableKeyPattern:a=>gn.VIEW_VARIABLE(a),variableValueTransformer:async a=>{const l=a.map(async({key:d,variables:m})=>{const h=await s(d),{ui_template:g,color_variables:C}=wt(h);let b=JSON.stringify(g);return b=Xe({uiTemplateString:b,variables:o}),b=Ze({theme:e,uiTemplateString:b,colorVariables:C}),b=Ze({theme:e,uiTemplateString:b,colorVariables:r}),b=Xe({uiTemplateString:b,variables:m}),hn(b)}),u=await Promise.all(l);return JSON.stringify(u)}})}const yl=({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:o,color_variables:s}=wt(e);let a=JSON.stringify(o);if(Object.keys(r.viewVariables??{}).length>0){const u=Cl({...r,uiTemplateString:a,aiAgentColorVariables:t,internalVariables:n});if(u===null)return null;a=u}return a=Xe({...r,uiTemplateString:a,variables:n}),a=Ze({...r,uiTemplateString:a,colorVariables:s}),a=Ze({...r,uiTemplateString:a,colorVariables:t}),a=Xe({...r,uiTemplateString:a}),hn(a)},Sl=async({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:o,color_variables:s}=wt(e);let a=JSON.stringify(o);return Object.keys(r.viewVariables??{}).length>0&&(a=await vl({...r,uiTemplateString:a,aiAgentColorVariables:t,internalVariables:n})),a=Xe({...r,uiTemplateString:a,variables:n}),a=Ze({...r,uiTemplateString:a,colorVariables:s}),a=Ze({...r,uiTemplateString:a,colorVariables:t}),a=Xe({...r,uiTemplateString:a}),hn(a)},Al=e=>{const{aiAgentColorVariables:t={}}=e,{internalVariables:n}=ns();return c.useState(()=>{const r=e.onGetCachedTemplate(e.templateKey);return r?yl({...e,rawTemplate:r,aiAgentColorVariables:t,internalVariables:n,onRequestTemplate:e.onGetCachedTemplate}):null})},xl=e=>{const[t]=Al(e);if(t)return t;const{aiAgentColorVariables:n={}}=e,{internalVariables:r,fetchTemplate:o,suspend:s}=ns();return s(e.templateKey,async()=>{const l=await o({...e,suspense:!0});return await Sl({...e,rawTemplate:l,aiAgentColorVariables:n,internalVariables:r})}).value},Tl="remove_powered_by",cr=(e,t)=>{var o,s;const{chatSDK:n}=ke(),{aiAgentInfo:r}=kt();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&&tr(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 c.useMemo(()=>!(Array.isArray(a)&&a.includes(Tl)),[a])}throw new Error("Unsupported feature")},Il={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"},wl={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}}},kl={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}}},Ll={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}}},Ml={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}}},Ol={text:wl,number:kl,"single-select":Ll,"multi-select":Ml},Rl={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function rs(e){return Ol[e.type]||Rl}function Gr(e){return rs(e).getValueOrDefault(e)}function Nl(e,t,n={}){const r={...Il,...n};return rs(e).validate(e,t,r)}const Dl=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=c.useState({}),[l,u]=c.useState(()=>{const v={};return e.fields.forEach(f=>{v[f.key]=Gr(f)}),v}),d=c.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);c.useEffect(()=>{if(d==="submitted"||d==="canceled"){const v={};let f=!1;e.fields.forEach(y=>{const E=Gr(y);JSON.stringify(l[y.key])!==JSON.stringify(E)&&(f=!0),v[y.key]=E}),f&&u(v)}},[d]);const m=(v,f)=>{u(y=>({...y,[v]:f})),a(y=>({...y,[v]:void 0}))},h=e.fields.map(v=>{var E,x,S;const f=l[v.key]??null,y={key:v.key,label:v.label,error:s[v.key],required:v.required};return v.type==="text"?{...y,type:"text",layout:v.layout,value:f,...v.placeholder&&{placeholder:v.placeholder},...((E=v.rules)==null?void 0:E.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...y,type:"number",layout:v.layout,value:f,...v.placeholder&&{placeholder:v.placeholder},...((x=v.rules)==null?void 0:x.max)&&{max:v.rules.max}}:v.type==="single-select"?{...y,type:"single-select",layout:v.layout,value:f,options:v.options}:v.type==="multi-select"?{...y,type:"multi-select",layout:v.layout,value:f,options:v.options,...((S=v.rules)==null?void 0:S.max_select)&&{maxSelect:v.rules.max_select}}:{...y,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(f=>f.key===v),updateFieldValue:m,submit:async()=>{const v={};let f=!1;for(const y of e.fields){const E=l[y.key]??null,x=Nl(y,E,n);x.isValid||(v[y.key]=x.error,f=!0)}if(a(v),!f&&r){const y={};e.fields.forEach(E=>{y[E.key]=l[E.key]??null}),await r(y)}},cancel:async()=>{await(o==null?void 0:o())}}},$l=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}=kt(),r=ts(e)[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?$l(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},Pl=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const o=c.useRef(null),s=c.useRef(t),a=c.useRef(t),l=c.useRef(!1);s.current=t,c.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]),c.useEffect(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null),(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current},[])},Fl=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:l=>{const u=Date.now(),d=t.get(l);return d!==void 0&&u-d<n?!1:(t.set(l,u),!0)},setInterval:l=>{n=l},reset:()=>{t.clear()}}},Bl=(e,t,n=1e4,r=!0)=>{const o=c.useRef(null),s=c.useRef(null),a=c.useRef(!1);o.current||(o.current=Fl(n));const l=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??l;c.useEffect(()=>{var d;(d=o.current)==null||d.setInterval(n)},[n]),c.useEffect(()=>{var h;if(!r){a.current=!1,s.current=u;return}if(!u||!l){a.current=!1,s.current=null;return}const d=!a.current,m=s.current!==u;a.current=!0,s.current=u,!(!d&&!m)&&(h=o.current)!=null&&h.shouldAnnounce(u)&&t(l)},[u,l,r,t])},ur=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=e.members.filter(s=>s.userId!==t.userId).sort((s,a)=>a.joinedAt-s.joinedAt)[0],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?je(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},zr=e=>c.useReducer((t,n)=>({...t,...n}),e);var Ne=(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))(Ne||{});const Hl=new Set(["free_text","single_choice"]),Ul=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=zr({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,u]=zr({followUpItem:!1}),d=c.useMemo(()=>{var f;const C=s.csat,b=typeof C=="number",v=(f=e.follow_up)==null?void 0:f.find(y=>b?y.scores.includes(C):y.always_visible??!1);if(Hl.has(v==null?void 0:v.response_type))return v},[s.csat,e.follow_up]),m=(()=>{var C;if(typeof n=="number")return"submitted";if((t===Ne.AI_AGENT_CSAT_5||t===Ne.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===Ne.AI_AGENT_CSAT_5_WITH_CRE){const b=typeof s.csat=="number",v=!((C=e.cre)!=null&&C.required)||typeof s.isResolved=="boolean";if(b&&v)return"submittable"}return"unsubmittable"})(),h=c.useCallback(()=>typeof s.csat>"u"?!1:d!=null&&d.required&&!s.csatReason?(u({followUpItem:!0}),!1):!0,[s,d,u]);return c.useEffect(()=>{r||(a({csatReason:""}),u({followUpItem:!1}))},[r,d,a,u]),{params:s,setParams:a,error:l,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},In=5,Vl=250,Gl=50,Wr=e=>Math.max(0,e-Gl),zl=e=>e<1e3?{speed:In*.5,chunkSize:2}:e<2e3?{speed:In*.8,chunkSize:2}:{speed:In*.6,chunkSize:3},Wl=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:o,onAnimationComplete:s}=e,[a,l]=c.useState(()=>Wr(t.length)),u=c.useRef(null),d=c.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=c.useRef({onStart:r,onProgress:o,onComplete:s}).current,h=c.useRef({startCalled:!1,completeCalled:!1}).current,g=c.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,C=n,b=a<t.length,v=g.initialEnabled&&(C||b);return c.useLayoutEffect(()=>{m.onStart=r,m.onProgress=o,m.onComplete=s,g.textLength=t.length,g.enabled=n}),c.useLayoutEffect(()=>{var f;g.initialEnabled&&(h.startCalled||(h.startCalled=!0,(f=m.onStart)==null||f.call(m)),l(y=>t.length<y?t.length:y))},[t]),c.useEffect(()=>{if(!g.initialEnabled)return;let f=Wr(t.length);d.lastUpdate=0,d.startTime=0,d.lastProgressCall=0;const y=E=>{var G;d.lastUpdate===0&&(d.lastUpdate=E,d.startTime=E,d.lastProgressCall=E);const x=g.textLength,S=E-d.lastUpdate,I=E-d.startTime,{speed:k,chunkSize:M}=zl(I),U=k*M;S>=U&&f<x&&(f=Math.min(f+M,x),l(f),d.lastUpdate=E),E-d.lastProgressCall>=Vl&&(d.lastProgressCall=E,(G=m.onProgress)==null||G.call(m)),(f<x||g.enabled)&&(u.current=requestAnimationFrame(y))};return u.current=requestAnimationFrame(y),()=>{var E;u.current&&cancelAnimationFrame(u.current),h.startCalled&&!h.completeCalled&&(h.completeCalled=!0,(E=m.onComplete)==null||E.call(m))}},[]),c.useEffect(()=>{var x;const f=g.initialEnabled&&h.startCalled,y=!n,E=a>=t.length&&t.length>0;f&&y&&E&&!h.completeCalled&&(h.completeCalled=!0,(x=m.onComplete)==null||x.call(m))},[n,a,t.length]),{streamText:g.initialEnabled?t.slice(0,a):t,isAnimating:v}},ss=e=>e.replace(/\s+/g," ").trim(),ql="Code block",is=e=>`A11Y_INLINE_CODE_${e}`,as=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}},ls=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}},Kl=e=>{const{blockquotePrefix:t,content:n}=as(e),{content:r}=ls(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(u=>u===l))&&!(l==="`"&&a.includes("`")))return{char:l,blockquotePrefix:t,length:s.length}},Yl=(e,t)=>{const{blockquotePrefix:n,content:r}=as(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=ls(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(u=>u===t.char)},jl=(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},Xl=(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},Zl=(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},Jl=e=>{let t=0,n="";for(;t<e.length;){const r=jl(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=Xl(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=Zl(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},cs=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Ql=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return cs(n,r,a)?t:`${n}${r}`}),ec=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),tc=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),nc=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 cs(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},rc=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),oc=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},qr=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))},Kr=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},sc=e=>{const t=e.split(`
|
|
2
|
+
`),n=[];let r=0;for(;r<t.length;){const o=t[r],s=t[r+1],a=Kr(o);if(a.length>0&&s&&qr(s)){for(n.push(a.join(" ")),r+=2;r<t.length;){const l=t[r],u=Kr(l);if(u.length===0||qr(l))break;n.push(u.join(" ")),r+=1}continue}n.push(o),r+=1}return n.join(`
|
|
3
|
+
`)},ic=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),ac=(e,t)=>{const n=e.split(`
|
|
4
|
+
`),r=[];let o=0;for(;o<n.length;){const s=n[o],a=Kl(s);if(!a){r.push(s),o+=1;continue}let l=-1;for(let u=o+1;u<n.length;u++)if(Yl(n[u],a)){l=u;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},lc=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,u=!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+=is(m),n=l+a.length,u=!0;break}l+=1}u||(r+=a,n=s)}return{text:r,inlineCodes:t}},cc=(e,{codeBlockPlaceholder:t=ql}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
7
|
+
`);if(!n)return;const r=[];let o=n;o=ac(o,t),o=oc(o);const s=lc(o);o=s.text,r.push(...s.inlineCodes),o=Jl(o),o=Ql(o),o=ec(o),o=tc(o),o=nc(o),o=sc(o),o=ic(o),o=rc(o);for(let l=0;l<r.length;l++)o=o.replaceAll(is(l),r[l]);return ss(o)||void 0},rn=e=>(e==null?void 0:e.trim())||"",uc=e=>(e?ss(e):void 0)||void 0,dr=e=>({text:rn(e),format:"plain"}),dc=e=>({text:rn(e),format:"markdown"}),ht=({markdownText:e,plainText:t,comparisonText:n})=>{const r=rn(e);return r&&r!==rn(n)?dc(r):dr(t)},mt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?cc(t,{codeBlockPlaceholder:o}):uc(t);if(e&&s.push(e),a&&s.push(a),r&&s.push(r),s.length!==0)return s.join(", ")},mc=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r}=t;let o=null;const s=[];let a=null,l=null,u=!1,d=0;const m=(S,I)=>({text:S,ignoreSuppression:I,queueOrder:d++}),h=()=>{const S=s[0]??null,I=o;return S&&I?I.queueOrder<S.queueOrder?(o=null,I):s.shift()??null:S?s.shift()??null:I!==null?(o=null,I):null},g=()=>{for(;;){const S=h();if(!S)return null;if(!(!S.ignoreSuppression&&(r!=null&&r())))return S}},C=S=>{a=S,u=!0,e(S),l=setTimeout(()=>{l=null,u=!1;const I=g();I&&C(I.text)},n)},b=S=>{a=S,e(S)},v=(S,I,k)=>{if(S&&!(!I&&(r!=null&&r()))&&!(S===a&&u))if(u){if(((k==null?void 0:k.mode)??"latestOnly")==="ordered"){const U=s[s.length-1];if((U==null?void 0:U.text)===S)return;s.push(m(S,I));return}o=m(S,I)}else o=null,C(S)};return{announce:(S,I)=>{v(S,!1,I)},announceIgnoringSuppression:(S,I)=>{v(S,!0,I)},flush:()=>{const S=[];let I=h();for(;I!==null;)S.push(I),I=h();if(l!==null&&(clearTimeout(l),l=null),u=!1,S.length!==0)for(const k of S)b(k.text)},destroy:()=>{l!==null&&(clearTimeout(l),l=null),o=null,s.length=0,a=null,u=!1}}},hc=e=>{switch(e){case"conversationClosed":case"csatDisplayed":return"ordered";default:return"latestOnly"}},gc=(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(". "),fc=(e,t)=>{switch(e.event){case"newMessage":return 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"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},pc=(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}},_c=(e,t)=>!t||!Oe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Yr=(e,t)=>pe.isAdmin(e)?pe.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Ec=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,bc=e=>e===ie.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===ie.CollectionEventSource.EVENT_MESSAGE_UPDATED,jr=(e,t,n,r)=>{const{newestFirst:o=!1}={};if(o){for(const s of e)if(s&&Yr(s,n)&&t.some(a=>kr(s,a)))return s;return}for(let s=e.length-1;s>=0;s-=1){const a=e[s];if(a&&Yr(a,n)&&t.some(l=>kr(a,l)))return a}},Cc=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",vc=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},yc=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Sc=({intent:e,strings:t})=>({label:vc(e,t),hint:yc(e,t)}),Ac="1.23.0",we="sb-agent",ce={ENTRY:`${we}-entry`,MODAL_ROOT:`${we}-modal-root`,WINDOW:`${we}-window`,LAUNCHER:`${we}-launcher`},us="data-sb-initial-focus",ds="true",xc=`[${us}="${ds}"]`,Tc={[us]:ds},Ut=2147483647,ot={MODAL:Ut-1,TOOLTIP:Ut-2,WINDOW:Ut-3,LAUNCHER:Ut-4},ms=36,Ic=100,wc=Ac,mr="noopener noreferrer nofollow";function kc(){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 Vt={};function Lc(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Vt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Vt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Vt[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(Vt).filter(t=>t.startsWith(e))}}}}const Mc={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",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:"Connect with an 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_document:e=>`Document file: ${e}`,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_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"},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} 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_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"}},Wn={language:"en",strings:Mc,dateLocale:Ai.enUS},hs=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,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_DOCUMENT:e.conversation.a11y_file_document,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_RATING_LABEL:e.csat.a11y_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,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}),gs=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Lt},Lt="en",fs=new Set([Lt,"ko","es","pt","fr","hi","it","de","tr","ja"]),Oc='@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}',Rc=(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.":""))))})},Xr=hs(Wn.strings),Nc={...Xr,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_UPLOAD_FILES:"Files",FILE_VIEWER__UNSUPPORT:"Unsupported message",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",A11Y_ATTACH_FILE:"Attach file",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_CSAT_RATING_LABEL:(e,t)=>`${e} — ${t}`,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",A11Y_CONNECT_AGENT:"Talk to human agent",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:Xr.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:Wn.language,dateLocale:Wn.dateLocale,stringSet:Nc},Dc=Object.freeze(Object.defineProperty({__proto__:null,default:on},Symbol.toStringTag,{value:"Module"})),qn=new Map([[Lt,on]]);async function $c(e){const t=qn.get(e);if(t)return t;try{if(fs.has(e)){const{default:n}=await Rc(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/RKaCusvu.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Dc),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/CfhYXtgc.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/BCDZXq61.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BBssumix.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/Jlh8RyJW.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/Sz9ta-fi.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/Bz2jHC-Z.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/CFY_588Z.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/CHz4H01e.cjs"))}),`./languages/${e}.ts`,3);return qn.set(e,n),n}return on}catch{return on}}const{Provider:Pc,useContext:Q}=me("Localization"),Fc=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=c.useState(qn.get(Lt));return c.useEffect(()=>{const l=t??gs(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),$c(l).then(a))},[e,t,n]),i.createElement(Pc,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,u,d)=>We.format(l,u,{locale:s.dateLocale,...d})}},o)},sn="data-sb-agent-theme",Zr=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${sn}='${e}'] & { ${r} }`},W={light:Zr("light"),dark:Zr("dark")},Bc=R.css(({theme:e})=>{const{palette:t}=e;return`
|
|
2
8
|
:root,
|
|
3
9
|
:host {
|
|
4
10
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|
|
@@ -47,25 +53,53 @@
|
|
|
47
53
|
--sendbird-overlay-dark: ${t.overlay.dark};
|
|
48
54
|
--sendbird-overlay-light: ${t.overlay.light};
|
|
49
55
|
}
|
|
50
|
-
`}),
|
|
56
|
+
`}),Hc=R.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);}`,p={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background600:"var(--sendbird-background-600)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)"},ondark:{textMidEmphasis:"var(--sendbird-ondark-text-mid-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)"}},{Provider:Uc,useContext:hr}=me("MessengerTheme");function Vc(e){const{theme:t,appearance:n,logger:r}=e;return i.createElement(Za,{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(Gc,{...e}))}function Gc({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=ar();return c.useLayoutEffect(()=>{e.setAttribute(sn,n.selectedTheme)},[e,n.selectedTheme]),i.createElement(R.ThemeProvider,{theme:n},i.createElement(Uc,{value:{theme:n,updateTheme:r,rootElement:e}},t))}function He(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const zc=(e,t)=>{c.useEffect(()=>{const n=He(t)instanceof ShadowRoot,r=He(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])},Wc=(e,t=document.body)=>{c.useEffect(()=>{const n=He(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])},qc=80,Kc=()=>{const{stringSet:e}=Q(),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,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=c.useRef(t);return n.current=t,n},ps=me("AriaLiveRegion",{announce:oe,announceScreenEntry:oe,announceStatus:oe,announceError:oe,flush:oe,setSuppressionState:oe}),Yc=ps.Provider,gr=ps.useContext,jc={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Xc=({children:e})=>{const t=c.useRef(null),n=c.useRef(new Set),r=c.useRef(oe),o=Kc(),[s]=c.useState(()=>mc(C=>{r.current(C)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=C=>{const b=t.current;b&&(b.textContent="",requestAnimationFrame(()=>{b.textContent=C}))},c.useEffect(()=>()=>{s.destroy()},[s]);const a=s.announce,l=s.flush,u=c.useCallback(C=>{const b=gc(C,o.current);a(b)},[a]),d=c.useCallback(C=>{const b=fc(C,o.current);a(b,{mode:hc(C.event)})},[a]),m=c.useCallback((C,b)=>{const v=pc(C,o.current);s.announceIgnoringSuppression(v),b&&setTimeout(()=>{b.focus()},qc)},[s]),h=c.useCallback((C,b)=>{if(b){n.current.add(C);return}n.current.delete(C)},[]),g=c.useMemo(()=>({announce:a,announceScreenEntry:u,announceStatus:d,announceError:m,flush:l,setSuppressionState:h}),[a,m,u,d,l,h]);return i.createElement(Yc,{value:g},e,i.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:jc}))},_s=me("ConversationAnnouncements",{announcementsActive:!0,announce:oe,announceStatusText:oe,announceScreenEntry:oe,announceStatus:oe,announceError:oe,setIsSuppressed:oe,setStatusPauseState:oe,flush:oe}),Zc=_s.Provider,st=_s.useContext,Jc=({children:e,announcementsActive:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:o,announceError:s,flush:a,setSuppressionState:l}=gr(),u=c.useRef([]),d=c.useRef(new Set),m=c.useRef(Symbol("conversation-announcements")),h=c.useCallback(I=>{if(!t||!I){l(m.current,!1);return}l(m.current,!0)},[t,l]),g=c.useCallback(()=>{u.current=[]},[]),C=c.useCallback(()=>{if(u.current.length===0)return;if(!t){g();return}const I=[...u.current];g(),I.forEach(k=>{if(a(),k.type==="status"){o(k.params);return}n(k.text)})},[n,o,t,g,a]),b=c.useCallback((I,k)=>{if(k){d.current.add(I);return}d.current.delete(I),d.current.size===0&&C()},[C]),v=c.useCallback(I=>{t&&n(I)},[n,t]),f=c.useCallback(I=>{if(t){if(d.current.size>0){u.current.push({type:"text",text:I});return}a(),n(I)}},[n,t,a]),y=c.useCallback(I=>{t&&r(I)},[r,t]),E=c.useCallback(I=>{if(t){if(d.current.size>0){u.current.push({type:"status",params:I});return}o(I)}},[o,t]),x=c.useCallback((I,k)=>{t&&s(I,k)},[s,t]);c.useLayoutEffect(()=>(t||(g(),l(m.current,!1)),()=>{g(),l(m.current,!1)}),[t,g,l]);const S=c.useMemo(()=>({announcementsActive:t,announce:v,announceStatusText:f,announceScreenEntry:y,announceStatus:E,announceError:x,setIsSuppressed:h,setStatusPauseState:b,flush:a}),[t,a,v,f,x,y,E,h,b]);return i.createElement(Zc,{value:S},e)},{Provider:Qc,Consumer:Es,useContext:ne}=me("Messenger");function eu({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:o=!0,...s}){const[a,l]=c.useState(!1),[u,d]=c.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)??u,setExpanded:(t==null?void 0:t.setExpanded)??d};return i.createElement(Oa,{...s},h=>i.createElement(Qc,{value:{...s,...h,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o}},e))}const bs=/iPad|iPhone|iPod/.test(navigator.userAgent),tu=/Android/.test(navigator.userAgent),Mt=e=>bs||tu;let vt=null,wn=null;const nu=(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)},Cs=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},be=R.css`&:focus-visible{outline:2px solid ${p.themedColor.primary};outline-offset:2px;}`,De=e=>{const t=e;return typeof t=="number"?`${t}px`:t},D=({as:e,variant:t="body1",color:n,maxTextLines:r,className:o,...s})=>i.createElement(su,{as:e,$variant:t,className:o,$color:n,$maxTextLines:r,...s}),Jr=new WeakMap,ru=(e,t)=>{let n=Jr.get(t);n||(n=new Map,Jr.set(t,n));const r=n.get(e);if(r)return r;const o=t[e]??t.body1,s=R.css`font-size:${De(o.fontSize)};font-weight:${o.fontWeight};${o.fontFamily?`font-family: ${o.fontFamily};`:""}
|
|
51
57
|
${o.lineHeight?`line-height: ${o.lineHeight};`:"line-height: 100%;"}
|
|
52
|
-
`;return n.set(e,i),i},Ya=e=>e?M.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Za=h.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>ja(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Ya(e)}`,Ze=({style:e,rootElementId:t,visible:n,onClose:r,children:o})=>{if(!n)return null;const{rootElement:i}=lo(),a=Ve(i),l=Ve(i,!0);return is.createPortal(s.createElement(Xa,{onClick:r,style:e},s.createElement(Ja,{onClick:c=>c.stopPropagation()},o)),a.getElementById(t)??a.getElementById(ae.MODAL_ROOT)??l.body)},Xa=h.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${m.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${ze.MODAL};`,Ja=h.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:${ze.MODAL};`,Bn=({visible:e,title:t,description:n,confirmText:r="OK",onConfirm:o,onClose:i})=>{const a=()=>{o==null||o(),i()};return s.createElement(Ze,{rootElementId:ae.WINDOW,visible:e,onClose:i},s.createElement(Qa,null,s.createElement(el,null,t&&s.createElement(T,{variant:"h1",color:m.themedColor.textHighEmphasis},t),n&&s.createElement(tl,null,s.createElement(T,{variant:"subtitle2",color:m.themedColor.textHighEmphasis},n))),s.createElement(nl,null,s.createElement(rl,{onClick:a},s.createElement(T,{variant:"button",color:m.themedColor.primary},r)))))},Qa=h.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};`,el=h.default.div`margin-bottom:16px;`,tl=h.default.div`margin-top:8px;`,nl=h.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,rl=h.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;`,{Provider:ol,useContext:se}=te("MessengerSession"),sl=d.forwardRef(function({children:e,...t},n){return s.createElement(Ri,{ref:n,...t},r=>s.createElement(il,{...r},e))}),il=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:i,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:u,_aiAgentSDK:g}=j(),{userSessionInfo:p,authenticate:E,userSession:v,aiAgentInfo:x,launcherInfo:_}=t,[f,b]=d.useState(!1),y=d.useRef(null);$e.useGroupChannelHandler(n,{async onUserJoined(A,L){var S,R,P,O;A.conversation&&A.conversation.type===ee.ConversationType.PROACTIVE&&L.userId===((S=n.currentUser)==null?void 0:S.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",A.url),(P=g.session)==null||P._updateActiveChannel({url:A.url,status:"open",conversationStatus:(R=A.conversation)==null?void 0:R.status}),l.setOpened(!0),al({sound:document.hidden||!l.opened}),(O=y.current)==null||O.call(y,{channel:A}))}}),d.useEffect(()=>{E().then(({launcher:A})=>{A.auto_open&&!dt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(A=>{var L;r.error("messengerSession: failed to initialize",A),(L=c==null?void 0:c.onInitializeFailed)==null||L.call(c,A)})},[n,o,i,p==null?void 0:p.userId]),d.useEffect(()=>{const A=()=>b(!0);return u.subscribe(ue.AnonymousSessionTokenExpired,A),()=>u.unsubscribe(ue.AnonymousSessionTokenExpired,A)},[u]);const w=d.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!v||!x||!_?null:s.createElement(ol,{value:{...t,userSession:v,aiAgentInfo:{...x,...a==null?void 0:a.bot},launcherInfo:{..._,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:A=>y.current=A}},e,s.createElement(Bn,{visible:f,title:"Session timed out",description:"Start a new conversation.",onConfirm:w,onClose:be}))};function al({sound:e}){Ka("🔔You have received a new message"),e&&mo()}const ll=e=>{const{chatSDK:t,handlers:n,logger:r}=j(),{aiAgentInfo:o}=se(),i=d.useRef(new Set),a=g=>{if(!(n!=null&&n.onCustomEvent))return;Le(g)&&g.sender.userId===o.userId&&!ke.isStreaming(g)&&!i.current.has(g.messageId)&&(r.debug("useCustomEventForMessageReceive: bot-message-received",g),n.onCustomEvent({type:"bot-message-received",data:{message:g}}),i.current.add(g.messageId))},l=g=>{if(n!=null&&n.onCustomEvent&&g.isAdminMessage()&&g.customType==="user_action_required"&&!i.current.has(g.messageId)){const p=gn(g.data);Array.isArray(p.history)&&p.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",p),n.onCustomEvent({type:"user-action-requested",data:p}),i.current.add(g.messageId))}},c=(g,p)=>{g.url===e&&(a(p),l(p))},u=g=>{l(g)};return $e.useGroupChannelHandler(t,{onMessageUpdated:c,onMessageReceived:c}),{checkForUserActionRequired:u}},Lt=`@${ce}-focused-channel`,ho=`${Date.now()}-${Math.random().toString(36).slice(2)}`,cl=()=>{try{const e=localStorage.getItem(Lt);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},fr=e=>{try{localStorage.setItem(Lt,JSON.stringify({channelUrl:e,tabId:ho}))}catch{}},pr=()=>{try{const e=localStorage.getItem(Lt);if(!e)return;JSON.parse(e).tabId===ho&&localStorage.removeItem(Lt)}catch{}},dl=(e,t)=>(d.useEffect(()=>{if(!t||!e)return;const n=()=>fr(e),r=()=>pr();return document.hasFocus()&&fr(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),pr()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||cl()===e}),ul=e=>{var a;const{config:t,chatSDK:n}=j(),{sdkUser:r}=se(),o=!!((a=t==null?void 0:t.conversation)!=null&&a.messageAlertSoundEnabled),{isChannelViewedInAnyTab:i}=dl(e,o);$e.useGroupChannelHandler(n,{onMessageReceived(l,c){if(!o||l.url!==e||i())return;(Le(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&mo()}})};function ml(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 hl(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await ml(e.file);return new we.MessageMetaArray({key:Hr,value:[t,n]})}}const gl=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=j(),r=d.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const i=await hl(o),a={...o,metaArrays:i?[i]:void 0},l=fl(r.current);return l?{...a,data:JSON.stringify(l)}:a},onAfterSendMessage:o=>{var i,a,l;e(),(i=n==null?void 0:n.onMessageSend)==null||i.call(n,o.message),o.sendingStatus===we.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===we.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},fl=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};async function Un(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Rt(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const Ye=50,an=Ye-40,{Provider:pl,useContext:go}=te("ConversationScroll"),Er={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},ln=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function El({scrollMode:e,messageStackDirection:t,children:n}){const r=d.useRef(null),o=d.useRef(null),i=d.useRef(0),a=d.useRef(0),l=d.useRef(!1),c=d.useRef(!1),u=d.useRef(null),g=d.useRef(Er),p=d.useRef(!1),E=d.useRef(null),[v,x]=d.useState(0),[_,f]=d.useState(0),[b,y]=d.useState(!1),[w,A]=d.useState(!1),[L,$]=d.useState(!0),S=D=>{const V=ln(D);return i.current=V,f(V),V},R=()=>{u.current&&(clearTimeout(u.current),u.current=null)},P=d.useMemo(()=>b||t==="bottom"?"auto":e,[b,t,e]),O=()=>{g.current.contentSnapshotHeight=g.current.contentHeight,g.current.shouldUpdate=!0,g.current.shouldRecalc=!0},I=()=>{const D=r.current;!D||!g.current.shouldUpdate||x(V=>{g.current.shouldUpdate=!1;const{contentHeight:q,contentSnapshotHeight:Q,shouldRecalc:ie}=g.current,le=D.clientHeight;if(Q>q)return V;const Ke=U(D,{messageType:"outgoing"});let Se=0;if(Ke){const re=Ke.message.offsetTop-an+le;Se=Math.max(0,re-q)}else{const re=q-Q,Ae=le-an;Se=Math.max(0,re-Ae)}return V===0||Se!==V||ie?(g.current.shouldRecalc=!1,Se):V})},U=d.useCallback((D,V)=>{const{messageType:q="all"}=V??{},Q=Array.from(D.querySelectorAll(`#${ce}-message-item`));let ie=Q;q==="outgoing"&&(ie=Q.filter(pt=>pt.getAttribute("data-layout-id")==="outgoingmessage"));const le=ie[ie.length-1];if(!le)return null;const Ke=D.getBoundingClientRect(),Se=le.getBoundingClientRect(),re=D.scrollTop+(Se.top-Ke.top),Ae=re+le.offsetHeight;return{message:le,scrollTop:re,lastMessageBottom:Ae}},[]),N=d.useCallback(()=>{const D=r.current;if(!D||P!=="fixed")return;const V=U(D);g.current.contentHeight=(V==null?void 0:V.lastMessageBottom)??D.scrollHeight,!p.current&&g.current.contentSnapshotHeight>0&&O(),c.current?i.current=ln(D):S(D),I()},[P,U]),z=d.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),R(),g.current=Er,x(0),f(0),$(!0),i.current=0,l.current=!1,a.current=0,c.current=!1},[]),Y=d.useCallback((D=!0)=>{const V=i.current>Ye;if(l.current=!1,f(0),!V){Rt(()=>{const q=r.current;q&&!l.current&&q.scrollTo({top:q.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,$(!1),R()),Rt(()=>{const q=r.current;if(!q){c.current=!1,$(!0);return}if(l.current){c.current=!1,S(q),$(!0);return}const Q=()=>{if(r.current!==q){c.current=!1,r.current&&S(r.current),$(!0);return}c.current=!1,S(q),$(!0)};if(D&&!u.current){const ie=setTimeout(Q,500);u.current=ie,q.addEventListener("scrollend",()=>{clearTimeout(ie),u.current=null,Q()},{once:!0})}q.scrollTo({top:q.scrollHeight,behavior:D?"smooth":"auto"}),D||Q()})},[]),G=d.useCallback(D=>{D&&(r.current=D,P==="fixed"&&(z(),g.current.viewport=D.clientHeight,o.current=new MutationObserver(()=>{N()}),o.current.observe(D,{childList:!0,subtree:!0})))},[P,N,z]),ve=d.useCallback(()=>{const D=r.current;if(!D)return;const V=U(D,{messageType:"outgoing"});V&&(D.scrollTo({top:V.message.offsetTop-an,behavior:"smooth"}),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{A(!1)},500))},[U]),gt=(D,V,q)=>{const Q=ln(D);if(q&&Q>Ye){c.current=!1,l.current=!0,R(),S(D),$(!0),a.current=V;return}i.current=Q},k=(D,V,q)=>{const ie=S(D)<=Ye;V&&!ie&&(l.current=!0,R()),q&&ie&&(l.current=!1)},Ne=D=>{const{scrollTop:V}=D.currentTarget,q=a.current;c.current?gt(D.currentTarget,V,V<q):k(D.currentTarget,V<q,V>q),a.current=V},qe=d.useCallback(()=>{P==="fixed"&&(A(!0),O())},[P]),ye=d.useCallback(()=>{P==="fixed"?setTimeout(()=>ve(),300):Y()},[P,ve]),Yt=d.useCallback(D=>{p.current=D,P==="fixed"?O():l.current||Y()},[P,Y]),Zt=d.useCallback(D=>{y(D),D&&(x(0),o.current&&(o.current.disconnect(),o.current=null))},[]),Xt=d.useCallback(D=>{P==="auto"&&D&&!l.current&&Y()},[P,Y]),Jt=!(_<=Ye)&&!w,Qt=d.useCallback(()=>i.current>Ye,[]);return s.createElement(pl,{value:{ref:G,state:{bottomSpace:v,isAwayFromBottom:Jt,isScrollPositionReconciled:L,shouldCountNewMessages:Qt},props:{onScroll:Ne},actions:{scrollToBottom:Y,onBeforeMessageSend:qe,onAfterMessageSend:ye,onStreamingUpdate:Yt,onConversationClosed:Zt,onTypingIndicatorUpdate:Xt}}},n)}const{Provider:_l,Context:bl,useContext:ne}=te("Conversation"),Cl=({children:e})=>{var o;const{channelSource:t}=ne(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=ll(n);return d.useEffect(()=>{var a;const i=(a=t.channel)==null?void 0:a.lastMessage;i&&r(i)},[t.channel,r]),s.createElement(s.Fragment,null,e)},xl=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:i,refreshActiveChannel:a}=se(),l=go(),c=e||(i==null?void 0:i.url);ul(c);const{onBeforeSendMessage:u,onAfterSendMessage:g}=gl({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),p=d.useCallback(x=>(l.actions.onBeforeMessageSend(),u(x)),[l.actions,u]),E=d.useCallback(x=>{const _=x.some(f=>ke.isStreaming(f));l.actions.onStreamingUpdate(_)},[l.actions.onStreamingUpdate]),v=d.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return s.createElement(Wi,{key:c,channelUrl:c,onBeforeSendMessage:p,onAfterSendMessage:g,onMessagesUpdated:E,onMessagesReceived:E,onChannelDeleted:v,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},x=>s.createElement(_l,{value:{...x,scrollSource:l,goToActiveConversation:v,onNavigateToConversationList:n}},s.createElement(Cl,null,o)))},fo=({children:e,...t})=>{var a;const{config:n}=de(),{agentPreviewConfigs:r}=j(),o=((a=n==null?void 0:n.conversation)==null?void 0:a.scrollMode)??"auto",i=r==null?void 0:r.messageStackDirection;return s.createElement(El,{scrollMode:o,messageStackDirection:i},s.createElement(xl,{...t},e))},Hn=d.createContext({onDrop:be,subscribe:()=>be}),xn=({children:e})=>{const t=d.useRef(new Set);return s.createElement(Hn.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(i=>i(o))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},vl=({onDropFiles:e})=>{const{subscribe:t}=d.useContext(Hn);d.useEffect(()=>t(e),[e])};xn.Consumer=({children:e})=>{const{onDrop:t}=d.useContext(Hn);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};class Ot extends d.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:s.createElement(d.Suspense,{fallback:r},o)}}const yl=e=>s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},s.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"})),Sl=e=>s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},s.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"})),Al=e=>s.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},s.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"})),Tl=e=>s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},s.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"})),Il=e=>s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},s.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"})),wl=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),kl={close:yl,send:Il,menu:Tl,expand:Al,collapse:Sl,spinner:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),info:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/ohTjxqcW.cjs"))),refresh:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),delete:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/CKPzhVy2.cjs"))),"close-filled":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),question:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/JA0x62Fd.cjs"))),actionbook:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),bot:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/PhHbzZB_.cjs"))),"bot-filled":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DlvMdI1f.cjs"))),copy:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),"arrow-left":d.lazy(()=>Promise.resolve().then(()=>require("./cjs/CZIjo9nb.cjs"))),add:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:d.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs")))},F=({type:e,size:t=24,className:n,color:r})=>{const o=kl[e];return s.createElement($l,{className:n,$rtlFlip:wl.has(e),$size:t,$color:r??m.color.primary.main},s.createElement(Ot,{errorFallback:s.createElement(Ll,null)},s.createElement(o,null)))},Ml=M.css`[dir='rtl'] &{transform:scaleX(-1);}`,$l=h.default.div`width:${({$size:e})=>ge(e)};height:${({$size:e})=>ge(e)};display:inline-block;&:focus{outline:none;}svg{display:block;}[class*='fill']{fill:${({$color:e})=>e};}[class*='stroke']{stroke:${({$color:e})=>e};stroke-width:2px;stroke-linejoin:round;}${({$rtlFlip:e})=>e&&Ml};`,Ll=()=>s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},s.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),s.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),s.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),Rl=.75,po=6,Ol=po*2;let vn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(vn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Dl=e=>vn?Array.from(vn.segment(e),t=>t.segment):[...e],Nl=e=>{const t=Math.floor(e.length*Rl),n=Math.max(0,e.length-po);return Math.max(t,n)},_r=(e,t="")=>{if(e.length<Ol)return{start:e+t,end:""};const n=Dl(e),r=Nl(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Pl=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return _r(t);const o=t.slice(0,n),i=t.slice(n);return _r(o,i)},Eo=({children:e,...t})=>{const{start:n,end:r}=d.useMemo(()=>Pl(e),[e]);return r?s.createElement(Fl,null,s.createElement(Bl,{...t},n),s.createElement(Ul,{...t},r)):s.createElement(T,{...t},n)},Fl=h.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,Bl=h.default(T)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,Ul=h.default(T)`flex-shrink:0;white-space:nowrap;`,Vn=({name:e,type:t="FILE",iconColor:n,iconBackgroundColor:r,onClick:o})=>{const{colors:i}=M.useTheme();return s.createElement(Hl,{onClick:o,$clickable:!!o},s.createElement(zl,{$bgColor:r??i.base.primary},s.createElement(F,{type:"file-document",size:24,color:n??i.base.primaryContrastContent})),s.createElement(Gl,null,s.createElement(Eo,{variant:"button",color:m.themedColor.textHighEmphasis},e),s.createElement(T,{color:m.themedColor.textMidEmphasis,variant:"caption3"},t)))},Hl=h.default.div`border-radius:12px;gap:8px;width:${H.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${m.themedColor.textDisabled};background-color:${m.themedColor.bg_50_600};${({$clickable:e})=>e&&Vl}`,Vl=M.css`cursor:pointer;&:hover{background-color:${m.themedColor.bg_100_500};}`,zl=h.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Gl=h.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Wl({file:e,children:t,onClickFile:n}){return s.createElement(ql,null,s.createElement(Vn,{name:e.name,type:In(e.name,e.type),onClick:n&&(()=>n==null?void 0:n(e))}),t)}const ql=h.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${H.GAP_GROUPED}px;`,Ce=`${ce}-incoming-msg`,Kl=`${ce}-marked-text`;function jl({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const o=()=>{n?n({files:[{url:e.url,type:e.type,name:e.name}],index:0}):t&&t(e)},i=()=>e.type.startsWith("image")?s.createElement(Xl,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?s.createElement(Jl,{controls:!0},s.createElement("source",{src:e.url}),s.createElement("track",{kind:"captions"})):null;if(i){const a={id:`${Ce}-media-body`,onClick:o};return s.createElement(Yl,null,s.createElement(Zl,{...a},i()),r)}return null}const Yl=h.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${H.GAP_GROUPED}px;`,Zl=h.default.div`width:${H.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${B.light`
|
|
53
|
-
|
|
58
|
+
`;return n.set(e,s),s},ou=e=>e?R.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",su=_.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>ru(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>ou(e)}`,vs=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),Ot=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 fr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Ce(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const iu='[data-sb-initial-focus="true"]',ys=e=>Array.from(e.querySelectorAll(vs)).filter(Ot),au=e=>Array.from(e.querySelectorAll(iu)).find(Ot)??ys(e)[0]??null,lu=e=>Array.from(e.ownerDocument.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e&&Ot(t)),cu=e=>{const t=au(e)??e;t===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),t.focus()},uu=(e,t,n)=>{const r=ys(t);if(r.length===0){e.preventDefault(),t.focus();return}const o=r[0],s=r[r.length-1],a=n.activeElement;(e.shiftKey?a===o:a===s)&&(e.preventDefault(),(e.shiftKey?s:o).focus())},du=(e,t)=>{const n=c.useRef(null);c.useEffect(()=>{if(!e||!t.current)return;const r=t.current,o=r.getRootNode();n.current=o.activeElement instanceof HTMLElement?o.activeElement:null;let s=!1;return Ce(()=>{s||!r.isConnected||cu(r)}),()=>{s=!0;const a=n.current;n.current=null,a&&Ce(()=>{lu(r)||!a.isConnected||!Ot(a)||a.focus()})}},[e,t]),c.useEffect(()=>{if(!e||!t.current)return;const r=t.current,o=r.getRootNode(),s=a=>{a.key==="Tab"&&uu(a,r,o)};return r.addEventListener("keydown",s),()=>r.removeEventListener("keydown",s)},[e,t])},mu=(e,t=!0,n)=>{const r=n==null?void 0:n.containerRef;c.useEffect(()=>{if(!t||!e)return;const o=a=>{a.key==="Escape"&&e()&&a.stopImmediatePropagation()},s=(r==null?void 0:r.current)??document;return s.addEventListener("keydown",o),()=>s.removeEventListener("keydown",o)},[r,e,t])},ft=({style:e,rootElementId:t,visible:n,onClose:r,children:o,"aria-label":s,"aria-labelledby":a,"aria-describedby":l})=>{const u=c.useRef(null),{rootElement:d}=hr();if(du(n,u),mu(c.useCallback(()=>(r(),!0),[r]),n,{containerRef:u}),!n)return null;const m=He(d),h=He(d,!0);return xi.createPortal(i.createElement(hu,{onClick:r,style:e},i.createElement(gu,{ref:u,role:"dialog","aria-modal":"true","aria-label":s,"aria-labelledby":a,"aria-describedby":l,onClick:g=>g.stopPropagation()},o)),m.getElementById(t)??m.getElementById(ce.MODAL_ROOT)??h.body)},hu=_.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${p.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${ot.MODAL};`,gu=_.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:${ot.MODAL};`,Qr=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},pr=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:o,onConfirm:s,onCancel:a,onClose:l,"aria-label":u})=>{const d=c.useId(),m=c.useId(),h=u??Qr(t)??Qr(n),g=u?void 0:t?d:n?m:void 0,C=t&&n?m:void 0,b=()=>{l(),Ce(()=>s==null?void 0:s())},v=()=>{l(),Ce(()=>a==null?void 0:a())};return i.createElement(ft,{rootElementId:ce.WINDOW,visible:e,onClose:l,"aria-label":h,"aria-labelledby":g,"aria-describedby":C},i.createElement(fu,null,i.createElement(pu,null,t&&i.createElement("div",{id:d},i.createElement(D,{variant:"h1",color:p.themedColor.textHighEmphasis},t)),n&&i.createElement(_u,{id:m},i.createElement(D,{variant:"subtitle2",color:p.themedColor.textHighEmphasis},n))),i.createElement(Eu,null,o&&i.createElement(eo,{onClick:v},i.createElement(D,{variant:"button",color:p.themedColor.textHighEmphasis},o)),i.createElement(eo,{onClick:b},i.createElement(D,{variant:"button",color:p.themedColor.primary},r)))))},fu=_.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};`,pu=_.default.div`margin-bottom:16px;`,_u=_.default.div`margin-top:8px;`,Eu=_.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,eo=_.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${be}`,{Provider:bu,useContext:_e}=me("MessengerSession"),Cu=c.forwardRef(function({children:e,...t},n){return i.createElement(tl,{ref:n,...t},r=>i.createElement(vu,{...r},e))}),vu=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:u,dispatcher:d,_aiAgentSDK:m}=ne(),{userSessionInfo:h,authenticate:g,userSession:C,aiAgentInfo:b,launcherInfo:v}=t,[f,y]=c.useState(!1),E=c.useRef(null);Ye.useGroupChannelHandler(n,{async onUserJoined(S,I){var M,U,F,G;S.conversation&&S.conversation.type===Ee.ConversationType.PROACTIVE&&I.userId===((M=n.currentUser)==null?void 0:M.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",S.url),(F=m.session)==null||F._updateActiveChannel({url:S.url,status:"open",conversationStatus:(U=S.conversation)==null?void 0:U.status}),l.setOpened(!0),yu({sound:document.hidden||!l.opened}),(G=E.current)==null||G.call(E,{channel:S}))}}),c.useEffect(()=>{g().then(({launcher:S})=>{S.auto_open&&!Mt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(S=>{var I;r.error("messengerSession: failed to initialize",S),(I=u==null?void 0:u.onInitializeFailed)==null||I.call(u,S)})},[n,o,s,h==null?void 0:h.userId]),c.useEffect(()=>{const S=()=>y(!0);return d.subscribe(Me.AnonymousSessionTokenExpired,S),()=>d.unsubscribe(Me.AnonymousSessionTokenExpired,S)},[d]);const x=c.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!C||!b||!v?null:i.createElement(bu,{value:{...t,userSession:C,aiAgentInfo:{...b,...a==null?void 0:a.bot},launcherInfo:{...v,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:S=>E.current=S}},e,i.createElement(pr,{visible:f,title:"Session timed out",description:"Start a new conversation.",onConfirm:x,onClose:oe}))};function yu({sound:e}){nu("🔔You have received a new message"),e&&Cs()}const Su=e=>{const{chatSDK:t,handlers:n,logger:r}=ne(),{aiAgentInfo:o}=_e(),s=c.useRef(new Set),a=m=>{if(!(n!=null&&n.onCustomEvent))return;Oe(m)&&m.sender.userId===o.userId&&!$e.isStreaming(m)&&!s.current.has(m.messageId)&&(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),s.current.add(m.messageId))},l=m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!s.current.has(m.messageId)){const h=Hn(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),s.current.add(m.messageId))}},u=(m,h)=>{m.url===e&&(a(h),l(h))},d=m=>{l(m)};return Ye.useGroupChannelHandler(t,{onMessageUpdated:u,onMessageReceived:u}),{checkForUserActionRequired:d}},an=`@${we}-focused-channel`,Ss=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Au=()=>{try{const e=localStorage.getItem(an);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},to=e=>{try{localStorage.setItem(an,JSON.stringify({channelUrl:e,tabId:Ss}))}catch{}},no=()=>{try{const e=localStorage.getItem(an);if(!e)return;JSON.parse(e).tabId===Ss&&localStorage.removeItem(an)}catch{}},xu=(e,t)=>(c.useEffect(()=>{if(!t||!e)return;const n=()=>to(e),r=()=>no();return document.hasFocus()&&to(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),no()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Au()===e}),Tu=e=>{var a;const{config:t,chatSDK:n}=ne(),{sdkUser:r}=_e(),o=!!((a=t==null?void 0:t.conversation)!=null&&a.messageAlertSoundEnabled),{isChannelViewedInAnyTab:s}=xu(e,o);Ye.useGroupChannelHandler(n,{onMessageReceived(l,u){if(!o||l.url!==e||s())return;(Oe(u)&&u.sender.userId!==(r==null?void 0:r.userId)||u.isAdminMessage()&&!u.silent)&&Cs()}})};function Iu(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 wu(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Iu(e.file);return new qe.MessageMetaArray({key:Bo,value:[t,n]})}}const ku=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ne(),r=c.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await wu(o),a={...o,metaArrays:s?[s]:void 0},l=Lu(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===qe.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===qe.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},Lu=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:Mu,useContext:As}=me("ConversationScroll"),ro={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Ln=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function Ou({scrollMode:e,messageStackDirection:t,children:n}){const r=c.useRef(null),o=c.useRef(null),s=c.useRef(0),a=c.useRef(0),l=c.useRef(!1),u=c.useRef(!1),d=c.useRef(null),m=c.useRef(ro),h=c.useRef(!1),g=c.useRef(null),[C,b]=c.useState(0),[v,f]=c.useState(0),[y,E]=c.useState(!1),[x,S]=c.useState(!1),[I,k]=c.useState(!0),M=B=>{const Z=Ln(B);return s.current=Z,f(Z),Z},U=()=>{d.current&&(clearTimeout(d.current),d.current=null)},F=c.useMemo(()=>y||t==="bottom"?"auto":e,[y,t,e]),G=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},L=()=>{const B=r.current;!B||!m.current.shouldUpdate||b(Z=>{m.current.shouldUpdate=!1;const{contentHeight:X,contentSnapshotHeight:ge,shouldRecalc:ve}=m.current,Be=B.clientHeight;if(ge>X)return Z;const lt=P(B,{messageType:"outgoing"});let Le=0;if(lt){const Ve=lt.message.offsetTop-kn+Be;Le=Math.max(0,Ve-X)}else{const Ve=X-ge,ct=Be-kn;Le=Math.max(0,Ve-ct)}return Z===0||Le!==Z||ve?(m.current.shouldRecalc=!1,Le):Z})},P=c.useCallback((B,Z)=>{const{messageType:X="all"}=Z??{},ge=Array.from(B.querySelectorAll(`#${we}-message-item`));let ve=ge;X==="outgoing"&&(ve=ge.filter(Qe=>Qe.getAttribute("data-layout-id")==="outgoingmessage"));const Be=ve[ve.length-1];if(!Be)return null;const lt=B.getBoundingClientRect(),Le=Be.getBoundingClientRect(),Ve=B.scrollTop+(Le.top-lt.top),ct=Ve+Be.offsetHeight;return{message:Be,scrollTop:Ve,lastMessageBottom:ct}},[]),N=c.useCallback(()=>{const B=r.current;if(!B||F!=="fixed")return;const Z=P(B);m.current.contentHeight=(Z==null?void 0:Z.lastMessageBottom)??B.scrollHeight,!h.current&&m.current.contentSnapshotHeight>0&&G(),u.current?s.current=Ln(B):M(B),L()},[F,P]),w=c.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),U(),m.current=ro,b(0),f(0),k(!0),s.current=0,l.current=!1,a.current=0,u.current=!1},[]),$=c.useCallback((B=!0)=>{const Z=s.current>dt;if(l.current=!1,f(0),!Z){Ce(()=>{const X=r.current;X&&!l.current&&X.scrollTo({top:X.scrollHeight,behavior:"auto"})});return}u.current||(u.current=!0,k(!1),U()),Ce(()=>{const X=r.current;if(!X){u.current=!1,k(!0);return}if(l.current){u.current=!1,M(X),k(!0);return}const ge=()=>{if(r.current!==X){u.current=!1,r.current&&M(r.current),k(!0);return}u.current=!1,M(X),k(!0)};if(B&&!d.current){const ve=setTimeout(ge,500);d.current=ve,X.addEventListener("scrollend",()=>{clearTimeout(ve),d.current=null,ge()},{once:!0})}X.scrollTo({top:X.scrollHeight,behavior:B?"smooth":"auto"}),B||ge()})},[]),O=c.useCallback(B=>{B&&(r.current=B,F==="fixed"&&(w(),m.current.viewport=B.clientHeight,o.current=new MutationObserver(()=>{N()}),o.current.observe(B,{childList:!0,subtree:!0})))},[F,N,w]),q=c.useCallback(()=>{const B=r.current;if(!B)return;const Z=P(B,{messageType:"outgoing"});Z&&(B.scrollTo({top:Z.message.offsetTop-kn,behavior:"smooth"}),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{S(!1)},500))},[P]),te=(B,Z,X)=>{const ge=Ln(B);if(X&&ge>dt){u.current=!1,l.current=!0,U(),M(B),k(!0),a.current=Z;return}s.current=ge},re=(B,Z,X)=>{const ve=M(B)<=dt;Z&&!ve&&(l.current=!0,U()),X&&ve&&(l.current=!1)},K=B=>{const{scrollTop:Z}=B.currentTarget,X=a.current;u.current?te(B.currentTarget,Z,Z<X):re(B.currentTarget,Z<X,Z>X),a.current=Z},T=c.useCallback(()=>{F==="fixed"&&(S(!0),G())},[F]),V=c.useCallback(()=>{F==="fixed"?setTimeout(()=>q(),300):$()},[F,q]),H=c.useCallback(B=>{h.current=B,F==="fixed"?G():l.current||$()},[F,$]),j=c.useCallback(B=>{E(B),B&&(b(0),o.current&&(o.current.disconnect(),o.current=null))},[]),se=c.useCallback(B=>{F==="auto"&&B&&!l.current&&$()},[F,$]),Re=!(v<=dt)&&!x,Ae=c.useCallback(()=>s.current>dt,[]);return i.createElement(Mu,{value:{ref:O,state:{bottomSpace:C,isAwayFromBottom:Re,isScrollPositionReconciled:I,shouldCountNewMessages:Ae},props:{onScroll:K},actions:{scrollToBottom:$,onBeforeMessageSend:T,onAfterMessageSend:V,onStreamingUpdate:H,onConversationClosed:j,onTypingIndicatorUpdate:se}}},n)}const{Provider:Ru,Context:Nu,useContext:he}=me("Conversation"),Du=({children:e})=>{var o;const{channelSource:t}=he(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=Su(n);return c.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)},$u=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=_e(),l=As(),u=e||(s==null?void 0:s.url);Tu(u);const{onBeforeSendMessage:d,onAfterSendMessage:m}=ku({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),h=c.useCallback(b=>(l.actions.onBeforeMessageSend(),d(b)),[l.actions,d]),g=c.useCallback(b=>{const v=b.some(f=>$e.isStreaming(f));l.actions.onStreamingUpdate(v)},[l.actions.onStreamingUpdate]),C=c.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(hl,{key:u,channelUrl:u,onBeforeSendMessage:h,onAfterSendMessage:m,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:C,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},b=>i.createElement(Ru,{value:{...b,scrollSource:l,goToActiveConversation:C,onNavigateToConversationList:n}},i.createElement(Du,null,o)))},xs=({children:e,...t})=>{var a;const{config:n}=ke(),{agentPreviewConfigs:r}=ne(),o=((a=n==null?void 0:n.conversation)==null?void 0:a.scrollMode)??"auto",s=r==null?void 0:r.messageStackDirection;return i.createElement(Ou,{scrollMode:o,messageStackDirection:s},i.createElement($u,{...t},e))},_r=c.createContext({onDrop:oe,subscribe:()=>oe}),Kn=({children:e})=>{const t=c.useRef(new Set);return i.createElement(_r.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)},Pu=({onDropFiles:e})=>{const{subscribe:t}=c.useContext(_r);c.useEffect(()=>t(e),[e])};Kn.Consumer=({children:e})=>{const{onDrop:t}=c.useContext(_r);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const Fu=e=>ze(e)||Uo(e);function Bu(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function Hu(e,t){return e.filter(n=>$e.isWelcomeMessage(n,t))}const Ts=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>Bu(r)?!1:t.length>0?!$e.isWelcomeMessage(r,n):!0),Uu=[],Is=()=>{var b,v,f,y,E,x,S;const{agentPreviewConfigs:e={},aiAgentId:t}=ne(),{aiAgentInfo:n,userSession:r}=_e(),{channelSource:o,messageSource:s,state:{input:a,streamAnimation:l}}=he(),u=e.welcomeMessages??Uu,d=c.useMemo(()=>Ts(s.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,s.messages,u]),m=je(o.channel),h=(f=(v=(b=o.channel)==null?void 0:b.members.find(I=>I.userId!==r.userId))==null?void 0:v.nickname)==null?void 0:f.trim(),g=m?(E=(y=o.channel)==null?void 0:y.name)==null?void 0:E.trim():(x=n==null?void 0:n.nickname)==null?void 0:x.trim(),C=h||g||void 0;return{initialized:s.initialized,channelUrl:(S=o.channel)==null?void 0:S.url,agentName:C,isClosed:Se(o.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:a.disabled,inputDisabledBy:a.disabledBy,isStreamAnimating:l.isAnimating,subscribeMessageEvents:s.subscribeMessageEvents,currentUserId:r.userId}},Vu=(e={})=>{const{announceScreenEntry:t,announcementsActive:n}=st(),{initialized:r=!1,channelUrl:o,agentName:s,isClosed:a=!1,messages:l=[],hasWelcomeMessages:u=!1}=e,d=c.useRef(null),m=c.useMemo(()=>l.some(g=>pe.isAdmin(g)&&pe.isCSAT(g)),[l]),h=l.length===0&&!u;c.useEffect(()=>{if(!n){d.current=null;return}!r||!o||d.current!==o&&(t({screen:"conversation",agentName:s,isClosed:a,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=o)},[s,t,n,o,m,r,a,h])},Gu=()=>{const e=Is();Vu(e)},zu=(e,t,n)=>t!=null&&t.startsWith("image")?n.A11Y_FILE_IMAGE(e):t!=null&&t.startsWith("video")?n.A11Y_FILE_VIDEO(e):n.A11Y_FILE_DOCUMENT(e),Wu=(e,t)=>{var r,o,s,a,l,u;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const d=((o=e.name)==null?void 0:o.trim())||"";return ht({markdownText:n,comparisonText:d,plainText:zu(d,e.type,t)})}if(e.isMultipleFilesMessage()){const d=((l=(a=(s=e.fileInfoList)==null?void 0:s[0])==null?void 0:a.fileName)==null?void 0:l.trim())||"",m=((u=e.fileInfoList)==null?void 0:u.length)??0;return ht({markdownText:n,comparisonText:d,plainText:m>0?t.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(m):""})}return n?ht({markdownText:n}):dr("")},oo=(e,t,n=We.format)=>{const r=Wu(e,t),o="sender"in e?e.sender:void 0,s=mt({message:r.text,messageFormat:r.format,codeBlockPlaceholder:t.A11Y_CODE_BLOCK_PLACEHOLDER}),a=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,l=typeof(o==null?void 0:o.nickname)=="string"&&o.nickname.trim()||void 0;return[t.SCROLL_TO_NEW_MESSAGES_LABEL([e]),a,l,s].filter(u=>!!u).join(", ")},so=2e3,io=400,Xt=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]},ws=e=>{if(!pe.isAdmin(e)||!pe.isCSAT(e))return null;const t=Ec(e);return t?`csat:${t}`:null},qu=e=>{const t=new Set;for(const n of e){const r=ws(n);r&&t.add(r)}return t},Ku=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Xt(r).some(o=>t.includes(o)))return r}},Mn=(e,t)=>e.some(n=>t.includes(n)),ao=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,On=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Yu=()=>{const{announceStatusText:e,announceStatus:t,announcementsActive:n}=st(),{stringSet:r,format:o}=Q(),{channelUrl:s,messages:a,isClosed:l,isHandedOff:u,agentName:d,initialized:m,inputDisabled:h,inputDisabledBy:g,isStreamAnimating:C,subscribeMessageEvents:b,currentUserId:v}=Is(),{outgoingMessageStates:f,outgoingMessageStatusSignature:y}=c.useMemo(()=>{if(!v)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const T=a.flatMap(V=>{const H=_c(V,v);return!H||!("sendingStatus"in V)?[]:[{key:H,sendingStatus:V.sendingStatus}]});return{outgoingMessageStates:T,outgoingMessageStatusSignature:T.map(({key:V,sendingStatus:H})=>`${V}:${H}`).join(",")}},[v,a]),E=c.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:h,inputDisabledBy:g,outgoingMessageStatuses:On(f)}),x=c.useRef({messages:a,currentUserId:v,inputDisabledBy:g,isStreamAnimating:C,stringSet:r,format:o}),S=c.useRef([]),I=c.useRef(null),k=c.useRef({eventKeys:[],text:null,replaceableUntil:null}),M=c.useRef(new Set),U=c.useRef(new Set),F=c.useRef(!1),G=c.useRef(s);x.current={messages:a,currentUserId:v,inputDisabledBy:g,isStreamAnimating:C,stringSet:r,format:o};const L=()=>x.current.isStreamAnimating||x.current.inputDisabledBy==="ai_responding",P=()=>{I.current!=null&&(clearTimeout(I.current),I.current=null)},N=(T,V,H)=>{k.current={eventKeys:T,text:V,replaceableUntil:H!=null&&H.replaceableForMs?Date.now()+H.replaceableForMs:null}},w=()=>S.current.length>0,$=()=>{S.current=[]},O=()=>{const[T,...V]=S.current;if(!T)return!1;S.current=V;const{eventKeys:H,text:j}=T,se=Ae=>{N(H,Ae,{replaceableForMs:H.length>0?so:void 0}),e(Ae)};if(H.length===0)return j&&se(j),!0;const le=x.current,Re=Ku(le.messages,H);return Re?(se(oo(Re,le.stringSet,le.format)),!0):(j&&se(j),!0)},q=()=>{for(P();O(););},te=(T=so)=>{P(),I.current=setTimeout(()=>{if(I.current=null,L())return;const V=ao(),[H]=S.current;if(!H)return;if(H.focusTarget!==V){S.current=[{...H,focusTarget:V},...S.current.slice(1)],te(io);return}O()&&w()&&te(io)},T)},re=(T,V)=>{const H={eventKeys:V,text:T,focusTarget:ao()},j=V.length===0?-1:S.current.findIndex(({eventKeys:se})=>Mn(se,V));j>=0?S.current=S.current.map((se,le)=>le===j?H:se):S.current=[...S.current,H],te()},K=(T,V,H)=>{if(T!=="messagesUpdated"||V.length===0)return!1;const j=k.current;return!Mn(j.eventKeys,V)||j.text==null||j.replaceableUntil==null||Date.now()>j.replaceableUntil?!1:H!==j.text};c.useEffect(()=>{const T=G.current!==s;(!n||!m||T)&&(F.current=!1,U.current.clear(),$(),k.current={eventKeys:[],text:null,replaceableUntil:null},M.current.clear(),P(),T&&(G.current=s),!n||!m)||F.current||(F.current=!0,G.current=s,E.current={isClosed:l,isHandedOff:u,inputDisabled:h,inputDisabledBy:g,outgoingMessageStatuses:On(f)},M.current=new Set(a.flatMap(V=>{if(!$e.isStreaming(V))return[];const H="sender"in V?V.sender:void 0;return(H==null?void 0:H.userId)===x.current.currentUserId?[]:Xt(V)})),U.current=qu(a))},[t,n,s,m,h,l,u,y]),c.useEffect(()=>b(T=>{if(!F.current||T.kind==="initialized"||!bc(T.source))return;const V=x.current,H=jr(T.messages,T.messages,V.currentUserId)??jr(V.messages,T.messages,V.currentUserId);if(!H)return;const j=Xt(H),se=ws(H);if(se!=null){if(U.current.has(se))return;U.current.add(se),t({event:"csatDisplayed"});return}if($e.isStreaming(H)){Xt(H).forEach(X=>{M.current.add(X)});return}const le=j.filter(X=>M.current.has(X)),Re=T.kind==="messagesUpdated"&&le.length>0;Re&&le.forEach(X=>{M.current.delete(X)});const Ae=T.kind==="messagesUpdated"&&S.current.some(({eventKeys:X})=>Mn(X,j)),B=oo(H,V.stringSet,V.format),Z=K(T.kind,j,B);if(!(!Re&&T.kind!=="messagesAdded"&&!Ae&&!Z)){if(Re||L()||Ae){re(B,[...new Set([...le,...j])]);return}w()&&q(),N(j,B),e(B)}}),[t,e,b]),c.useEffect(()=>{F.current&&(L()||w()&&te())},[g,C]),c.useEffect(()=>()=>{P()},[]),c.useEffect(()=>{if(!F.current)return;const T=E.current,V=T.outgoingMessageStatuses;T.outgoingMessageStatuses=On(f),f.some(({key:j,sendingStatus:se})=>{const le=V.get(j);return le!==void 0&&le!=="failed"&&se==="failed"})&&t({event:"sendFailed"})},[t,y]),c.useEffect(()=>{if(!F.current)return;const T=E.current;l&&!T.isClosed&&t({event:"conversationClosed"}),T.isClosed=l},[t,l]),c.useEffect(()=>{if(!F.current)return;const T=E.current;u&&!T.isHandedOff&&t({event:"agentConnected",agentName:d}),T.isHandedOff=u},[d,t,u]),c.useEffect(()=>{if(!F.current)return;const T=E.current;h&&g!=="ai_responding"&&(!T.inputDisabled||T.inputDisabledBy==="ai_responding")&&t({event:"inputDisabled"}),T.inputDisabled=h,T.inputDisabledBy=g},[t,h,g])},ju=()=>{const{channelSource:e}=he(),t=os(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Xu=e=>{const{announceStatus:t,announcementsActive:n}=st();Bl(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Zu=()=>{const e=ju();Xu(e)};class ln extends c.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(c.Suspense,{fallback:r},o)}}const Ju=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"})),Qu=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"})),td=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"})),nd=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"})),rd=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),od={close:Ju,send:nd,menu:td,expand:ed,collapse:Qu,spinner:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),info:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/ohTjxqcW.cjs"))),refresh:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),delete:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CKPzhVy2.cjs"))),"close-filled":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),question:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/JA0x62Fd.cjs"))),actionbook:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),bot:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/PhHbzZB_.cjs"))),"bot-filled":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DlvMdI1f.cjs"))),copy:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),"arrow-left":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CZIjo9nb.cjs"))),add:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs")))},z=({type:e,size:t=24,className:n,color:r})=>{const o=od[e];return i.createElement(id,{className:n,$rtlFlip:rd.has(e),$size:t,$color:r??p.color.primary.main},i.createElement(ln,{errorFallback:i.createElement(ad,null)},i.createElement(o,null)))},sd=R.css`[dir='rtl'] &{transform:scaleX(-1);}`,id=_.default.div.attrs({"aria-hidden":"true"})`
|
|
59
|
+
width: ${({$size:e})=>De(e)};
|
|
60
|
+
height: ${({$size:e})=>De(e)};
|
|
61
|
+
display: inline-block;
|
|
62
|
+
&:focus {
|
|
63
|
+
outline: none;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
svg {
|
|
67
|
+
display: block;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
[class*='fill'] {
|
|
71
|
+
fill: ${({$color:e})=>e};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
[class*='stroke'] {
|
|
75
|
+
stroke: ${({$color:e})=>e};
|
|
76
|
+
stroke-width: 2px;
|
|
77
|
+
stroke-linejoin: round;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
${({$rtlFlip:e})=>e&&sd};
|
|
81
|
+
`,ad=()=>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"})),ld=.75,ks=6,cd=ks*2;let Yn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Yn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const ud=e=>Yn?Array.from(Yn.segment(e),t=>t.segment):[...e],dd=e=>{const t=Math.floor(e.length*ld),n=Math.max(0,e.length-ks);return Math.max(t,n)},lo=(e,t="")=>{if(e.length<cd)return{start:e+t,end:""};const n=ud(e),r=dd(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},md=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)},Ls=({children:e,...t})=>{const{start:n,end:r}=c.useMemo(()=>md(e),[e]);return r?i.createElement(hd,null,i.createElement(gd,{...t},n),i.createElement(fd,{...t},r)):i.createElement(D,{...t},n)},hd=_.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,gd=_.default(D)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,fd=_.default(D)`flex-shrink:0;white-space:nowrap;`,pd=({id:e,children:t})=>i.createElement(_d,{id:e},t),_d=_.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;`,Gt=(e,t)=>e!=null&&e.startsWith("image")?t.A11Y_HINT_OPEN_IMAGE:t.A11Y_HINT_OPEN_FILE,zt=({name:e,mimeType:t,selected:n},r)=>{var s;const o=t!=null&&t.startsWith("image")?r.A11Y_FILE_IMAGE(e):t!=null&&t.startsWith("video")?r.A11Y_FILE_VIDEO(e):r.A11Y_FILE_DOCUMENT(e);return n?((s=r.A11Y_FILE_SELECTED)==null?void 0:s.call(r,o))??`${o}, selected`:o},de=(e,t)=>t?{describedByProps:{"aria-describedby":e},descriptionNode:c.createElement(pd,{id:e,children:t})}:{describedByProps:{},descriptionNode:null},Ed=(e,t,n,r)=>{var s;const o=n.trim()||n;return((s=r.A11Y_CSAT_RATING_LABEL)==null?void 0:s.call(r,e,o))??`${e} / ${t} — ${o}`},Wt=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},ee=()=>{const{stringSet:e}=Q(),t=c.useId(),n=c.useId(),r=c.useId(),o=c.useId(),s=c.useId(),a=c.useId(),l=c.useId(),u=c.useId(),d=c.useId(),m=c.useId(),h=c.useId(),g=c.useId(),C=c.useId(),b=c.useId(),v=c.useId(),f=c.useId(),y=w=>w===e.A11Y_HINT_OPEN_CONVERSATION?de(t,w):w===e.A11Y_HINT_OPEN_CONVERSATIONS?de(n,w):(w===e.A11Y_HINT_CLOSE_CONVERSATION,de(r,w)),E=de(o,e.A11Y_HINT_OPEN_MENU),x=de(s,e.A11Y_HINT_CLOSE_CONVERSATION),S=de(a,e.A11Y_HINT_CONNECT_TO_AGENT),I=de(l,e.A11Y_HINT_ATTACH_FILE),k=de(u,e.A11Y_HINT_SEND_MESSAGE),M=de(d,e.A11Y_HINT_VIEW_NEW_MESSAGES),U=de(m,e.A11Y_HINT_VIEW_NEW_MESSAGES),F=de(h,e.A11Y_HINT_SEND_REPLY),G=de(g,e.A11Y_HINT_SELECT_RATING),L=de(C,e.A11Y_HINT_SELECT_RATING),P=de(b,e.A11Y_HINT_OPEN_CONVERSATION),N=w=>{const $=Gt(w,e);return w!=null&&w.startsWith("image")?de(f,$):de(v,$)};return{launcher:{button:({isOpened:w,opensConversationList:$})=>{const O=Sc({intent:Cc({isOpened:w,opensConversationList:$}),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}}),q=y(O.hint);return{props:{"aria-label":O.label,...q.describedByProps},hint:O.hint,descriptionNode:q.descriptionNode}}},messenger:{closeButton:{"aria-label":e.A11Y_CLOSE_MESSENGER},expandButton:w=>({"aria-label":w?e.A11Y_COLLAPSE_MESSENGER:e.A11Y_EXPAND_MESSENGER})},conversation:{menuButton:{props:{"aria-label":e.A11Y_MENU,...E.describedByProps},hint:e.A11Y_HINT_OPEN_MENU,descriptionNode:E.descriptionNode},closeConversationButton:{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...x.describedByProps},hint:e.A11Y_HINT_CLOSE_CONVERSATION,descriptionNode:x.descriptionNode},handoffButton:{props:{"aria-label":e.A11Y_CONNECT_AGENT,...S.describedByProps},hint:e.A11Y_HINT_CONNECT_TO_AGENT,descriptionNode:S.descriptionNode},headerTitle:w=>({role:"heading","aria-level":2,"aria-label":w,tabIndex:-1}),messageInput:{attachFileButton:{props:{"aria-label":e.A11Y_ATTACH_FILE,...I.describedByProps},hint:e.A11Y_HINT_ATTACH_FILE,descriptionNode:I.descriptionNode},sendButton:{props:{"aria-label":e.A11Y_SEND_MESSAGE,...k.describedByProps},hint:e.A11Y_HINT_SEND_MESSAGE,descriptionNode:k.descriptionNode},textInput:w=>({role:"textbox","aria-label":w})},suggestedReplies:{hint:e.A11Y_HINT_SEND_REPLY,descriptionNode:F.descriptionNode,item:w=>({props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${w}`,...F.describedByProps}})},feedback:{hint:e.A11Y_HINT_SELECT_RATING,descriptionNode:G.descriptionNode,button:(w,$)=>({props:{"aria-label":w==="good"?e.FEEDBACK_GOOD:e.FEEDBACK_BAD,...G.describedByProps,"aria-pressed":$}}),optionsBottomSheet:{"aria-label":e.A11Y_FEEDBACK_OPTIONS}},newMessagesButton:{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...M.describedByProps},hint:e.A11Y_HINT_VIEW_NEW_MESSAGES,descriptionNode:M.descriptionNode},scrollToBottomButton:{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...U.describedByProps},hint:e.A11Y_HINT_VIEW_NEW_MESSAGES,descriptionNode:U.descriptionNode},startNewConversationButton:({onActivate:w})=>({role:"button",tabIndex:0,"aria-label":e.TALK_TO_AGENT,onClick:w,onKeyDown:Wt(w)}),poweredByLink:{"aria-label":`${e.POWERED_BY} Sendbird`},retryButton:(w=e.RETRY)=>({"aria-label":w}),file:{label:(w,$)=>w?zt({name:w,mimeType:$},e):"",preview:w=>({props:{"aria-label":zt(w,e)}}),interactivePreview:w=>{const $=N(w.mimeType);return{props:{"aria-label":zt(w,e),...$.describedByProps},hint:Gt(w.mimeType,e),descriptionNode:$.descriptionNode}},openDescription:w=>{const $=N(w);return{props:$.describedByProps,hint:Gt(w,e),descriptionNode:$.descriptionNode}},buttonLikeInteractivePreview:({onActivate:w,...$})=>{const O=N($.mimeType);return{props:{role:"button",tabIndex:0,"aria-label":zt($,e),...O.describedByProps,onClick:w,onKeyDown:Wt(w)},hint:Gt($.mimeType,e),descriptionNode:O.descriptionNode}},removeButton:w=>({"aria-label":e.A11Y_FILE_REMOVE_BUTTON(w)})},csat:{scoresContainer:w=>({props:{role:"radiogroup","aria-label":w},descriptionNode:L.descriptionNode}),scoreItem:({score:w,label:$,selected:O,disabled:q,currentIndex:te,totalCount:re,hasSelection:K,onChange:T})=>({props:{disabled:q,onClick:()=>T(w),onKeyDown:V=>{var le;if(q)return;let H=null;switch(V.key){case"ArrowRight":case"ArrowDown":H=(te+1)%re;break;case"ArrowLeft":case"ArrowUp":H=(te-1+re)%re;break;default:return}V.preventDefault(),T(H+1);const j=V.currentTarget.parentElement,se=j==null?void 0:j.querySelectorAll('[role="radio"]');(le=se==null?void 0:se[H])==null||le.focus()},tabIndex:O||!K&&te===0?0:-1,role:"radio","aria-checked":O,"aria-disabled":q,...L.describedByProps,"aria-label":Ed(w,re,$,e)}}),submitButton:w=>({"aria-label":w})},form:{button:w=>({"aria-label":w}),textInput:(w,$,O)=>({"aria-label":w,"aria-required":$,"aria-disabled":O}),numberInput:(w,$,O)=>({"aria-label":w,"aria-required":$,"aria-disabled":O}),singleSelectGroup:w=>({role:"radiogroup",...w?{"aria-label":w}:{}}),singleSelectOption:(w,$,O)=>({role:"radio","aria-label":w,"aria-checked":$,"aria-disabled":O}),multiSelectOption:(w,$,O)=>({"aria-label":w,"aria-pressed":$,"aria-disabled":O})}},conversationList:{footer:{button:({onActivate:w})=>({role:"button",tabIndex:0,"aria-label":e.TALK_TO_AGENT,onClick:w,onKeyDown:Wt(w)})},item:({agent:w,status:$,time:O,unreadCount:q,onActivate:te})=>{const re=typeof te<"u",K=re?P:{describedByProps:{},descriptionNode:null};return{props:{...re?{role:"button",tabIndex:0,onClick:te,onKeyDown:Wt(te)}:{},...K.describedByProps,"aria-label":e.A11Y_CONVERSATION_ITEM(w,$,O,q)},hint:re?e.A11Y_HINT_OPEN_CONVERSATION:void 0,descriptionNode:re?K.descriptionNode:void 0}}}}},Er=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:o,onClick:s,ariaLabel:a})=>{const{colors:l}=R.useTheme(),{conversation:u}=ee(),d=s?u.file.interactivePreview({name:e,mimeType:t}):u.file.preview({name:e,mimeType:t}),m={...d,props:{...d.props,...a?{"aria-label":a}:{}}};return i.createElement(bd,{as:s?"button":"div",type:s?"button":void 0,onClick:s,...m.props,$clickable:!!s},i.createElement(vd,{$bgColor:o??l.base.primary},i.createElement(z,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(yd,null,i.createElement(Ls,{variant:"button",color:p.themedColor.textHighEmphasis},e),i.createElement(D,{color:p.themedColor.textMidEmphasis,variant:"caption3"},n)),m.descriptionNode)},bd=_.default.div`border:none;border-radius:12px;gap:8px;width:${Y.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${p.themedColor.textDisabled};background-color:${p.themedColor.bg_50_600};${({$clickable:e})=>e&&Cd}`,Cd=R.css`cursor:pointer;&:hover{background-color:${p.themedColor.bg_100_500};}`,vd=_.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,yd=_.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Sd({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(Ad,null,i.createElement(Er,{name:e.name,mimeType:e.type,type:Qn(e.name,e.type),onClick:r}),t)}const Ad=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${Y.GAP_GROUPED}px;`,Fe=`${we}-incoming-msg`,xd=`${we}-marked-text`;function Td({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:o}=ee(),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.buttonLikeInteractivePreview({name:e.name,mimeType:e.type,onActivate:a}):o.file.preview({name:e.name,mimeType:e.type}),u=()=>s?i.createElement(kd,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(Ld,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${Fe}-media-body`,...l.props};return i.createElement(Id,null,i.createElement(wd,{...d},u(),l.descriptionNode),r)}return null}const Id=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${Y.GAP_GROUPED}px;`,wd=_.default.div`width:${Y.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${W.light`
|
|
82
|
+
background-color: ${p.color.background100};
|
|
54
83
|
`}
|
|
55
|
-
${
|
|
56
|
-
background-color: ${
|
|
84
|
+
${W.dark`
|
|
85
|
+
background-color: ${p.color.background400};
|
|
57
86
|
`}
|
|
58
|
-
`,
|
|
59
|
-
background-color: ${
|
|
87
|
+
`,kd=_.default.img`width:100%;height:100%;object-fit:cover;`,Ld=_.default.video`width:100%;height:100%;object-fit:cover;`,it=({className:e,children:t,size:n=26})=>i.createElement(Md,{className:e,$size:n},t??i.createElement(z,{type:"spinner",size:n})),Md=_.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>De(e)};height:${({$size:e})=>De(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,cn=3,fn=6,Od=fn/cn,Rd=cn,Nd=fn,Dd=e=>{const t=e%cn;return{gridColumns:t>0?fn:cn,wideBottomCount:t}},Ms=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=ee(),o=e.length;if(o===0)return null;const{gridColumns:s,wideBottomCount:a=0}=Dd(o),l=!!n&&!t,u=e.map(C=>C.type??"image/*"),d=u.find(C=>C.startsWith("image")),m=u.find(C=>!C.startsWith("image")),h=l&&d?r.file.openDescription(d):void 0,g=l&&m?r.file.openDescription(m):void 0;return i.createElement(Pd,{$width:Y.BODY_MAX_WIDTH,$columns:s},e.map((C,b)=>{const v=a>0&&b>=o-a,f=()=>!t&&(n==null?void 0:n(b)),y=C.type??"image/*",E=l?r.file.buttonLikeInteractivePreview({name:C.name||"",mimeType:y,onActivate:f}):r.file.preview({name:C.name||"",mimeType:y});let x=1;return s===fn&&(v?x=a===1?Nd:Rd:x=Od),i.createElement(Fd,{key:C.url,$clickable:l,$itemSpan:x,$isPending:t,...E.props},i.createElement($d,{src:C.url,alt:C.name||""}),t&&i.createElement(Bd,null))}),h==null?void 0:h.descriptionNode,g==null?void 0:g.descriptionNode)},$d=({src:e,alt:t})=>{const[n,r]=c.useState(!1),[o,s]=c.useState(!1);return i.createElement(i.Fragment,null,!n&&!o&&i.createElement(Hd,null,i.createElement(it,{size:20},i.createElement(z,{type:"spinner",color:"textLowEmphasis",size:20}))),o?i.createElement(Ud,null,i.createElement(z,{type:"photo",color:"textLowEmphasis",size:24})):i.createElement(Vd,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>s(!0)}))},Pd=_.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Fd=_.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${W.light`
|
|
88
|
+
background-color: ${p.color.background100};
|
|
60
89
|
`}
|
|
61
|
-
${
|
|
62
|
-
background-color: ${
|
|
90
|
+
${W.dark`
|
|
91
|
+
background-color: ${p.color.background400};
|
|
63
92
|
`}
|
|
64
93
|
${e=>e.$itemSpan&&e.$itemSpan>1&&`
|
|
65
94
|
grid-column: span ${e.$itemSpan};
|
|
66
95
|
aspect-ratio: ${e.$itemSpan/2};
|
|
67
96
|
`}
|
|
68
97
|
|
|
98
|
+
&:focus-visible {
|
|
99
|
+
outline: 2px solid ${p.color.primary.main};
|
|
100
|
+
outline-offset: -2px;
|
|
101
|
+
}
|
|
102
|
+
|
|
69
103
|
&:hover {
|
|
70
104
|
${e=>e.$clickable&&!e.$isPending&&`
|
|
71
105
|
& > img {
|
|
@@ -73,29 +107,69 @@
|
|
|
73
107
|
}
|
|
74
108
|
`}
|
|
75
109
|
}
|
|
76
|
-
`,
|
|
77
|
-
background-color: ${
|
|
110
|
+
`,Bd=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${p.color.overlay.dark};pointer-events:none;`,Os=_.default.div`display:flex;align-items:center;justify-content:center;`,Hd=_.default(Os)`position:absolute;inset:0;`,Ud=_.default(Os)`position:absolute;inset:0;${W.light`
|
|
111
|
+
background-color: ${p.color.background200};
|
|
78
112
|
`}
|
|
79
|
-
${
|
|
80
|
-
background-color: ${
|
|
113
|
+
${W.dark`
|
|
114
|
+
background-color: ${p.color.background500};
|
|
81
115
|
`}
|
|
82
|
-
`,
|
|
116
|
+
`,Vd=_.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Gd=({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(zd,null,i.createElement(Ms,{images:e,onClickImage:o}),t)},zd=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${Y.GAP_GROUPED}px;`,Wd="✱",Rs=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Wd}+)`,"g");return e.replace(t,(n,r,o,s)=>r?n:s?`<span id=${xd} aria-label="masked-text">${s}</span>`:n)},qd=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),co=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)}}},Kd=c.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs"))).MarkdownText})),Yd=c.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock}));function jd(e){var o,s;const t=e.maxBodyWidth??Y.BODY_MAX_WIDTH,n=c.useMemo(()=>$i(e.message,Rs),[e.message]),r={id:`${Fe}-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(uo,{...r},e.children):null:i.createElement(uo,{...r},n.map((a,l)=>a.type==="text"?i.createElement(mo,{key:l,variant:"body3"},i.createElement(ln,{fallback:a.value},i.createElement(Kd,{onClickImage:u=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:u,type:"image/*"})}},a.value))):a.type==="code"?i.createElement(ln,{key:l,fallback:i.createElement(mo,{variant:"body3"},a.value)},i.createElement(Yd,{code:a.value,language:a.language})):null),e.children)}const uo=_.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})=>R.css`
|
|
83
117
|
color: ${t||e.colors.messageIncoming.text};
|
|
84
|
-
background-color
|
|
118
|
+
${r==="bubble"?R.css`background-color:${n||e.colors.messageIncoming.background};border-radius:12px;overflow:hidden;padding:12px 0;`:R.css`background-color:transparent;border-radius:0;overflow:visible;padding:0;`}
|
|
85
119
|
`}
|
|
86
|
-
padding: 12px 0;
|
|
87
120
|
transition: max-width 0.3s;
|
|
88
121
|
overflow-wrap: break-word;
|
|
89
|
-
`,
|
|
122
|
+
`,mo=_.default(D)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`;function Ns({id:e,src:t,size:n=56,onClick:r,style:o,...s}){return i.createElement(Xd,{id:e,tabIndex:r?0:void 0,onClick:r,$size:De(n),style:o,...s},t?i.createElement(Zd,{src:t,alt:""}):i.createElement(z,{type:"user",size:n}))}const Xd=_.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:${p.themedColor.bg_100_500};&:focus{outline:none;}${be}`,Zd=_.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,Jd=({sender:e,isBotMessage:t})=>{const n=`${Fe}-sender-avatar`;return t&&!e.profileUrl?i.createElement(Qd,{id:n},i.createElement(z,{type:"delight",size:"100%"})):i.createElement(Ns,{id:n,size:Y.AVATAR_SIZE,src:e.profileUrl})},Qd=_.default.div`flex-shrink:0;width:${Y.AVATAR_SIZE}px;height:${Y.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;}}`,em=({sender:e})=>i.createElement(tm,{id:`${Fe}-sender-name`,variant:"caption1",color:p.themedColor.textMidEmphasis},e.nickname),tm=_.default(D)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,nm=({createdAt:e})=>{const{stringSet:t,format:n}=Q();return e?i.createElement(D,{id:`${Fe}-sent-time`,variant:"caption4",color:p.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Ds="(prefers-reduced-motion: reduce)",rm=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Ds).matches,$s=()=>{const[e,t]=c.useState(rm);return c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(Ds);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},om=({thinkingMessage:e,customStyle:t})=>{const n=$s();return e?i.createElement(am,{$prefersReducedMotion:n},i.createElement(lm,null,e),!n&&i.createElement(cm,null)):i.createElement(sm,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>i.createElement(im,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},sm=_.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};`,im=_.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;}`,am=_.default.div.attrs({id:`${Fe}-typing-indicator`})`
|
|
123
|
+
position: relative;
|
|
124
|
+
overflow: hidden;
|
|
125
|
+
animation: ${({$prefersReducedMotion:e})=>e?"none":"fadeIn 0.4s ease-in-out"};
|
|
126
|
+
@keyframes fadeIn {
|
|
127
|
+
from {
|
|
128
|
+
opacity: 0;
|
|
129
|
+
}
|
|
130
|
+
to {
|
|
131
|
+
opacity: 1;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
`,lm=_.default(D).attrs({variant:"body3"})`
|
|
90
135
|
white-space: pre-wrap;
|
|
91
136
|
word-break: break-word;
|
|
92
|
-
color: ${
|
|
93
|
-
`,
|
|
94
|
-
|
|
95
|
-
|
|
137
|
+
color: ${p.themedColor.textHighEmphasis};
|
|
138
|
+
`,cm=_.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=$r(e.colors.base.background,.5),n=$r(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
139
|
+
`,um=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>fr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return i.createElement(dm,{id:`${Fe}-ext-cta-button`,onClick:r},i.createElement(mm,{variant:"button"},n.label))},dm=_.default.button.attrs({type:"button"})`
|
|
140
|
+
all: unset;
|
|
141
|
+
display: flex;
|
|
142
|
+
width: 100%;
|
|
143
|
+
box-sizing: border-box;
|
|
144
|
+
align-items: center;
|
|
145
|
+
justify-content: center;
|
|
146
|
+
cursor: pointer;
|
|
147
|
+
border-radius: 6px;
|
|
148
|
+
padding: 8px;
|
|
149
|
+
color: ${p.themedColor.textHighEmphasis};
|
|
150
|
+
background-color: ${p.color.background50};
|
|
151
|
+
${W.dark`
|
|
152
|
+
background-color: ${p.color.ondark.textDisabled};
|
|
96
153
|
`}
|
|
97
|
-
|
|
98
|
-
|
|
154
|
+
|
|
155
|
+
${be}
|
|
156
|
+
`,mm=_.default(D)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,hm=({extendedMessagePayload:e,onClickCitation:t=n=>fr(n.link)})=>{const{stringSet:n}=Q(),{theme:r}=ar(),o=e==null?void 0:e.citations;return!o||o.length===0?null:i.createElement(gm,{id:`${Fe}-ext-citation`},i.createElement(fm,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),i.createElement(pm,null,o.map((s,a)=>i.createElement(Em,{key:`${s.embedding_id}-${a}`,onClick:()=>t(s)},i.createElement(z,{type:"source",size:16,color:r.colors.messageIncoming.text}),i.createElement(_m,{variant:"body3",color:r.colors.messageIncoming.text},s.title)))))},gm=_.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,fm=_.default(D)`opacity:0.5;`,pm=_.default.div`display:flex;flex-direction:column;gap:8px;`,_m=_.default(D)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Em=_.default.button.attrs({type:"button"})`
|
|
157
|
+
background: none;
|
|
158
|
+
border: none;
|
|
159
|
+
padding: 0;
|
|
160
|
+
font: inherit;
|
|
161
|
+
color: inherit;
|
|
162
|
+
|
|
163
|
+
display: flex;
|
|
164
|
+
align-items: center;
|
|
165
|
+
gap: 4px;
|
|
166
|
+
cursor: pointer;
|
|
167
|
+
|
|
168
|
+
&:hover {
|
|
169
|
+
opacity: 0.5;
|
|
170
|
+
}
|
|
171
|
+
`,bm=e=>i.createElement(i.Fragment,null),Cm=({visible:e,onClose:t,children:n,"aria-label":r})=>i.createElement(ft,{rootElementId:ce.WINDOW,visible:e,onClose:t,"aria-label":r},i.createElement(Am,null,n)),vm=({onClick:e,destructive:t,icon:n,initialFocus:r,children:o})=>i.createElement(ym,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&i.createElement(Sm,null,i.createElement(z,{type:n,size:24,color:p.themedColor.primary})),o),Ke=Object.assign(Cm,{ActionItem:vm}),ym=_.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?p.themedColor.error:p.themedColor.textHighEmphasis};${be}`,Sm=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Am=_.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};`,jn=e=>`${e}-filled`,xm=e=>e==="good"?Ee.AIAgentMessageFeedbackRating.GOOD:Ee.AIAgentMessageFeedbackRating.BAD,Ps=R.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,ho={good:p.themedColor.secondary,bad:p.themedColor.error},Tm=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:o="",onSubmit:s,isCommentEnabled:a=!1})=>{const{stringSet:l}=Q(),{rootElement:u}=hr(),d=He(u),[m,h]=c.useState(r),[g,C]=c.useState(o),[b,v]=c.useState(!1),f=c.useRef(!1),y=m??r??"good";c.useLayoutEffect(()=>{e?(h(r),C(o)):(h(void 0),C(""))},[e,r,o]),c.useEffect(()=>{if(!e)return;const S=k=>{const M=k;M.metaKey||M.altKey||M.ctrlKey||(f.current=!0)},I=()=>{f.current=!1,v(!1)};return d.addEventListener("keydown",S),d.addEventListener("pointerdown",I),()=>{d.removeEventListener("keydown",S),d.removeEventListener("pointerdown",I)}},[d,e]);const E=()=>{m&&(s({rating:m,comment:g.trim()||void 0}),t())},x=()=>{t()};return e?i.createElement(ft,{rootElementId:ce.WINDOW,visible:e,onClose:x,"aria-label":l.FEEDBACK_TITLE},i.createElement(Im,null,i.createElement(wm,null,i.createElement(D,{variant:"h2",color:p.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),i.createElement(km,null,i.createElement(Lm,null,["good","bad"].map(S=>{const I=m===S,k=S==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD;return i.createElement(Mm,{key:S,$selected:I,$rating:S,onClick:()=>h(S),"data-sb-initial-focus":S===y?"true":void 0},i.createElement(z,{type:I?jn(S):S,size:24,color:I?ho[S]:p.themedColor.textLowEmphasis}),i.createElement(D,{variant:"caption1",color:I?ho[S]:p.themedColor.textLowEmphasis},k))})),a&&i.createElement(Om,null,i.createElement(D,{variant:"caption3",color:p.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),i.createElement(Rm,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:S=>C(S.target.value),onFocus:()=>v(f.current),onBlur:()=>v(!1),maxLength:100,$focusVisible:b,"data-focus-visible":b?"true":"false"}))),i.createElement(Nm,null,i.createElement(Dm,{onClick:x},i.createElement(D,{variant:"button",color:p.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),i.createElement($m,{onClick:E,disabled:!m},i.createElement(D,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT))))):null},Im=_.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,wm=_.default.div`padding:24px;`,km=_.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,Lm=_.default.div`display:flex;gap:4px;`,Mm=_.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${p.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;background-color:${({$selected:e})=>e?p.color.background100:"transparent"};${({$selected:e})=>W.dark`
|
|
172
|
+
background-color: ${e?p.color.background600:"transparent"};
|
|
99
173
|
`}
|
|
100
174
|
|
|
101
175
|
&:hover {
|
|
@@ -105,217 +179,302 @@
|
|
|
105
179
|
&:active {
|
|
106
180
|
opacity: 0.6;
|
|
107
181
|
}
|
|
108
|
-
`,
|
|
109
|
-
|
|
110
|
-
|
|
182
|
+
`,Om=_.default.div`display:flex;flex-direction:column;gap:6px;`,Rm=_.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${p.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${p.themedColor.textHighEmphasis};background-color:${p.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${p.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&R.css`
|
|
183
|
+
outline: 2px solid ${p.themedColor.primary};
|
|
184
|
+
outline-offset: 2px;
|
|
185
|
+
`}
|
|
186
|
+
`,Nm=_.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Fs=_.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;`,Dm=_.default(Fs)`${Ps}`,$m=_.default(Fs)`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};}`,go={good:p.themedColor.secondary,bad:p.themedColor.error},Pm=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:o,extendedMessagePayload:s,onFeedbackUpdate:a})=>{const{stringSet:l}=Q(),{conversation:u}=ee(),[d,m]=c.useState(!1),[h,g]=c.useState(!1),[C,b]=c.useState(void 0),[v,f]=c.useState(""),y=c.useRef(null),E=c.useRef(null),x=c.useRef(null),S=c.useRef(!1),I=u.feedback,k=s==null?void 0:s.feedback,M=(k==null?void 0:k.rating)??"none";if(M!=="none"?!1:!!(n||!e||!r||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const F=O=>{O&&Ce(()=>{const q=O==="good"?y.current:E.current;q==null||q.focus()})},G=({restoreTrigger:O=!0}={})=>{g(!1),O&&F(x.current)},L=O=>{M==="none"?(b(O),f(""),m(!0)):(x.current=O,g(!0))},P=()=>{a==null||a(null),G()},N=()=>{S.current=!0,G({restoreTrigger:!1}),b(k==null?void 0:k.rating),f((k==null?void 0:k.comment)??""),m(!0)},w=O=>{S.current=!1,a==null||a(O),m(!1),F(x.current)},$=()=>{m(!1),S.current&&(S.current=!1,g(!0))};return t&&M!=="none"?i.createElement(fo,{role:"presentation",$horizontal:!0},i.createElement(Fm,null,i.createElement(z,{type:jn(M),size:12,color:go[M]})),(k==null?void 0:k.comment)&&i.createElement(po,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):i.createElement(i.Fragment,null,i.createElement(fo,{role:"presentation"},i.createElement(Bm,{role:"presentation"},["good","bad"].map(O=>{const q=M===O,te=I.button(O,q);return i.createElement(Hm,{key:O,$selected:q,$rating:O,ref:O==="good"?y:E,...te.props,onClick:()=>L(O)},i.createElement(z,{type:q?jn(O):O,size:14,color:q?go[O]:p.themedColor.textMidEmphasis}))})),I.descriptionNode,M!=="none"&&(k==null?void 0:k.comment)&&i.createElement(po,{variant:"caption2"},k.comment)),i.createElement(Ke,{visible:h,onClose:G,...I.optionsBottomSheet},i.createElement(Ke.ActionItem,{onClick:N,initialFocus:!0},l.FEEDBACK_EDIT),i.createElement(Ke.ActionItem,{onClick:P,destructive:!0},l.FEEDBACK_REMOVE)),i.createElement(Tm,{visible:d,onClose:$,isEdit:M!=="none",initialRating:C,initialComment:v,onSubmit:w,isCommentEnabled:o}))},fo=_.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:${Y.BODY_MAX_WIDTH}px;`,Fm=_.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,Bm=_.default.div`display:flex;gap:2px;`,Hm=_.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;border:1px solid ${p.color.background200};background-color:${({$selected:e})=>e?p.color.background100:"transparent"};${({$selected:e})=>W.dark`
|
|
187
|
+
border: 1px solid ${p.color.background400};
|
|
188
|
+
background-color: ${e?p.color.background500:"transparent"};
|
|
111
189
|
`}
|
|
112
190
|
|
|
113
|
-
${
|
|
114
|
-
`,
|
|
115
|
-
color: ${
|
|
191
|
+
${Ps}
|
|
192
|
+
`,po=_.default(D)`color:${p.themedColor.textMidEmphasis};${W.dark`
|
|
193
|
+
color: ${p.themedColor.textHighEmphasis};
|
|
116
194
|
`}
|
|
117
|
-
`,
|
|
118
|
-
background-color: ${
|
|
195
|
+
`,br=R.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;${be}&:disabled{cursor:not-allowed;}`,_o=_.default.button`${br};background-color:${p.themedColor.primary};color:${p.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,Um=_.default.button`${br};color:${p.themedColor.primary};${W.light`
|
|
196
|
+
background-color: ${p.color.background50};
|
|
119
197
|
`};
|
|
120
|
-
${
|
|
121
|
-
background-color: ${
|
|
198
|
+
${W.dark`
|
|
199
|
+
background-color: ${p.color.background700};
|
|
122
200
|
`};
|
|
123
201
|
|
|
124
202
|
&:hover:not(:disabled) {
|
|
125
203
|
opacity: 0.9;
|
|
126
204
|
}
|
|
127
|
-
`,
|
|
128
|
-
background-color: ${
|
|
205
|
+
`,Vm=_.default.button`${br};background-color:transparent;color:${p.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,Gm=e=>{switch(e){case"primary":return _o;case"secondary":return Um;case"clear":return Vm;default:return _o}},zm=_.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);}}`,Wm=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:o=!1,className:s,ariaLabel:a})=>{const l=()=>{switch(n){case"primary":return p.themedColor.textHighEmphasisInverse;case"secondary":return p.themedColor.primary;case"clear":return p.themedColor.textHighEmphasis;default:return p.themedColor.textHighEmphasisInverse}},u=Gm(n);return i.createElement(u,{onClick:t,disabled:r||o,className:s,"aria-label":a},o?i.createElement(zm,null,i.createElement(z,{type:"spinner",size:22,color:l()})):i.createElement(D,{variant:"button",color:l()},e))},qm=({children:e,className:t,style:n,id:r,role:o})=>i.createElement(D,{variant:"caption4",color:p.themedColor.error,className:t,style:n,id:r,role:o},e),Km=({id:e,children:t,className:n,style:r,required:o,ariaHidden:s=!1,"aria-hidden":a})=>{const{stringSet:l}=Q();return i.createElement(D,{id:e,variant:"caption3",color:p.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":a??s},t,!o&&i.createElement("span",{style:{color:p.themedColor.textLowEmphasis}},` (${l.OPTIONAL})`))},Ym=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:o=!1,className:s,disabled:a=!1,max:l,ariaLabel:u,required:d=!1})=>{const m=g=>{const b=g.target.value.replace(/[^0-9.-]/g,""),v=b.split("."),y=v.length>1?v[0]+"."+v.slice(1).join("").replace(/\./g,""):b;if(g.target.value=y,y===""||y==="-")t==null||t(null);else{const E=Number(y);if(!isNaN(E)){if(l!==void 0&&E>l)return;t==null||t(E)}}},h=e==null?"":String(e);return i.createElement(Qm,{type:"text",value:h,onChange:m,placeholder:n,className:s,disabled:a||o,inputMode:"decimal","aria-label":u,"aria-required":d,"aria-disabled":a||o,$error:r,$submitted:o})},jm=R.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;${be}&::placeholder{color:${p.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,Xm=R.css`color:${p.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${W.light`
|
|
206
|
+
background-color: ${p.color.ondark.textMidEmphasis};
|
|
129
207
|
`}
|
|
130
|
-
${
|
|
131
|
-
background-color: ${
|
|
208
|
+
${W.dark`
|
|
209
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
132
210
|
`}
|
|
133
211
|
|
|
134
212
|
&::placeholder {
|
|
135
|
-
color: ${
|
|
213
|
+
color: ${p.themedColor.textLowEmphasis};
|
|
136
214
|
}
|
|
137
|
-
`,
|
|
138
|
-
background-color: ${
|
|
215
|
+
`,Zm=R.css`border:1px solid ${p.themedColor.error};color:${p.themedColor.textHighEmphasis};${W.light`
|
|
216
|
+
background-color: ${p.color.background50};
|
|
139
217
|
`}
|
|
140
|
-
${
|
|
141
|
-
background-color: ${
|
|
218
|
+
${W.dark`
|
|
219
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
142
220
|
`}
|
|
143
|
-
`,
|
|
144
|
-
background-color: ${
|
|
221
|
+
`,Jm=R.css`border:1px solid ${p.themedColor.textDisabled};color:${p.themedColor.textHighEmphasis};${W.light`
|
|
222
|
+
background-color: ${p.color.background50};
|
|
145
223
|
`}
|
|
146
|
-
${
|
|
147
|
-
background-color: ${
|
|
224
|
+
${W.dark`
|
|
225
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
148
226
|
`}
|
|
149
227
|
|
|
150
228
|
&:focus {
|
|
151
|
-
border-color: ${
|
|
229
|
+
border-color: ${p.themedColor.primary};
|
|
152
230
|
}
|
|
153
|
-
`,
|
|
231
|
+
`,Qm=_.default.input`${jm}${({$error:e,$submitted:t})=>t?Xm:e?Zm:Jm}`,eh=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 u=t.filter(d=>d!==a);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,a];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:s=>{r||t!==s&&(n==null||n(s))}}}},Bs=e=>{const{options:t,submitted:n=!1,error:r=!1,className:o,groupLabel:s}=e,{conversation:a}=ee(),l=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=eh(e),m=l?void 0:a.form.singleSelectGroup(s),h=c.useRef([]),g=l?-1:Math.max(t.findIndex(b=>u.includes(b.value)),0),C=(b,v)=>{var E;if(l||n)return;let f=null;switch(b.key){case"ArrowRight":case"ArrowDown":f=(v+1)%t.length;break;case"ArrowLeft":case"ArrowUp":f=(v-1+t.length)%t.length;break;default:return}b.preventDefault();const y=t[f];y&&(d(y.value),(E=h.current[f])==null||E.focus())};return i.createElement(nh,{className:o,...m},t.map((b,v)=>{const f=u.includes(b.value),y=s?`${s}, ${b.label}`:b.label,E=l?a.form.multiSelectOption(y,f,n):a.form.singleSelectOption(y,f,n);return i.createElement(ch,{key:b.value,ref:x=>{h.current[v]=x},type:"button",$active:f,$submitted:n,$error:r,...E,disabled:n,onClick:()=>d(b.value),onKeyDown:x=>C(x,v),tabIndex:l?void 0:v===g?0:-1},i.createElement(D,{variant:"caption1",color:th(f,n)},b.label))}))},th=(e,t)=>t?e?p.themedColor.textHighEmphasis:p.themedColor.textDisabled:e?p.themedColor.primary:p.themedColor.textMidEmphasis,nh=_.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,rh=R.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,oh=R.css`cursor:default;background-color:${p.color.ondark.textMidEmphasis};color:${p.themedColor.textHighEmphasis};${W.dark`
|
|
154
232
|
background-color: transparent;
|
|
155
233
|
border: 1px solid white;
|
|
156
234
|
color: white;
|
|
157
235
|
`}
|
|
158
|
-
`,
|
|
159
|
-
background-color: ${
|
|
160
|
-
color: ${
|
|
236
|
+
`,sh=R.css`cursor:default;${W.light`
|
|
237
|
+
background-color: ${p.color.ondark.textMidEmphasis};
|
|
238
|
+
color: ${p.themedColor.textDisabled};
|
|
161
239
|
`}
|
|
162
|
-
${
|
|
163
|
-
background-color: ${
|
|
164
|
-
border: 1px solid ${
|
|
165
|
-
color: ${
|
|
240
|
+
${W.dark`
|
|
241
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
242
|
+
border: 1px solid ${p.color.onlight.textLowEmphasis};
|
|
243
|
+
color: ${p.themedColor.textDisabled};
|
|
166
244
|
`}
|
|
167
|
-
`,
|
|
168
|
-
background-color: ${
|
|
169
|
-
color: ${
|
|
245
|
+
`,ih=R.css`cursor:pointer;border:1px solid ${p.themedColor.primary};${W.light`
|
|
246
|
+
background-color: ${p.color.background50};
|
|
247
|
+
color: ${p.themedColor.primary};
|
|
170
248
|
`}
|
|
171
|
-
${
|
|
172
|
-
background-color: ${
|
|
173
|
-
color: ${
|
|
249
|
+
${W.dark`
|
|
250
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
251
|
+
color: ${p.themedColor.primary};
|
|
174
252
|
`}
|
|
175
|
-
`,
|
|
176
|
-
background-color: ${
|
|
177
|
-
color: ${
|
|
253
|
+
`,ah=R.css`cursor:pointer;border:1px solid ${p.themedColor.textDisabled};${W.light`
|
|
254
|
+
background-color: ${p.color.background50};
|
|
255
|
+
color: ${p.themedColor.textMidEmphasis};
|
|
178
256
|
`}
|
|
179
|
-
${
|
|
180
|
-
background-color: ${
|
|
181
|
-
color: ${
|
|
257
|
+
${W.dark`
|
|
258
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
259
|
+
color: ${p.themedColor.textMidEmphasis};
|
|
182
260
|
`}
|
|
183
|
-
`,
|
|
184
|
-
${r} ${
|
|
261
|
+
`,lh=R.css`border-color:${p.themedColor.error}!important;`,ch=_.default.button`${rh}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?oh:sh;const r=e?ih:ah;return n?R.css`
|
|
262
|
+
${r} ${lh}
|
|
185
263
|
`:r}}
|
|
186
|
-
|
|
187
|
-
background-color: ${
|
|
264
|
+
`,uh=e=>i.createElement(Bs,{...e,multiple:!1}),dh=e=>i.createElement(Bs,{...e,multiple:!0}),mh=_.default.div`width:100%;height:1px;background-color:${p.themedColor.textDisabled};`,hh=({className:e})=>i.createElement(mh,{className:e}),gh=({id:e,value:t="",onChange:n,placeholder:r,variant:o="single-line",error:s=!1,submitted:a=!1,className:l,disabled:u=!1,maxLength:d,ariaLabel:m,required:h=!1,ariaInvalid:g=!1,ariaErrorMessage:C,"aria-label":b,"aria-required":v,"aria-invalid":f,"aria-errormessage":y,"aria-disabled":E})=>{const S={id:e,value:t,onChange:I=>{const k=I.target.value;d&&k.length>d||n==null||n(k)},placeholder:r,className:l,disabled:u||a,maxLength:d,"aria-label":b??m,"aria-required":v??h,"aria-disabled":E??(u||a),"aria-invalid":f??g,"aria-errormessage":y??C,$error:s,$submitted:a};return o==="multi-line"?i.createElement(ph,{...S}):i.createElement(fh,{...S})},Hs=R.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;${be}&::placeholder{color:${p.themedColor.textLowEmphasis};}`,Us=R.css`color:${p.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${W.light`
|
|
265
|
+
background-color: ${p.color.ondark.textMidEmphasis};
|
|
188
266
|
`}
|
|
189
|
-
${
|
|
190
|
-
background-color: ${
|
|
267
|
+
${W.dark`
|
|
268
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
191
269
|
`}
|
|
192
270
|
|
|
193
271
|
&::placeholder {
|
|
194
|
-
color: ${
|
|
272
|
+
color: ${p.themedColor.textLowEmphasis};
|
|
195
273
|
}
|
|
196
|
-
`,
|
|
197
|
-
background-color: ${
|
|
274
|
+
`,Vs=R.css`border:1px solid ${p.themedColor.error};color:${p.themedColor.textHighEmphasis};${W.light`
|
|
275
|
+
background-color: ${p.color.background50};
|
|
198
276
|
`}
|
|
199
|
-
${
|
|
200
|
-
background-color: ${
|
|
277
|
+
${W.dark`
|
|
278
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
201
279
|
`}
|
|
202
|
-
`,
|
|
203
|
-
background-color: ${
|
|
280
|
+
`,Gs=R.css`border:1px solid ${p.themedColor.textDisabled};color:${p.themedColor.textHighEmphasis};${W.light`
|
|
281
|
+
background-color: ${p.color.background50};
|
|
204
282
|
`}
|
|
205
|
-
${
|
|
206
|
-
background-color: ${
|
|
283
|
+
${W.dark`
|
|
284
|
+
background-color: ${p.color.onlight.textLowEmphasis};
|
|
207
285
|
`}
|
|
208
286
|
|
|
209
287
|
&:focus {
|
|
210
|
-
border-color: ${
|
|
288
|
+
border-color: ${p.themedColor.primary};
|
|
211
289
|
}
|
|
212
|
-
`,
|
|
290
|
+
`,fh=_.default.input`${Hs};height:36px;${({$error:e,$submitted:t})=>t?Us:e?Vs:Gs}`,ph=_.default.textarea`${Hs};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Us:e?Vs:Gs}`,_h=({children:e,className:t,style:n})=>i.createElement(D,{variant:"button",color:p.themedColor.textHighEmphasis,className:t,style:n},e),fe={Title:_h,Label:Km,ErrorLabel:qm,Separator:hh,Button:Wm,TextInput:gh,NumberInput:Ym,SingleSelect:uh,MultiSelect:dh},Eh=1,bh=new Set(["text","number","single-select","multi-select"]),Ch=e=>{var y;const t=(y=e.extendedMessagePayload)==null?void 0:y.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=Q(),{conversation:r}=ee(),[o,s]=c.useState({submitting:!1,canceling:!1}),[a,l]=c.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:g}=Dl(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:E=>{var x;return(x=e.onSubmitForm)==null?void 0:x.call(e,{key:t.key,data:E})},onCancel:()=>{var E;return(E=e.onCancelForm)==null?void 0:E.call(e,{key:t.key})}}),C=u==="submitted",b=async()=>{s(E=>({...E,submitting:!0}));try{await m()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{s(E=>({...E,submitting:!1}))}},v=async()=>{s(E=>({...E,canceling:!0}));try{await h()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{s(E=>({...E,canceling:!1}))}},f=c.useMemo(()=>{const E=()=>t.version>Eh,x=()=>t.fields.some(S=>!bh.has(S.type));return E()||x()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:f.visible?i.createElement(c.Fragment,null,i.createElement(Eo,{$maxWidth:e.maxBodyWidth??Y.BODY_MAX_WIDTH},i.createElement(fe.Title,null,t.title),i.createElement(vh,null,d.map(E=>i.createElement(yh,{key:E.key},i.createElement(fe.Label,{style:{marginBottom:"6px"},required:E.required},E.label),E.type==="text"&&i.createElement(fe.TextInput,{value:E.value||"",placeholder:E.placeholder,onChange:x=>g(E.key,x),disabled:C,error:!!E.error,submitted:C,variant:E.layout==="multiline"?"multi-line":"single-line",maxLength:E.maxLength,ariaLabel:E.label,required:E.required}),E.type==="number"&&i.createElement(fe.NumberInput,{value:E.value||null,placeholder:E.placeholder,onChange:x=>g(E.key,x),disabled:C,error:!!E.error,submitted:C,max:E.max,ariaLabel:E.label,required:E.required}),E.type==="single-select"&&i.createElement(fe.SingleSelect,{options:E.options.map(x=>({label:x,value:x})),value:E.value||"",onChange:x=>g(E.key,x),submitted:C,groupLabel:E.label}),E.type==="multi-select"&&i.createElement(fe.MultiSelect,{options:E.options.map(x=>({label:x,value:x})),value:E.value||[],onChange:x=>g(E.key,x),submitted:C,maxSelect:E.maxSelect,groupLabel:E.label}),E.error&&i.createElement(fe.ErrorLabel,{style:{marginTop:"4px"}},E.error)))),i.createElement(fe.Separator,null),i.createElement(Sh,null,i.createElement(fe.Button,{variant:C?"clear":"primary",ariaLabel:r.form.button(C?n.SUBMITTED:n.BUTTON__SUBMIT)["aria-label"],onClick:b,disabled:C||o.canceling,loading:o.submitting},C?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&i.createElement(fe.Button,{variant:"secondary",ariaLabel:r.form.button(n.BUTTON__CANCEL)["aria-label"],onClick:v,disabled:o.submitting,loading:o.canceling},n.BUTTON__CANCEL))),i.createElement(pr,{...a,onClose:()=>l({visible:!1,title:""})})):i.createElement(Eo,{$maxWidth:e.maxBodyWidth??Y.BODY_MAX_WIDTH},i.createElement(D,{variant:"body3"},f.reason),f.cancelable&&i.createElement(fe.Button,{variant:"primary",ariaLabel:r.form.button(n.BUTTON__CANCEL)["aria-label"],onClick:v,loading:o.canceling},n.BUTTON__CANCEL))},Eo=_.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>R.css`
|
|
213
291
|
color: ${e.colors.messageIncoming.text};
|
|
214
292
|
background-color: ${e.colors.messageIncoming.background};
|
|
215
293
|
`}
|
|
216
294
|
padding: 16px 12px;
|
|
217
295
|
transition: max-width 0.3s;
|
|
218
296
|
overflow-wrap: break-word;
|
|
219
|
-
`,
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
297
|
+
`,vh=_.default.div`display:flex;flex-direction:column;gap:12px;`,yh=_.default.div`display:flex;flex-direction:column;`,Sh=_.default.div`display:flex;flex-direction:column;gap:8px;`,Ah=e=>i.createElement(i.Fragment,null),xh=new Set(["default"]),{MessageTemplate:Th}=Ii.createMessageTemplate({parser:Fn.parser,renderer:Fn.renderer,Container:e=>i.createElement("div",{...e})}),Ih=e=>i.createElement(ln,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},i.createElement(wh,{...e})),wh=({extendedMessagePayload:e,onGetCachedMessageTemplate:t=()=>null,onRequestMessageTemplate:n,onHandleTemplateInternalAction:r=oe})=>{const o=e==null?void 0:e.message_template;if(!xh.has((o==null?void 0:o.type)??"default"))throw new Error("Unsupported template type");if(!n)throw new Error("onRequestMessageTemplate is required");const a=o==null?void 0:o.key;if(!a)throw new Error("Template key is missing");const{theme:l}=hr(),u=xl({onRequestTemplate:n,onGetCachedTemplate:t,theme:l.selectedTheme,templateKey:a,variables:o==null?void 0:o.variables,viewVariables:o==null?void 0:o.view_variables,aiAgentColorVariables:l.aiAgentColorVariables});return i.createElement(kh,{id:`${Fe}-ext-message-template`},i.createElement(Fn.MessageProvider,{handleInternalAction:(d,m)=>{d.stopPropagation(),r==null||r(m)}},i.createElement(Th,{templateItems:u.body.items,templateVersion:u.version})))},kh=_.default.div`box-sizing:border-box;overflow:hidden;width:100%;`,Lh=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=ee(),[o,s]=c.useState(!1),{suggestedReplies:a}=r,l=(e==null?void 0:e.suggested_replies)??[];if(l.length===0||o)return null;const u=d=>{t&&(t({reply:d}),s(!0))};return i.createElement(Mh,{id:`${Fe}-ext-suggested-replies`,role:"presentation",$type:n},l.map((d,m)=>{const h=a.item(d);return i.createElement(Oh,{key:m,$type:n,...h.props,onClick:()=>u(d)},i.createElement(Rh,{variant:"body3"},d))}),a.descriptionNode)},Mh=_.default.div`margin:16px 0;padding:0 ${Y.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?Nh:Dh};`,Oh=_.default.button.attrs({type:"button"})`
|
|
298
|
+
all: unset;
|
|
299
|
+
box-sizing: border-box;
|
|
300
|
+
padding: 8px 12px;
|
|
301
|
+
display: flex;
|
|
302
|
+
align-items: center;
|
|
303
|
+
justify-content: center;
|
|
304
|
+
border-radius: 20px / clamp(20px, 5%, 100px);
|
|
305
|
+
cursor: pointer;
|
|
306
|
+
word-break: break-word;
|
|
307
|
+
color: ${p.color.primary.main};
|
|
308
|
+
border: 1px solid ${p.color.primary.main};
|
|
309
|
+
background-color: ${p.themedColor.bg_50_600};
|
|
310
|
+
|
|
311
|
+
&:hover {
|
|
312
|
+
background-color: ${p.themedColor.bg_100_500};
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
${be}
|
|
316
|
+
|
|
317
|
+
${({$type:e,theme:t})=>R.css`${e==="vertical"?$h:Ph};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
318
|
+
`,Rh=_.default(D)`color:inherit;`,Nh=R.css`flex-direction:column;align-items:flex-end;`,Dh=R.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,$h=R.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,Ph=R.css`white-space:nowrap;`,Fh=e=>{const{components:t}=Je.useContext(),{stringSet:n}=Q(),r=Vo(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})},Bh=e=>i.createElement(zs,{...e,testerMode:!1}),Je=Pe({template:Bh,components:{SenderName:em,SenderAvatar:Jd,SentTime:nm,MessageBody:Fh,TextMessageBody:jd,MediaMessageBody:Td,FileMessageBody:Sd,MultipleFilesMessageBody:Gd,TypingIndicator:om,SuggestedReplies:Lh,MessageTemplate:Ih,CustomMessageTemplate:bm,CTAButton:um,Citation:hm,Form:Ch,Feedback:Pm,MessageLogs:Ah}}),Hh=/(?:!\[[^\]]*]\([^)]+\)|\[[^\]]+]\([^)]+\)|https?:\/\/\S+|www\.\S+)/i,Uh=e=>e?Hh.test(e):!1,zs=e=>{var I,k,M,U,F,G,L;const{components:t}=Je.useContext(),{streamText:n,isAnimating:r}=Wl({text:e.message,enabled:e.isStreaming,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,u=!!((I=o.extendedMessagePayload)!=null&&I.form)&&!((k=o.extendedMessagePayload)!=null&&k.form.canceled_at),d=!!((M=o.extendedMessagePayload)!=null&&M.message_template),m=!!((U=o.extendedMessagePayload)!=null&&U.cta_button),h=!!((F=o.extendedMessagePayload)!=null&&F.citations)&&o.extendedMessagePayload.citations.length>0,g=!!o.createdAt,C=m||h,b=o.messageType==="user"&&!Uh(o.message),v=o.groupType==="top"||o.groupType==="single",f=o.groupType==="bottom"||o.groupType==="single",y=a||!l?0:Y.AVATAR_SIZE,E=P=>b?i.createElement(qh,null,P):P,x=i.createElement(i.Fragment,null,i.createElement(Yh,null,i.createElement(Rn,{$extraStartPadding:y},s?i.createElement(t.TypingIndicator,{...o}):C?i.createElement(Gh,{$maxWidth:o.maxBodyWidth??Y.BODY_MAX_WIDTH},E(i.createElement(t.MessageBody,{...o,surface:"plain"})),m&&i.createElement(zh,{$marginTop:12,$paddingInline:12},i.createElement(t.CTAButton,{...o})),h&&i.createElement(t.Citation,{...o})):E(i.createElement(t.MessageBody,{...o}))),d&&i.createElement(bo,{$startPadding:0,$endPadding:0},i.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??i.createElement(Rn,{$extraStartPadding:y},i.createElement(t.MessageBody,{...o,messageType:"user",message:((L=(G=o.extendedMessagePayload)==null?void 0:G.message_template)==null?void 0:L.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??i.createElement(Rn,{$extraStartPadding:y},i.createElement(t.TypingIndicator,{...o}))})),i.createElement(t.CustomMessageTemplate,{...o}),u&&i.createElement(bo,{$extraStartPadding:y},i.createElement(t.Form,{...o}))),f&&g&&i.createElement(Kh,{$extraStartPadding:y+8,"aria-hidden":"true"},i.createElement(t.SentTime,{...o}))),S=i.createElement(c.Fragment,null,!s&&i.createElement(Rt,{$extraStartPadding:y+8},i.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&i.createElement(t.SuggestedReplies,{...o}));return i.createElement(Vh,{$marginBottom:s?0:mn(o.groupType)},v&&i.createElement(Wh,{"aria-hidden":"true"},!a&&l&&i.createElement(t.SenderAvatar,{...o}),i.createElement(t.SenderName,{...o})),x,S,i.createElement(t.MessageLogs,{...o}))},Vh=_.default.div.attrs({role:"presentation"})`
|
|
319
|
+
display: flex;
|
|
320
|
+
flex-direction: column;
|
|
321
|
+
align-items: flex-start;
|
|
322
|
+
margin-bottom: ${({$marginBottom:e})=>`${e}px`};
|
|
323
|
+
`,Rt=_.default.div.attrs({role:"presentation"})`
|
|
324
|
+
display: flex;
|
|
325
|
+
align-self: stretch;
|
|
326
|
+
justify-content: flex-start;
|
|
327
|
+
${({$startPadding:e=Y.HORIZONTAL_PADDING,$endPadding:t=Y.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
228
328
|
padding-inline: ${e+n}px ${t}px;
|
|
229
329
|
`}
|
|
230
|
-
`,
|
|
330
|
+
`,Gh=_.default.div.attrs({role:"presentation"})`
|
|
331
|
+
display: flex;
|
|
332
|
+
flex-direction: column;
|
|
333
|
+
min-width: 0;
|
|
334
|
+
max-width: min(${({$maxWidth:e})=>e}px, 100%);
|
|
335
|
+
border-radius: 12px;
|
|
336
|
+
overflow: hidden;
|
|
337
|
+
padding: 12px 0;
|
|
338
|
+
${({theme:e})=>R.css`color:${e.colors.messageIncoming.text};background-color:${e.colors.messageIncoming.background};`}
|
|
339
|
+
`,zh=_.default.div.attrs({role:"presentation"})`
|
|
340
|
+
display: flex;
|
|
341
|
+
flex-direction: column;
|
|
342
|
+
min-width: 0;
|
|
343
|
+
${({$marginTop:e=0,$paddingInline:t=0})=>R.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
344
|
+
`,Wh=_.default(Rt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,Rn=_.default(Rt)`display:flex;`,qh=_.default.div.attrs({"aria-hidden":"true",role:"presentation"})``,Kh=_.default(Rt)`margin-top:${Y.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,bo=_.default(Rt).attrs({role:"presentation"})`
|
|
345
|
+
display: flex;
|
|
346
|
+
${({$startPadding:e=Y.HORIZONTAL_PADDING,$endPadding:t=Y.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
231
347
|
padding-inline: ${e+n}px ${t}px;
|
|
232
348
|
`}
|
|
233
|
-
`,
|
|
234
|
-
|
|
349
|
+
`,Yh=_.default.div.attrs({role:"presentation"})`
|
|
350
|
+
display: flex;
|
|
351
|
+
flex-direction: column;
|
|
352
|
+
min-width: 0;
|
|
353
|
+
max-width: 100%;
|
|
354
|
+
gap: ${Y.GAP_GROUPED}px;
|
|
355
|
+
`;function jh({file:e,children:t,onClickFile:n,sendingStatus:r}){const o=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return i.createElement(Xh,null,i.createElement(Er,{name:e.name,mimeType:e.type,type:Qn(e.name,e.type),onClick:o}),t)}const Xh=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${Y.GAP_GROUPED}px;`;function Zh({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s}){const{conversation:a}=ee(),{aspectRatio:l,localFile:u}=n,[d]=c.useState(()=>u instanceof Blob?URL.createObjectURL(u):t.url),[m,h]=c.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})}})(),C=g?a.file.buttonLikeInteractivePreview({name:t.name,mimeType:t.type,onActivate:g}):a.file.preview({name:t.name,mimeType:t.type}),b={...C.props,$ratio:l,$clickable:!!g};return i.createElement(Jh,null,i.createElement(Qh,{...b},!m&&i.createElement(it,{size:26},i.createElement(z,{type:"spinner",color:"textLowEmphasis",size:26})),i.createElement(eg,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),C.descriptionNode),s)}const Jh=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${Y.GAP_GROUPED}px;`,Qh=_.default.div`width:${Y.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;${W.light`
|
|
356
|
+
background-color: ${p.color.background100};
|
|
235
357
|
`}
|
|
236
|
-
${
|
|
237
|
-
background-color: ${
|
|
358
|
+
${W.dark`
|
|
359
|
+
background-color: ${p.color.background400};
|
|
238
360
|
`}
|
|
239
|
-
`,
|
|
361
|
+
`,eg=_.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;`,tg=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s})=>{const[a]=c.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),l=e==="pending",u=e==="failed",d=m=>{if(u||l)return;const h=a[m];h&&(o?o({files:a,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return i.createElement(ng,null,i.createElement(Ms,{images:a,isPending:l,onClickImage:d}),s)},ng=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${Y.GAP_GROUPED}px;`;function rg(e){var n,r;const t=c.useMemo(()=>{const o=qd(Rs(e.message));return Fo.default.sanitize(o)},[e.message]);return i.createElement(og,{$maxWidth:e.maxBodyWidth??Y.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},i.createElement(sg,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const og=_.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>R.css`
|
|
240
362
|
color: ${t||e.colors.messageOutgoing.text};
|
|
241
363
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
242
364
|
`}
|
|
243
365
|
padding: 12px 0;
|
|
244
366
|
transition: max-width 0.3s;
|
|
245
367
|
overflow-wrap: break-word;
|
|
246
|
-
`,
|
|
247
|
-
`,
|
|
248
|
-
`,Iu=h.default(Mo)``,wu=h.default(Mo)`margin-top:${H.BODY_TIME_GAP}px;`,ku=e=>e.messageType!=="admin"?null:s.createElement(Mu,null,s.createElement(T,{variant:"caption2",color:m.themedColor.textMidEmphasis},$u(Ur.default.sanitize(e.message)))),Mu=h.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${H.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,$u=e=>{try{const t=[];let n=e,r=0;for(;n;){const o=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),i=n.match(/\*\*([^*]+)\*\*/),a=[o&&{match:o,type:"link"},i&&{match:i,type:"bold"}].filter(p=>!!p);if(!a.length){t.push(n);break}const l=a.reduce((p,E)=>E.match.index<p.match.index?E:p),{match:c,type:u}=l,g=c.index;g>0&&t.push(n.slice(0,g)),u==="link"?t.push(s.createElement("a",{key:r++,href:c[2],target:"_blank",rel:Fn},c[1])):u==="bold"&&t.push(s.createElement("strong",{key:r++},c[1])),n=n.slice(g+c[0].length)}return t.filter(o=>o!=="")}catch{return[e]}},$o=({onClick:e,checked:t,label:n,disabled:r,labelVariant:o="caption2"})=>{const i=t?m.themedColor.primary:r?m.themedColor.textDisabled:m.themedColor.textLowEmphasis,a=t?m.themedColor.textHighEmphasis:r?m.themedColor.textLowEmphasis:m.themedColor.textHighEmphasis;return s.createElement(Ou,{onClick:e,disabled:r},s.createElement(Lu,null,s.createElement(F,{size:20,type:t?"radio-on":"radio-off",color:i})),s.createElement(Ru,{variant:o,color:a},n))},Lu=h.default.div`width:20px;height:20px;`,Ru=h.default(T)`line-height:20px;word-break:break-word;`,Ou=h.default.button`all:unset;display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;&:enabled{cursor:pointer;}`,Du=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:o})=>(d.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(o==null||o(n))},[r,n]),e.cre?s.createElement(Nu,null,s.createElement(J.Label,{required:e.cre.required},e.cre.question),s.createElement(Pu,null,[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(i=>s.createElement($o,{key:i.label,checked:r===i.value,label:i.label,disabled:t,onClick:()=>o==null?void 0:o(i.value)})))):null),Nu=h.default.div`display:flex;flex-direction:column;gap:8px;`,Pu=h.default.div`display:flex;flex-direction:column;gap:8px;`,Fu=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:i}=K();return s.createElement(Bu,null,s.createElement(J.Label,{required:e.required},e.question),e.response_type==="free_text"&&s.createElement(J.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:a=>r(a),error:o}),e.response_type==="single_choice"&&s.createElement(Uu,null,e.options.map(a=>s.createElement($o,{key:a,checked:n===a,label:a,disabled:t,onClick:()=>r==null?void 0:r(a),labelVariant:"body3"}))),o&&s.createElement(J.ErrorLabel,null,i.FORM_VALIDATION_REQUIRED))},Bu=h.default.div`display:flex;flex-direction:column;gap:8px;`,Uu=h.default.div`display:flex;flex-direction:column;gap:8px;`,Hu=({value:e,selected:t,label:n})=>s.createElement(Vu,{$selected:t,"aria-label":n},zu[e-1]),Vu=h.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,zu=[s.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s.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)"}),s.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"}),s.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"}),s.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"}),s.createElement("defs",null,s.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},s.createElement("stop",{stopColor:"#FF2D1D"}),s.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},s.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"}),s.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"}),s.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"}),s.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"})),s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},s.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"}),s.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"}),s.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"})),s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},s.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"}),s.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"}),s.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"})),s.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},s.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"}),s.createElement("g",{clipPath:"url(#clip0_159_173224)"},s.createElement("g",{clipPath:"url(#clip1_159_173224)"},s.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"})),s.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},s.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"})),s.createElement("g",{mask:"url(#mask0_159_173224)"},s.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"}))),s.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"}),s.createElement("defs",null,s.createElement("clipPath",{id:"clip0_159_173224"},s.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),s.createElement("clipPath",{id:"clip1_159_173224"},s.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],Gu=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u";return s.createElement(qu,null,s.createElement(T,{variant:"caption3",color:m.themedColor.textMidEmphasis},e.csat_question),s.createElement(Ku,null,e.csat_scores.map(({label:i,image_url:a},l)=>{const c=l+1,u=n===c;return s.createElement(ju,{key:l,disabled:t,onClick:()=>r(c)},s.createElement(Wu,{value:c,selected:o||u,label:i,src:a}),!!i&&s.createElement(T,{color:u?m.themedColor.textHighEmphasis:m.themedColor.textLowEmphasis,variant:"caption3"},i))})))},Wu=({value:e,src:t,label:n,selected:r})=>{const[o,i]=d.useState(!1),a=o?s.createElement(Hu,{value:e,selected:r,label:n}):s.createElement(Zu,{$selected:r,"aria-label":n,src:t,onError:()=>i(!0)});return s.createElement(Yu,null,a)},qu=h.default.div`display:flex;flex-direction:column;gap:8px;`,Ku=h.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,ju=h.default.button`background-color:transparent;border:none;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;&:hover:not(:disabled) span{color:${m.themedColor.textHighEmphasis};}`,Yu=h.default.div`button:hover:not(:disabled) &{border-radius:4px;cursor:pointer;background-color:${m.color.background200};${B.dark`
|
|
249
|
-
background-color: ${
|
|
368
|
+
`,sg=_.default(D)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,ig=({sendingStatus:e})=>{const t=R.useTheme();switch(e){case"pending":return i.createElement(ag,{size:16},i.createElement(z,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return i.createElement("div",{style:{marginBottom:2}},i.createElement(z,{type:"error",color:p.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return i.createElement("div",{style:{marginBottom:2}},i.createElement(z,{type:"done",color:p.themedColor.secondary,size:16}))}},ag=_.default(it)`margin-bottom:2px;width:16px;height:16px;`,lg=({createdAt:e})=>{const{stringSet:t,format:n}=Q();return e?i.createElement(D,{variant:"caption4",color:p.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},cg=e=>{const{components:t}=Nt.useContext(),{stringSet:n}=Q(),r=()=>{const u=Vo(e)?i.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?u:e.messageType==="file"?e.file.type.startsWith("image")?i.createElement(t.MediaMessageBody,{...e},u):i.createElement(t.FileMessageBody,{...e},u):e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},u):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},o=e.sendingStatus==="failed"&&e.onClickFailedMessage,s=()=>{var u;return(u=e.onClickFailedMessage)==null?void 0:u.call(e)},l=o?{role:"button",tabIndex:0,onClick:s,onKeyDown:u=>{u.repeat||(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),s())}}:{};return i.createElement("div",{...l,style:{display:"contents",cursor:o?"pointer":"default"}},r())},ug=e=>{const{components:t}=Nt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single",o=e.messageType==="user"&&e.sendingStatus!=="failed";return i.createElement(dg,{$marginBottom:mn(e.groupType)},i.createElement(mg,{"aria-hidden":o?"true":void 0},i.createElement(t.MessageBody,{...e})),r&&i.createElement(hg,{$extraEndPadding:8,"aria-hidden":n?"true":void 0},n?i.createElement(t.SentTime,{...e}):i.createElement(t.SendingStatus,{...e})))},Nt=Pe({template:ug,components:{SendingStatus:ig,SentTime:lg,MessageBody:cg,TextMessageBody:rg,MediaMessageBody:Zh,FileMessageBody:jh,MultipleFilesMessageBody:tg}}),dg=_.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
369
|
+
`,Ws=_.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=Y.HORIZONTAL_PADDING,$endPadding:t=Y.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
370
|
+
`,mg=_.default(Ws)``,hg=_.default(Ws)`margin-top:${Y.BODY_TIME_GAP}px;`,gg=e=>e.messageType!=="admin"?null:i.createElement(fg,null,i.createElement(D,{variant:"caption2",color:p.themedColor.textMidEmphasis},pg(Fo.default.sanitize(e.message)))),fg=_.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${Y.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,pg=e=>{try{const t=[];let n=e,r=0;for(;n;){const o=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),s=n.match(/\*\*([^*]+)\*\*/),a=[o&&{match:o,type:"link"},s&&{match:s,type:"bold"}].filter(h=>!!h);if(!a.length){t.push(n);break}const l=a.reduce((h,g)=>g.match.index<h.match.index?g:h),{match:u,type:d}=l,m=u.index;m>0&&t.push(n.slice(0,m)),d==="link"?t.push(i.createElement("a",{key:r++,href:u[2],target:"_blank",rel:mr},u[1])):d==="bold"&&t.push(i.createElement("strong",{key:r++},u[1])),n=n.slice(m+u[0].length)}return t.filter(o=>o!=="")}catch{return[e]}},_g=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,qs=({options:e,value:t,disabled:n,hasError:r=!1,errorId:o,onChange:s})=>{const a=c.useRef([]),l=e.findIndex(h=>h.value===t),u=l>=0?l:0,d=h=>{requestAnimationFrame(()=>{var g;(g=a.current[h])==null||g.focus()})},m=h=>{const g=e[h];!g||n||(s==null||s(g.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&o?{"aria-invalid":!0,"aria-errormessage":o}:{}}),getRadioProps:h=>({ref:g=>{a.current[h]=g},tabIndex:n?-1:h===u?0:-1,describedBy:r&&o?o:void 0,onArrowNavigate:g=>{m(_g({direction:g,currentIndex:h,totalCount:e.length}))}})}},Eg=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},bg=({event:e,onClick:t,onArrowNavigate:n})=>{if(Cg(e))return;const r=Eg(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},Cg=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Cr=c.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:o=0,labelVariant:s="caption2",describedBy:a,onArrowNavigate:l},u)=>{const d=t?p.themedColor.primary:r?p.themedColor.textDisabled:p.themedColor.textLowEmphasis,m=t?p.themedColor.textHighEmphasis:r?p.themedColor.textLowEmphasis:p.themedColor.textHighEmphasis;return i.createElement(Sg,{ref:u,role:"radio",tabIndex:r?-1:o,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":a,onClick:r?void 0:e,onKeyDown:h=>bg({event:h,onClick:e,onArrowNavigate:l})},i.createElement(vg,{"aria-hidden":"true"},i.createElement(z,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(yg,{"aria-hidden":"true",variant:s,color:m},n))});Cr.displayName="Radio";const vg=_.default.div`width:20px;height:20px;`,yg=_.default(D)`line-height:20px;word-break:break-word;`,Sg=_.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${be}&[aria-disabled='false']{cursor:pointer;}`,Ag=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:o})=>{var u,d;const s=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],a=qs({options:s,value:r,disabled:t,onChange:o});if(c.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(o==null||o(n))},[r,n]),!e.cre)return null;const l=e.cre;return i.createElement(xg,null,i.createElement(fe.Label,{required:l.required,ariaHidden:!0},l.question),i.createElement(Tg,{...a.radioGroupProps(l.question)},s.map((m,h)=>i.createElement(Cr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(h),onClick:()=>o==null?void 0:o(m.value)}))))},xg=_.default.div`display:flex;flex-direction:column;gap:8px;`,Tg=_.default.div`display:flex;flex-direction:column;gap:8px;`,Ig=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:s}=Q(),a=c.useId(),l=e.response_type!=="free_text",u={ariaInvalid:o,ariaErrorMessage:o?a:void 0},d=e.response_type==="single_choice"?e.options.map(h=>({label:h,value:h})):[],m=qs({options:d,value:n,disabled:t,hasError:o,errorId:a,onChange:r});return i.createElement(wg,null,i.createElement(fe.Label,{required:e.required,ariaHidden:l},e.question),e.response_type==="free_text"&&i.createElement(fe.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:h=>r(h),error:o,ariaLabel:s.A11Y_CSAT_TEXT_INPUT_LABEL,required:e.required,ariaInvalid:u.ariaInvalid,ariaErrorMessage:u.ariaErrorMessage}),e.response_type==="single_choice"&&i.createElement(kg,{...m.radioGroupProps(e.question)},d.map((h,g)=>i.createElement(Cr,{key:h.value,checked:n===h.value,label:h.label,disabled:t,...m.getRadioProps(g),onClick:()=>r==null?void 0:r(h.value),labelVariant:"body3"}))),o&&i.createElement(Lg,{role:"alert",id:a},s.FORM_VALIDATION_REQUIRED))},wg=_.default.div`display:flex;flex-direction:column;gap:8px;`,kg=_.default.div`display:flex;flex-direction:column;gap:8px;`,Lg=_.default(fe.ErrorLabel)``,Mg=({value:e,selected:t})=>i.createElement(Og,{$selected:t,"aria-hidden":"true"},Rg[e-1]),Og=_.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Rg=[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)"}))))],Ng=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",{conversation:s}=ee(),a=s.csat.scoresContainer(e.csat_question);return i.createElement($g,null,i.createElement(D,{variant:"caption3",color:p.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(Pg,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:u},d)=>{const m=d+1,h=n===m,g=e.csat_scores.length,C=s.csat.scoreItem({score:m,label:l,selected:h,disabled:t,currentIndex:d,totalCount:g,hasSelection:!o,onChange:r});return i.createElement(Fg,{key:d,type:"button",...C.props},i.createElement(Dg,{value:m,selected:o||h,src:u}),!!l&&i.createElement(D,{"aria-hidden":"true",color:h?p.themedColor.textHighEmphasis:p.themedColor.textLowEmphasis,variant:"caption3"},l))})))},Dg=({value:e,src:t,selected:n})=>{const[r,o]=c.useState(!1),s=r?i.createElement(Mg,{value:e,selected:n}):i.createElement(Hg,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>o(!0)});return i.createElement(Bg,null,s)},$g=_.default.div`display:flex;flex-direction:column;gap:8px;`,Pg=_.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Fg=_.default.button`all:unset;background-color:transparent;border:none;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;&:not(:disabled):hover span{color:${p.themedColor.textHighEmphasis};}`,Bg=_.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${p.color.background200};${W.dark`
|
|
371
|
+
background-color: ${p.color.background500};
|
|
250
372
|
`}
|
|
251
373
|
}
|
|
252
|
-
`,
|
|
374
|
+
`,Hg=_.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Ug=({csatPayload:e})=>i.createElement(D,{variant:"button",color:p.themedColor.textHighEmphasis},e.title),Nn=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:s})=>{const{params:a,setParams:l,error:u,setError:d,followUpItem:m,state:h,validateParams:g,itemProps:C}=Ul({csatPayload:e,type:t,initialCsat:r,initialCsatReason:o,initialIsResolved:s});return i.createElement(i.Fragment,null,i.createElement(Vg,null,i.createElement(Ug,{...C}),t===Ne.AI_AGENT_CSAT_5_WITH_CRE&&i.createElement(Ag,{...C,defaultValue:s,value:a.isResolved,onChange:b=>l({isResolved:b})}),i.createElement(Ng,{...C,value:a.csat,onChange:b=>l({csat:b})}),m&&i.createElement(Ig,{...C,followUpItem:m,value:a.csatReason,onChange:b=>{l({csatReason:b}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&i.createElement(i.Fragment,null,i.createElement(fe.Separator,null),n({state:h,params:a,validateParams:g})))},Vg=_.default.div`display:flex;flex-direction:column;gap:12px;`,Gg=e=>{const{stringSet:t}=Q();return ca(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})},zg=()=>{const{stringSet:e}=Q();return i.createElement(D,{variant:"body2",color:p.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},Wg=({onMount:e,children:t})=>(c.useEffect(()=>{e&&Ce(e)},[]),t),qg=e=>{const{conversation:t}=ee(),{announceStatusText:n,announceError:r}=st();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:o,onSubmitCSAT:s,onScrollToBottom:a}=e,{csat:l,csatReason:u,csatExpireAt:d,isResolvedWhenDeterminedByUser:m}=e,h=Ye.useForceUpdate(),g=Gg(o==null?void 0:o.csat),C=c.useRef(null),b=c.useRef(!1),v=c.useRef(null),f=c.useRef(typeof l=="number"),y=(g==null?void 0:g.csat_submitted_label)??"",E=!!g&&g.visibility&&!!Ne[g.type];if(c.useEffect(()=>{E&&y&&(typeof l!="number"||f.current||(f.current=!0,n(y),Ce(()=>{var I;(I=v.current)==null||I.focus()})))},[n,l,E,y]),!E||!g)return null;const x=()=>{var k;const I=(k=C.current)==null?void 0:k.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},S=g.type===Ne.AI_AGENT_CSAT_5||g.type===Ne.AI_AGENT_CSAT_5_WITH_CRE||g.type===Ne.HELPDESK_CSAT_5?Nn:()=>null;return i.createElement(Kg,{ref:C},!l&&Rr(d)?i.createElement(zg,null):i.createElement(S,{csatPayload:g,type:g.type,initialCsat:l,initialCsatReason:u,initialIsResolved:m,renderSubmitButton:({state:I,params:k,validateParams:M})=>I==="submitted"?i.createElement(jg,{ref:v,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":y,tabIndex:-1},i.createElement(D,{variant:"button","aria-hidden":"true"},g.csat_submitted_label)):i.createElement(Wg,{onMount:a},i.createElement(Yg,{type:"button",...t.csat.submitButton(g.csat_submit_label),onClick:async()=>{if(b.current)return;const U=Rr(d);!U&&M()?(b.current=!0,await s(k).finally(()=>{b.current=!1})):(h(),U||Ce(()=>{r({type:"csatFormError"},x())}))}},i.createElement(D,{variant:"button"},g.csat_submit_label)))}))},Kg=_.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,Yg=_.default.button`all:unset;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;${be}&:hover{background-color:${p.color.primary.dark};}`,jg=_.default.div`color:${p.themedColor.textHighEmphasis};background-color:${p.themedColor.textDisabled};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;`,Xg=e=>{const{components:t}=pn.useContext(),n=e.messageType==="admin"?i.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?i.createElement(t.CSATMessage,{...e}):null;return i.createElement(Zg,{$marginBottom:mn(e.groupType)},n)},pn=Pe({template:Xg,components:{AdminMessage:gg,CSATMessage:qg}}),Zg=_.default.div`padding-inline:${Y.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Co={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Ks=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,onClickActionbook:o,onClickFunctionCall:s,onClickFunctionCallDetail:a,onClickGroundedness:l,onClickAgentMessageTemplate:u,bottomContent:d,renderCustomGroundednessIcon:m=g=>g.default,style:h={}})=>{const{iconColor:g="#000000",textColor:C="#000000",highlightColor:b=xt.DEFAULT_PRIMARY}=h;return i.createElement(vo,null,e&&i.createElement(vo,null,i.createElement(un,null,i.createElement(Kt,null,i.createElement(z,{size:16,type:"actionbook",color:g})),i.createElement(qt,{$clickable:!!o,$highlightColor:b,variant:"body2",color:C,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(v=>i.createElement(Dn,{key:v.key},i.createElement(Kt,null,i.createElement(z,{size:16,type:"function",color:g})),i.createElement(un,null,i.createElement(qt,{$clickable:!!s,$highlightColor:b,variant:"body2",color:C,onClick:()=>s==null?void 0:s(v),maxTextLines:1},v.name),a&&i.createElement(Qg,{role:"button",onClick:()=>a==null?void 0:a(v)},i.createElement(D,{variant:"body2",color:b},"View details"),i.createElement(z,{type:"chevron-right",size:16,color:b}))))),n==null?void 0:n.map(v=>i.createElement(Dn,{key:v.id},i.createElement(Kt,null,m({default:i.createElement(z,{size:16,type:Co[v.source_type]??Co.snippet,color:g}),sourceType:v.source_type})),i.createElement(qt,{$clickable:!!l,$highlightColor:b,variant:"body2",color:C,onClick:()=>l==null?void 0:l(v),maxTextLines:1},v.preview_title))),r==null?void 0:r.map(v=>i.createElement(Dn,{key:v.key},i.createElement(Kt,null,i.createElement(z,{size:16,type:"template",color:g})),i.createElement(qt,{$clickable:!!u,$highlightColor:b,variant:"body2",color:C,onClick:()=>u==null?void 0:u(v),maxTextLines:1},v.name))),d)},Jg=_.default(D)`font-weight:400;`,qt=_.default(Jg)`${({$clickable:e,$highlightColor:t})=>e&&R.css`
|
|
253
375
|
cursor: pointer;
|
|
254
376
|
text-decoration: underline;
|
|
255
377
|
&:hover {
|
|
256
378
|
color: ${t};
|
|
257
379
|
}
|
|
258
380
|
`}
|
|
259
|
-
`,St=h.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Nt=h.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,lm=h.default(Nt)`cursor:pointer;gap:4px;`,un=h.default(Nt)`flex-direction:row;align-items:center;`,Mr=h.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ro=d.createContext(null);function cm({testerType:e,origin:t,children:n}){return s.createElement(Ro.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&s.createElement(dm,null),n)}const Xe=()=>{const e=d.useContext(Ro);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},dm=()=>{const{isActionbookTester:e}=Xe();return s.createElement(De.Template,{template:e?um:void 0},s.createElement(De.MessageLogs,{component:mm}))},um=e=>s.createElement(ko,{...e,testerMode:!0,maxBodyWidth:H.WIDE_BODY_MAX_WIDTH}),mm=({extendedMessagePayload:e={}})=>{const{handlers:t}=j(),{manual:n,groundedness:r,function_calls:o,agent_message_templates:i,is_thinking:a}=e;return a||!n&&!(r!=null&&r.length)&&!(o!=null&&o.length)&&!(i!=null&&i.length)?s.createElement(s.Fragment,null):s.createElement(hm,null,s.createElement(gm,{width:4}),s.createElement(Lo,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:m.themedColor.textHighEmphasis,textColor:m.themedColor.textHighEmphasis,barColor:m.themedColor.textDisabled},bottomContent:s.createElement(fm,{variant:"caption2",color:m.themedColor.textLowEmphasis},"Only visible in the tester")}))},hm=h.default.div`display:flex;gap:16px;margin:16px ${H.HORIZONTAL_PADDING}px 0;align-self:stretch;`,gm=h.default.div`width:${({width:e})=>e}px;background-color:${m.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,fm=h.default(T)`margin-top:5px;`,pm=d.forwardRef(function(t,n){const{messages:r,renderMessage:o,loading:i,LoadingComponent:a,error:l,ErrorComponent:c,empty:u,EmptyComponent:g,messageTopArea:p,messageBottomArea:E,overlayArea:v,onLoadPrev:x,onLoadNext:_,loadThreshold:f=.05,onScroll:b=be,depsForResetScrollPositionToBottom:y,stackDirection:w="top",bottomSpacerHeight:A=0,ariaLabel:L}=t,$=d.useRef(null),S=d.useCallback(N=>{$.current=N,n&&(typeof n=="function"?n(N):n.current=N)},[n]),R=d.useRef(!1),P=d.useRef(void 0),O=d.useRef(0),I=d.useRef(0);d.useLayoutEffect(()=>{$.current&&($.current.scrollTop=$.current.scrollHeight)},y),d.useLayoutEffect(()=>{$.current&&(P.current==="top"&&($.current.scrollTop=$.current.scrollHeight-I.current),P.current==="bottom"&&($.current.scrollTop=O.current),P.current=void 0)},[$.current,r.length]);const U=async N=>{if(b==null||b(N),!$.current)return;const z=$.current;if(I.current=z.scrollHeight-z.scrollTop,O.current=z.scrollTop,R.current)return;const Y=z.clientHeight*Math.min(Math.max(0,f),1);z.scrollTop<=Y?(R.current=!0,P.current="top",await x(),R.current=!1):z.scrollHeight-z.scrollTop-z.clientHeight<=Y?(R.current=!0,P.current="bottom",await _(),R.current=!1):P.current=void 0};return l?s.createElement(s.Fragment,null,c):i?s.createElement(s.Fragment,null,a):s.createElement(Em,{id:"infinite-list-container"},s.createElement(_m,{id:"infinite-list-inner",ref:S,onScroll:U,role:"list","aria-label":L},w==="bottom"&&s.createElement("div",{style:{flexGrow:1}}),p,u?g:r.map((N,z)=>o({message:N,index:z})),E,A>0&&s.createElement("div",{style:{minHeight:A}})),s.createElement(bm,{id:"infinite-list-overlay-container"},s.createElement(Cm,{id:"infinite-list-overlay"},v)))}),Em=h.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,_m=h.default.div`display:flex;flex:1;flex-direction:column;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${m.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,bm=h.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,Cm=h.default.div`pointer-events:auto;`,xm=e=>Ie(e)||zr(e);function vm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function ym(e,t){return e.filter(n=>ke.isWelcomeMessage(n,t))}const xe=({as:e,type:t,size:n=16,color:r,disabled:o,...i})=>{const a=o?m.themedColor.textDisabled:m.themedColor.textHighEmphasis;return s.createElement(Sm,{as:e,disabled:o,...i},s.createElement(F,{type:t,size:n,color:r??a}))},Sm=h.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;&:disabled{cursor:not-allowed;}`,Am=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{var L,$;const[o,i]=d.useState(t),[a,l]=d.useState(!1),{stringSet:c,format:u}=K(),{config:g}=j(),p=e.length,E=e[o],v=(($=(L=g==null?void 0:g.conversation)==null?void 0:L.fileViewer)==null?void 0:$.downloadEnabled)!==!1,x=p>1,_=(E==null?void 0:E.type)||"",f=Ie(_),b=zr(_),y=!xm(_);d.useEffect(()=>{r&&(i(t),l(!1))},[r,t]);const w=d.useCallback(()=>{o>0&&(i(S=>S-1),l(!1))},[o]),A=d.useCallback(()=>{o<p-1&&(i(S=>S+1),l(!1))},[o,p]);return d.useEffect(()=>{if(!r)return;const S=R=>{R.key==="ArrowLeft"?w():R.key==="ArrowRight"?A():R.key==="Escape"&&n()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[r,w,A,n]),!r||!E?null:s.createElement(Ze,{onClose:n,visible:r,rootElementId:ae.MODAL_ROOT},s.createElement(Tm,null,s.createElement(Im,null,s.createElement(wm,null,s.createElement(km,null,s.createElement(T,{variant:"button",maxTextLines:1,color:m.themedColor.textHighEmphasis},E.name||c.IMAGE_VIEWER__DEFAULT_TITLE),E.timestamp&&s.createElement(T,{variant:"caption2",color:m.themedColor.textMidEmphasis},u(new Date(E.timestamp),"h:mm a")))),s.createElement(Mm,{type:"close",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),s.createElement($m,{onClick:S=>S.currentTarget===S.target&&n()},x&&s.createElement($r,{$position:"left",type:"chevron-right",size:32,onClick:w,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),s.createElement(Lm,null,f&&s.createElement(s.Fragment,null,!a&&s.createElement(Rm,null,s.createElement(Ge,{size:32},s.createElement(F,{type:"spinner",color:"textLowEmphasis",size:32}))),s.createElement(Om,{src:E.url,alt:E.name||"Image",$loaded:a,onLoad:()=>l(!0)})),b&&s.createElement(Dm,{controls:!0},s.createElement("source",{src:E.url,type:_})),y&&s.createElement(Nm,null,s.createElement(T,{variant:"h1",color:m.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),x&&s.createElement($r,{$position:"right",type:"chevron-right",size:32,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===p-1})),s.createElement(Pm,null,s.createElement(Fm,null),x&&s.createElement(T,{variant:"body3",color:m.themedColor.textHighEmphasis},o+1,"/",p),s.createElement(Bm,null,v&&!y&&s.createElement(xe,{as:"a",href:E.url,download:E.name||"file",type:"download",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD})))))},Tm=h.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${m.themedColor.bg_50_600};`,Im=h.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 16px;min-height:56px;border-bottom:1px solid ${m.themedColor.textDisabled};`,wm=h.default.div`flex:1;min-width:0;padding-right:16px;`,km=h.default.div`display:flex;flex-direction:column;gap:2px;`,Mm=h.default(xe)`flex-shrink:0;width:32px;height:32px;border-radius:50%;&:hover{background-color:${m.themedColor.bg_100_500};}`,Gt=h.default.div`display:flex;align-items:center;justify-content:center;`,$m=h.default(Gt)`flex:1;min-height:0;position:relative;padding:0 16px;`,Lm=h.default(Gt)`position:relative;max-width:100%;max-height:100%;`,Rm=h.default(Gt)`position:absolute;inset:0;`,Om=h.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;`,Dm=h.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Nm=h.default(Gt)`flex-direction:column;gap:16px;`,$r=h.default(xe)`position:absolute;${e=>e.$position==="left"?"left: 16px;":"right: 16px;"}top:50%;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;&:hover:not(:disabled){background-color:${m.themedColor.bg_200_400};}&:disabled{opacity:0.3;}@media (max-width:480px){width:38px;height:38px;${e=>e.$position==="left"?"left: 8px;":"right: 8px;"}}`,Pm=h.default.footer`display:flex;align-items:center;justify-content:space-between;padding:16px;min-height:56px;border-top:1px solid ${m.themedColor.textDisabled};`,Fm=h.default.div`width:40px;`,Bm=h.default.div`display:flex;align-items:center;justify-content:flex-end;width:40px;`,Oo=({title:e,description:t,negativeText:n,positiveText:r,onCancel:o,onConfirm:i})=>s.createElement(Um,null,s.createElement(Hm,null,s.createElement(T,{as:"div",variant:"h2",color:m.themedColor.textHighEmphasis},e)),s.createElement(Vm,null,s.createElement(T,{as:"div",variant:"body3",color:m.themedColor.textMidEmphasis},t)),s.createElement(zm,null,s.createElement(Gm,{type:"button",onClick:o},s.createElement(T,{variant:"button",color:m.themedColor.textHighEmphasis},n)),s.createElement(Wm,{type:"button",onClick:i},s.createElement(T,{variant:"button",color:m.themedColor.textHighEmphasisInverse},r)))),Um=h.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${m.color.background50};${B.dark`
|
|
260
|
-
background-color: ${
|
|
381
|
+
`,Kt=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,un=_.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Qg=_.default(un)`cursor:pointer;gap:4px;`,Dn=_.default(un)`flex-direction:row;align-items:center;`,vo=_.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ys=c.createContext(null);function ef({testerType:e,origin:t,children:n}){return i.createElement(Ys.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(tf,null),n)}const pt=()=>{const e=c.useContext(Ys);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},tf=()=>{const{isActionbookTester:e}=pt();return i.createElement(Je.Template,{template:e?nf:void 0},i.createElement(Je.MessageLogs,{component:rf}))},nf=e=>i.createElement(zs,{...e,testerMode:!0,maxBodyWidth:Y.WIDE_BODY_MAX_WIDTH}),rf=({extendedMessagePayload:e={}})=>{const{handlers:t}=ne(),{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(of,null,i.createElement(sf,{width:4}),i.createElement(Ks,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:p.themedColor.textHighEmphasis,textColor:p.themedColor.textHighEmphasis,barColor:p.themedColor.textDisabled},bottomContent:i.createElement(af,{variant:"caption2",color:p.themedColor.textLowEmphasis},"Only visible in the tester")}))},of=_.default.div`display:flex;gap:16px;margin:16px ${Y.HORIZONTAL_PADDING}px 0;align-self:stretch;`,sf=_.default.div`width:${({width:e})=>e}px;background-color:${p.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,af=_.default(D)`margin-top:5px;`,yo=40,So=.9,lf="[data-message-listitem]",cf='input, textarea, select, [role="textbox"], [contenteditable="true"]',uf=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*So;case"PageUp":return t.clientHeight*-So;case"ArrowDown":return n?yo:void 0;case"ArrowUp":return n?yo*-1:void 0;default:return}},df=({listRef:e,syncScrollPosition:t})=>c.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(cf))return;const s=o===r||o.matches(lf),a=uf({event:n,list:r,isMessageAnchor:s});if(a==null||a===0)return;const l=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(l,Math.max(0,r.scrollTop+a));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),mf="[data-message-listitem]",hf=e=>Math.min(Math.max(0,e),1),gf=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(mf),o=n===e||n===r;return!n||!e.contains(n)?null:o?e:n},ff=({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})},pf=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:o,onLoadPrev:s,onScroll:a})=>{const l=c.useRef(!1),u=c.useRef(void 0),d=c.useRef(0),m=c.useRef(0),h=c.useRef(null),g=c.useRef(null),C=c.useRef(null);c.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),c.useLayoutEffect(()=>{const y=t.current;y&&(u.current==="top"&&(y.scrollTop=y.scrollHeight-m.current,ff({list:y,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(y.scrollTop=d.current),u.current=void 0)},[t,r]);const b=c.useCallback(async y=>{const E=t.current;if(!E||(a==null||a(y),m.current=E.scrollHeight-E.scrollTop,d.current=E.scrollTop,l.current))return;const x=E.clientHeight*hf(n);if(E.scrollTop<=x){l.current=!0,u.current="top",h.current=gf(E),await s(),l.current=!1;return}if(E.scrollHeight-E.scrollTop-E.clientHeight<=x){l.current=!0,u.current="bottom",await o(),l.current=!1;return}u.current=void 0},[t,n,o,s,a]),v=c.useCallback(y=>{const E=t.current;if(!E)return;const x=C.current;if(x!=null){if(x===E.scrollTop){C.current=null;return}C.current=null}const S=g.current;if(S!=null&&S===E.scrollTop){g.current=null,C.current=E.scrollTop,b(y);return}g.current=null,b(y)},[b,t]),f=c.useCallback(y=>{const E=t.current;E&&(g.current=y,C.current=null,E.scrollTop=y,E.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return c.useLayoutEffect(()=>()=>{g.current=null,C.current=null},[]),{handleScroll:v,syncScrollPosition:f}},_f=c.forwardRef(function(t,n){const{messages:r,renderMessage:o,loading:s,LoadingComponent:a,error:l,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:g,overlayArea:C,onLoadPrev:b,onLoadNext:v,loadThreshold:f=.05,onScroll:y=oe,depsForResetScrollPositionToBottom:E,stackDirection:x="top",bottomSpacerHeight:S=0,ariaLabel:I}=t,k=c.useRef(null),M=c.useCallback(L=>{k.current=L,n&&(typeof n=="function"?n(L):n.current=L)},[n]),{handleScroll:U,syncScrollPosition:F}=pf({depsForResetScrollPositionToBottom:E,listRef:k,loadThreshold:f,messagesLength:r.length,onLoadNext:v,onLoadPrev:b,onScroll:y}),G=df({listRef:k,syncScrollPosition:F});return l?i.createElement(i.Fragment,null,u):s?i.createElement(i.Fragment,null,a):i.createElement(Ef,{id:"infinite-list-container"},i.createElement(bf,{id:"infinite-list-inner",ref:M,onScroll:U,onKeyDown:G,role:"list","aria-label":I,tabIndex:0},x==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((L,P)=>o({message:L,index:P})),g,S>0&&i.createElement("div",{style:{minHeight:S}})),i.createElement(Cf,{id:"infinite-list-overlay-container"},i.createElement(vf,{id:"infinite-list-overlay"},C)))}),Ef=_.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,bf=_.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${p.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,Cf=_.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,vf=_.default.div`pointer-events:auto;`,Ue=({as:e,type:t,size:n=16,color:r,disabled:o,children:s,...a})=>{const l=o?p.themedColor.textDisabled:p.themedColor.textHighEmphasis;return i.createElement(yf,{as:e,disabled:o,...a},i.createElement(z,{type:t,size:n,color:r??l}),s)},yf=_.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${be}&:disabled{cursor:not-allowed;}`,Sf=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{var I,k;const[o,s]=c.useState(t),[a,l]=c.useState(!1),{stringSet:u,format:d}=Q(),{config:m}=ne(),h=e.length,g=e[o],C=((k=(I=m==null?void 0:m.conversation)==null?void 0:I.fileViewer)==null?void 0:k.downloadEnabled)!==!1,b=h>1,v=(g==null?void 0:g.type)||"",f=ze(v),y=Uo(v),E=!Fu(v);c.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const x=c.useCallback(()=>{o>0&&(s(M=>M-1),l(!1))},[o]),S=c.useCallback(()=>{o<h-1&&(s(M=>M+1),l(!1))},[o,h]);return c.useEffect(()=>{if(!r)return;const M=U=>{U.key==="ArrowLeft"?x():U.key==="ArrowRight"&&S()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[r,x,S]),!r||!g?null:i.createElement(ft,{onClose:n,visible:r,rootElementId:ce.MODAL_ROOT,"aria-label":(g==null?void 0:g.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(Af,null,i.createElement(xf,null,i.createElement(Tf,null,i.createElement(If,null,i.createElement(D,{variant:"button",maxTextLines:1,color:p.themedColor.textHighEmphasis},g.name||u.IMAGE_VIEWER__DEFAULT_TITLE),g.timestamp&&i.createElement(D,{variant:"caption2",color:p.themedColor.textMidEmphasis},d(new Date(g.timestamp),"h:mm a")))),i.createElement(wf,{type:"close",size:24,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(kf,{onClick:M=>M.currentTarget===M.target&&n()},b&&i.createElement(Ao,{$position:"left",type:"chevron-right",size:32,onClick:x,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(Lf,null,f&&i.createElement(i.Fragment,null,!a&&i.createElement(Mf,null,i.createElement(it,{size:32},i.createElement(z,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(Of,{src:g.url,alt:g.name||"Image",$loaded:a,onLoad:()=>l(!0)})),y&&i.createElement(Rf,{controls:!0},i.createElement("source",{src:g.url,type:v})),E&&i.createElement(Nf,null,i.createElement(D,{variant:"h1",color:p.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),b&&i.createElement(Ao,{$position:"right",type:"chevron-right",size:32,onClick:S,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:o===h-1})),i.createElement(Df,null,i.createElement($f,null),b&&i.createElement(D,{variant:"body3",color:p.themedColor.textHighEmphasis},o+1,"/",h),i.createElement(Pf,null,C&&!E&&i.createElement(Ue,{as:"a",href:g.url,download:g.name||"file",type:"download",size:24,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD})))))},Af=_.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${p.themedColor.bg_50_600};`,xf=_.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 16px;min-height:56px;border-bottom:1px solid ${p.themedColor.textDisabled};`,Tf=_.default.div`flex:1;min-width:0;padding-right:16px;`,If=_.default.div`display:flex;flex-direction:column;gap:2px;`,wf=_.default(Ue)`flex-shrink:0;width:32px;height:32px;border-radius:50%;&:hover{background-color:${p.themedColor.bg_100_500};}`,_n=_.default.div`display:flex;align-items:center;justify-content:center;`,kf=_.default(_n)`flex:1;min-height:0;position:relative;padding:0 16px;`,Lf=_.default(_n)`position:relative;max-width:100%;max-height:100%;`,Mf=_.default(_n)`position:absolute;inset:0;`,Of=_.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;`,Rf=_.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Nf=_.default(_n)`flex-direction:column;gap:16px;`,Ao=_.default(Ue)`position:absolute;${e=>e.$position==="left"?"left: 16px;":"right: 16px;"}top:50%;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;&:hover:not(:disabled){background-color:${p.themedColor.bg_200_400};}&:disabled{opacity:0.3;}@media (max-width:480px){width:38px;height:38px;${e=>e.$position==="left"?"left: 8px;":"right: 8px;"}}`,Df=_.default.footer`display:flex;align-items:center;justify-content:space-between;padding:16px;min-height:56px;border-top:1px solid ${p.themedColor.textDisabled};`,$f=_.default.div`width:40px;`,Pf=_.default.div`display:flex;align-items:center;justify-content:flex-end;width:40px;`,js=({title:e,description:t,negativeText:n,positiveText:r,onCancel:o,onConfirm:s})=>i.createElement(Ff,null,i.createElement(Bf,null,i.createElement(D,{as:"div",variant:"h2",color:p.themedColor.textHighEmphasis},e)),i.createElement(Hf,null,i.createElement(D,{as:"div",variant:"body3",color:p.themedColor.textMidEmphasis},t)),i.createElement(Uf,null,i.createElement(Vf,{type:"button",onClick:o},i.createElement(D,{variant:"button",color:p.themedColor.textHighEmphasis},n)),i.createElement(Gf,{type:"button",onClick:s},i.createElement(D,{variant:"button",color:p.themedColor.textHighEmphasisInverse},r)))),Ff=_.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${p.color.background50};${W.dark`
|
|
382
|
+
background-color: ${p.color.background500};
|
|
261
383
|
`}
|
|
262
|
-
`,
|
|
263
|
-
`,
|
|
264
|
-
background-color: ${
|
|
384
|
+
`,Bf=_.default.div`padding:24px 24px 16px;`,Hf=_.default.div`padding-inline:24px;`,Uf=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,Vf=_.default.button`display:flex;align-items:center;justify-content:center;padding:12px 20px;border-radius:0;cursor:pointer;border:none;background:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,Gf=_.default.button`display:flex;align-items:center;justify-content:center;padding:12px 20px;border-radius:20px;cursor:pointer;border:none;background-color:${p.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,Yt=16,zf=({status:e})=>e===Qt.COMPLETED?i.createElement(z,{type:"done-circle",size:Yt,color:p.themedColor.textHighEmphasis}):e===Qt.CANCELED?i.createElement(z,{type:"stop-circle",size:Yt,color:p.themedColor.textLowEmphasis}):i.createElement(it,{size:Yt},i.createElement(z,{type:"spinner",size:Yt,color:p.themedColor.textHighEmphasis})),Xs=24,Wf=8,qf=40,Kf=({task:e,isFirst:t,isLast:n})=>i.createElement(Yf,{role:"listitem"},i.createElement(jf,null,i.createElement(xo,{$hidden:t}),i.createElement(Xf,null,i.createElement(zf,{status:e.status})),i.createElement(xo,{$hidden:n})),i.createElement(Zf,null,i.createElement(D,{as:"div",variant:"body3",color:e.status===Qt.CANCELED?p.themedColor.textLowEmphasis:p.themedColor.textHighEmphasis},e.user_facing_title))),Yf=_.default.div`display:flex;gap:4px;`,jf=_.default.div`display:flex;flex-direction:column;align-items:center;width:${Xs}px;flex-shrink:0;`,xo=_.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${p.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,Xf=_.default.div`display:flex;height:${Xs}px;align-items:center;justify-content:center;`,Zf=_.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${qf}px;padding-block:${Wf}px;`,Jf=({steward:e,onCancelSteward:t})=>{const{logger:n}=ne(),[r,o]=c.useState(!1),[s,a]=c.useState(!1),l=!!e.cancellation_option,u=Ri(e.status);return i.createElement(Qf,{$marginBottom:mn("single")},i.createElement(ep,null,i.createElement(tp,null,i.createElement(np,null,i.createElement(D,{as:"div",variant:"caption1",color:p.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement(D,{as:"div",variant:"caption4",color:p.themedColor.textLowEmphasis},e.description)),l&&i.createElement(ip,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(z,{type:"stop",size:16,color:s?p.themedColor.textDisabled:p.themedColor.textHighEmphasis}))),i.createElement(rp,null),e.tasks.length===0?u!==St.IN_PROGRESS?null:i.createElement(sp,null,i.createElement(it,{size:16},i.createElement(z,{type:"spinner",size:16,color:p.themedColor.textHighEmphasis}))):i.createElement(op,{role:"list"},e.tasks.map((d,m)=>i.createElement(Kf,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(ft,{rootElementId:ce.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(js,{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)}}})))},Qf=_.default.div`display:flex;flex-direction:column;margin:0 ${Y.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
385
|
+
`,ep=_.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${p.themedColor.bg_300_500};background-color:${p.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,tp=_.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,np=_.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,rp=_.default.div`height:1px;margin-block:12px;background-color:${p.themedColor.bg_200_400};`,op=_.default.div`display:flex;flex-direction:column;`,sp=_.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,ip=_.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:${p.themedColor.textHighEmphasis};background-color:${p.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,ap=({className:e,label:t,onClick:n})=>{const{colors:r}=R.useTheme(),{conversation:o}=ee(),s=o.newMessagesButton;return i.createElement(lp,{className:e,onClick:n,...s.props},i.createElement(D,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(z,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),s.descriptionNode)},lp=_.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;}${be}`,vr=({iconSize:e=64,icon:t,className:n,label:r,children:o})=>i.createElement(up,{className:n},t&&i.createElement(z,{type:t,size:e,color:p.themedColor.textLowEmphasis}),r&&i.createElement(D,{variant:"body1",color:p.themedColor.textMidEmphasis},r),o),cp=_.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,up=_.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,dp=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(vr,{icon:t,label:e,...r},n&&i.createElement(mp,{onClick:n.onClick,label:n.label??"Retry"})),mp=({label:e,onClick:t})=>{const{conversation:n}=ee();return i.createElement(hp,{tabIndex:0,"aria-label":n.retryButton(e)["aria-label"],onClick:t},i.createElement(z,{type:"refresh",size:20}),i.createElement(D,{variant:"button",color:p.color.primary.main},e))},hp=_.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${be}`,gp=({iconSize:e=48,className:t})=>i.createElement(it,{size:e,className:t}),fp=({label:e="No channels",icon:t="chat",...n})=>i.createElement(vr,{icon:t,label:e,...n}),pp=({label:e="No messages",icon:t="message",...n})=>i.createElement(vr,{icon:t,label:e,...n}),_p=e=>{const{components:t}=En.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(cp,null,n)},En=Pe({template:_p,components:{Loading:gp,Error:dp,NoChannels:fp,NoMessages:pp}}),At=e=>{const{Template:t}=En.useContext();return i.createElement(t,{...e})},Ep=[0,150,450];function bp({enabled:e}){const{state:t,actions:n}=As(),r=c.useRef(0),o=c.useRef(t.isAwayFromBottom);o.current=t.isAwayFromBottom,c.useEffect(()=>{if(!e){r.current+=1;return}const s=r.current+1;r.current=s;const a=Ep.map(l=>setTimeout(()=>{Ce(()=>{r.current===s&&(o.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const Cp=({className:e,date:t=Date.now(),style:n})=>{const{format:r,stringSet:o}=Q();return i.createElement(vp,{id:`${we}-date-separator`,style:n,className:e},i.createElement(D,{variant:"caption4",color:p.themedColor.textMidEmphasis},r(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},vp=_.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,yp=({className:e,style:t,onClick:n})=>{const{conversation:r}=ee(),o=r.scrollToBottomButton;return i.createElement(Sp,{className:e,style:t,onClick:n,tabIndex:0,...o.props},i.createElement(z,{size:24,type:"chevron-down",color:p.color.primary.main}),o.descriptionNode??null)},Sp=_.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);${W.light`
|
|
386
|
+
background-color: ${p.color.background50};
|
|
265
387
|
&:hover {
|
|
266
|
-
background-color: ${
|
|
388
|
+
background-color: ${p.color.background100};
|
|
267
389
|
}
|
|
268
390
|
&:active {
|
|
269
|
-
background-color: ${
|
|
391
|
+
background-color: ${p.color.background200};
|
|
270
392
|
}
|
|
271
393
|
`}
|
|
272
|
-
${
|
|
273
|
-
background-color: ${
|
|
394
|
+
${W.dark`
|
|
395
|
+
background-color: ${p.color.background400};
|
|
274
396
|
&:hover {
|
|
275
|
-
background-color: ${
|
|
397
|
+
background-color: ${p.color.background500};
|
|
276
398
|
}
|
|
277
399
|
&:active {
|
|
278
|
-
background-color: ${
|
|
400
|
+
background-color: ${p.color.background700};
|
|
279
401
|
}
|
|
280
402
|
`}
|
|
281
403
|
|
|
282
404
|
&:focus {
|
|
283
405
|
outline: none;
|
|
284
406
|
}
|
|
285
|
-
|
|
286
|
-
|
|
407
|
+
|
|
408
|
+
${be}
|
|
409
|
+
`,Ap=()=>null,bn=Pe({template:Ap,components:{DateSeparator:Cp,ScrollToBottomButton:yp}}),xp=()=>{const{stringSet:e,format:t}=Q(),{agentPreviewConfigs:n={},aiAgentId:r}=ne(),{aiAgentInfo:o}=_e(),{messageSource:s}=he(),{Template:a}=Je.useContext(),{components:l}=bn.useContext(),u=n.welcomeMessages??[],d=s.messages,m=Hu(d,r),h=d[m.length+1],g=m[0]??h;return{filteredMessages:Ts(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:C=>C>0||u.length===0?!0:h&&!We.isSameDay(h.createdAt,(g==null?void 0:g.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:i.createElement(i.Fragment,null,i.createElement(l.DateSeparator,{style:{margin:"16px 0"},date:g==null?void 0:g.createdAt}),u.map((C,b)=>{const v=b===u.length-1,f=m.length!==d.length,y=u.length===1?"single":b===0?"top":v||f?"bottom":"middle",E=(g==null?void 0:g.createdAt)??Date.now();return i.createElement("div",{key:b,role:"listitem",tabIndex:-1,"aria-label":mt({sender:(o==null?void 0:o.nickname)||"",message:C.message,messageFormat:"markdown",time:t(E,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},i.createElement(a,{messageType:"user",message:C.message,sender:o,groupType:y,createdAt:E,extendedMessagePayload:{suggested_replies:C.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!f,isBotMessage:!0,onClickSuggestedReply:async({reply:x})=>{s.sendUserMessage({message:x})}}))}))}},Tp=()=>{const{messageSource:e,scrollSource:t}=he();c.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Ip=e=>_.default(e).withConfig({shouldForwardProp:Oi.default}),wp=({style:e})=>{const{stringSet:t}=Q(),{conversation:n}=ee(),{isActionbookTester:r}=pt();return!cr("powered-by")||r?null:i.createElement(kp,{variant:"caption2",style:e},t.POWERED_BY+" ",i.createElement(Lp,{variant:"caption2",as:"a",href:"https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",...n.poweredByLink,rel:mr,target:"_blank"},"Sendbird"))},kp=_.default(D)`color:${p.themedColor.textLowEmphasis};text-align:center;`,Lp=Ip(D)`
|
|
410
|
+
color: ${p.themedColor.textLowEmphasis};
|
|
287
411
|
cursor: pointer;
|
|
288
412
|
text-decoration: none;
|
|
289
|
-
`,Rh=()=>{var a;const{stringSet:e}=K(),{channelSource:t,goToActiveConversation:n,scrollSource:r}=ne(),o=me(t.channel),i=d.useRef(o);return d.useEffect(()=>{if(!i.current&&o){const u=setTimeout(()=>{r.actions.scrollToBottom()},100);return()=>clearTimeout(u)}i.current=o},[o,r.actions.scrollToBottom]),!((a=t.channel)!=null&&a.isAIAgent)||!o?null:s.createElement(Oh,null,s.createElement(Dh,{variant:"button",role:"button",color:m.themedColor.textHighEmphasis,onClick:()=>n()},e.TALK_TO_AGENT))},Oh=h.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Dh=h.default(T)`border-radius:6px;box-sizing:border-box;padding:10px 20px;border:1px solid ${m.themedColor.textDisabled};cursor:pointer;user-select:none;`,Nh=()=>{var Y,G,ve,gt;const{Template:e}=mt.useContext(),{Template:t}=De.useContext(),{Template:n}=zt.useContext(),{components:r}=qt.useContext(),{stringSet:o}=K(),{config:i,cache:a,agentPreviewConfigs:l,chatSDK:c,state:u}=j(),{userSession:g,aiAgentInfo:p,connectionError:E}=se(),{conversation:v,channelSource:x,messageSource:_,scrollSource:f,state:{input:b,streamAnimation:y}}=ne(),{isActionbookTester:w}=Xe(),{filteredMessages:A,shouldShowOriginalDate:L,renderAgentPreviewWelcomeMessages:$}=Ih(),S=fa(x.channel),[R,P]=d.useState(null),[O,I]=d.useState(null);d.useEffect(()=>{f.actions.onTypingIndicatorUpdate(!!S)},[!!S,f.actions.onTypingIndicatorUpdate]),wh(),xh({enabled:_.initialized&&_.messages.length>0});const U=(k,Ne=!1)=>{var qe;return Ne?p:((qe=x.channel)==null?void 0:qe.members.find(ye=>ye.userId===k.sender.userId))??k.sender},N=k=>{if(k.sendingStatus==="failed"&&!b.disabled)return()=>I(k)},z=({message:k,index:Ne})=>{const qe=fs(k),ye=A[Ne-1],Yt=A[Ne+1],Zt=A[A.length-1],Xt=k===Zt,ft=it(k,p.userId),Jt=!(p.isUserFeedbackEnabled&&ft&&!ke.isWelcomeMessage(k)),Qt=ps(k,ye,Yt,Jt),D=!as.isSameDay((ye==null?void 0:ye.createdAt)??0,k.createdAt)&&L(Ne)&&!w,V=re=>{P({files:re.files.map(Ae=>({...Ae,timestamp:k.createdAt})),index:re.index})},q=re=>{V({files:[re],index:0})},Q=()=>{k.isFileMessage()&&Un(k.url)},ie=D?s.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:k.createdAt}):null,le={data:k.data,maxBodyWidth:u.expanded?H.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:k.extendedMessagePayload,createdAt:k.createdAt,groupType:Qt,onClickMedia:q,onClickMediaFiles:V,onClickFile:Q},Ke=()=>{if(Pe.isOutgoing(k,g.userId))return"outgoingmessage";if(Pe.isIncoming(k,g.userId))return"incomingmessage"},Se=(()=>{var re,Ae,pt;if(Pe.isAdmin(k))return Pe.isCSAT(k)?v?s.createElement(n,{...le,...v,isResolvedWhenDeterminedByUser:Vs(v),messageType:"admin.csat",onSubmitCSAT:async pe=>{var W;await((W=x.channel)==null?void 0:W.submitCSAT(pe))},onScrollToBottom:()=>f.actions.scrollToBottom()}):null:s.createElement(n,{...le,messageType:"admin",message:k.message});if(Pe.isSteward(k))return s.createElement(eh,{steward:k.extendedMessagePayload.steward,onCancelSteward:async()=>{await c.aiAgent.cancelStewardTask({channelUrl:k.channelUrl,messageId:k.messageId})}});if(Pe.isOutgoing(k,g.userId)){const pe={...le,message:k.message,sender:U(k),sendingStatus:k.sendingStatus,onClickFailedMessage:N(k)};if(k.isUserMessage())return s.createElement(e,{messageType:"user",...pe});if(k.isFileMessage()){const[W,oe]=((re=k.metaArrays.find(Ee=>Ee.key===Hr))==null?void 0:re.value)??[];return s.createElement(e,{messageType:"file",file:k,metadata:{aspectRatio:W&&oe?`${W}/${oe}`:"1/1",localFile:(Ae=k.messageParams)==null?void 0:Ae.file},...pe})}if(k.isMultipleFilesMessage()){const{files:W,metadata:oe}=br(k);return s.createElement(e,{messageType:"multipleFiles",files:W,metadata:oe,...pe})}}if(Pe.isIncoming(k,g.userId)){const pe={...le,sender:U(k,ft),message:k.message,suggestedRepliesVisible:Xt,suggestedRepliesDirection:l==null?void 0:l.suggestedRepliesDirection,isBotMessage:ft,isStreaming:ke.isStreaming(k),isHandedOff:He(x.channel),isConversationClosed:me(x.channel),isFeedbackEnabled:p.isUserFeedbackEnabled,isFeedbackCommentEnabled:p.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(pt=i==null?void 0:i.conversation)==null?void 0:pt.senderAvatarEnabled,onClickSuggestedReply:async({reply:W})=>{_.sendUserMessage({message:W})},onRequestMessageTemplate:async W=>{const{template:oe}=await c.aiAgent.getMessageTemplate(W);return a.template.set(W,oe),oe},onGetCachedMessageTemplate:W=>a.template.get(W),onHandleTemplateInternalAction:W=>{if(W.type==="internal"&&W.internalData){const{method:oe,payload:Ee}=W.internalData;oe==="message.send"&&(Ee!=null&&Ee.message)&&_.sendUserMessage({message:Ee.message})}},onFeedbackUpdate:W=>{const oe={messageId:k.messageId,channelUrl:k.channelUrl};if(!W)return c.aiAgent.deleteMessageFeedback(oe);const Ee={...oe,rating:qc(W.rating),comment:W.comment};return ke.hasFeedback(k)?c.aiAgent.updateMessageFeedback(Ee):c.aiAgent.createMessageFeedback(Ee)},onSubmitForm:({key:W,data:oe})=>c.aiAgent.submitForm({messageId:k.messageId,channelUrl:k.channelUrl,formKey:W,formData:oe}),onCancelForm:({key:W})=>c.aiAgent.cancelForm({messageId:k.messageId,channelUrl:k.channelUrl,formKey:W}),onStreamAnimationStart:()=>{y.start(k.messageId)},onStreamAnimationProgress:()=>{f.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{y.stop(k.messageId),f.actions.onStreamingUpdate(!1)}};if(k.isUserMessage())return s.createElement(t,{messageType:"user",...pe});if(k.isFileMessage())return s.createElement(t,{messageType:"file",file:k,...pe});if(k.isMultipleFilesMessage()){const{files:W}=br(k);return s.createElement(t,{messageType:"multipleFiles",files:W,...pe})}}})();return s.createElement("div",{key:qe,id:`${ce}-message-item`,role:"listitem","data-layout-id":Ke()},ie,Se)};return s.createElement(Ph,{id:`${ce}-message-list`},s.createElement(pm,{ref:f.ref,onScroll:f.props.onScroll,stackDirection:l==null?void 0:l.messageStackDirection,messages:A,renderMessage:z,onLoadPrev:_.loadPrevious,onLoadNext:_.loadNext,depsForResetScrollPositionToBottom:[_.initialized,_.messages.length!==0],bottomSpacerHeight:f.state.bottomSpace,ariaLabel:o.A11Y_MESSAGE_LIST,loading:!_.initialized||!x.channel,empty:A.length===0&&!S,error:!!(E||x.error),LoadingComponent:s.createElement(rt,{type:"loading"}),EmptyComponent:(()=>{const k=$();return k?s.createElement("div",{style:{width:"100%"}},k):s.createElement(rt,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:s.createElement(rt,{type:"error",label:(E==null?void 0:E.message)??((Y=x.error)==null?void 0:Y.message),action:x.error?{label:o.RETRY,onClick:()=>x.refetch()}:void 0}),messageTopArea:s.createElement(s.Fragment,null,s.createElement(Mh,{style:{marginTop:16}}),$()),messageBottomArea:s.createElement(s.Fragment,null,S&&s.createElement("div",{id:`${ce}-message-item`,role:"listitem",style:{marginTop:A.length===0?8:0}},s.createElement(t,{isTyping:!0,isBotMessage:S.isBot,sender:S.user,thinkingMessage:S.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(G=i==null?void 0:i.conversation)==null?void 0:G.senderAvatarEnabled})),((ve=i==null?void 0:i.conversation)==null?void 0:ve.isTalkToAgentViewEnabled)&&s.createElement(Rh,null)),overlayArea:s.createElement(s.Fragment,null,((gt=i==null?void 0:i.conversation)==null?void 0:gt.newMessageIndicatorEnabled)&&f.state.isAwayFromBottom&&_.newMessages.length>0&&s.createElement(Fh,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(_.newMessages),ariaLabel:o.A11Y_SCROLL_TO_NEW_MESSAGES,onClick:()=>f.actions.scrollToBottom()}),f.state.isAwayFromBottom&&_.newMessages.length===0&&!S&&s.createElement(r.ScrollToBottomButton,{ariaLabel:o.A11Y_SCROLL_TO_BOTTOM,onClick:()=>f.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),R&&s.createElement(Am,{files:R.files,initialIndex:R.index,onClose:()=>P(null),visible:!0}),O&&s.createElement(Me,{visible:!0,onClose:()=>I(null)},s.createElement(Me.ActionItem,{onClick:()=>{_.resendMessage(O),I(null)}},o.FAILED_MESSAGE_RESEND),s.createElement(Me.ActionItem,{destructive:!0,onClick:()=>{_.deleteMessage(O),I(null)}},o.FAILED_MESSAGE_REMOVE)))},Ph=h.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Fh=h.default(ch)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Bh=()=>s.createElement(Nh,null),Uh=()=>{var o;const{origin:e}=Xe(),{appId:t,aiAgentId:n}=de(),{channelSource:r}=ne();return(o=r.channel)!=null&&o.conversation?s.createElement(Hh,null,s.createElement(Sn,{style:{gap:4}},s.createElement(F,{color:m.themedColor.textLowEmphasis,size:12,type:"show"}),s.createElement(T,{as:"i",color:m.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),s.createElement(Sn,{role:"button",style:{gap:4},onClick:()=>{var c,u;const i=e??window.location.origin,a=(u=(c=r.channel)==null?void 0:c.conversation)==null?void 0:u.id,l=`${i}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},s.createElement(T,{variant:"body3",color:m.themedColor.textHighEmphasis},"Copy ",s.createElement("span",{style:{color:m.themedColor.primary}},"conversation link")),s.createElement(F,{color:m.themedColor.primary,size:14,type:"copy"}))):null},Sn=h.default.div`display:flex;justify-content:center;align-items:center;`,Hh=h.default(Sn)`flex-direction:column;padding-block:16px;background-color:${m.themedColor.bg_100_500};gap:8px;`,Vh=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>Ie(o.type)),r=e.some(o=>!Ie(o.type));return n&&r?Ie(t.type)?e.filter(o=>Ie(o.type)):[t]:r?[t]:e},zh=(e,t)=>{const n=[],r=[],o=[];for(const i of e){const a=t.isSupportedMimeType(i.type),l=i.size<=t.getUploadSizeLimit(i.type);a&&l?n.push(i):a?r.push(i):o.push(i)}return{passed:n,failedBySize:r,failedByType:o}},No=d.createContext(void 0),Gh=({children:e})=>{var $;const{chatSDK:t}=j(),{createAttachmentRules:n}=se(),{stringSet:r}=K(),{channelSource:o}=ne(),[i,a]=d.useState([]),[l,c]=d.useState({visible:!1,title:""}),u=n({channel:o.channel,uploadSizeLimit:($=t.appInfo)==null?void 0:$.uploadSizeLimit}),g=u.isEnabled(),p=u.maxAttachmentCount,E=S=>{c({visible:!0,title:S})},v=()=>{E(r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString()))},x=S=>{E(r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",S.toString()))},_=S=>{E(r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",S.toString()))},f=S=>S.map(R=>({file:R,preview:{url:URL.createObjectURL(R),type:R.type,name:R.name}})),b=S=>{a(R=>[...R,...f(S)])},y=S=>{a(R=>(R.forEach(P=>URL.revokeObjectURL(P.preview.url)),f(S)))},w=S=>{if(!g||S.length===0)return;if(p-i.length===0){v();return}if(i.length+S.length>p){v();return}const P=Vh(S),{passed:O,failedBySize:I,failedByType:U}=zh(P,u),N=I.length+U.length,z=P.length===1?I[0]:void 0;if(z?x(u.getUploadSizeLimitInMB(z.type)):N>0&&_(N),O.length===0)return;i.length>0&&i.every(G=>Ie(G.file.type))&&O.every(G=>Ie(G.type))?b(O):y(O)},A=S=>{a(R=>{var O;const P=(O=R[S])==null?void 0:O.preview;return P&&URL.revokeObjectURL(P.url),R.filter((I,U)=>U!==S)})},L=()=>{a(S=>(S.forEach(R=>URL.revokeObjectURL(R.preview.url)),[]))};return s.createElement(No.Provider,{value:{files:i,addFiles:w,removeFile:A,clearFiles:L,isFileUploadEnabled:g,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount,showFileUploadAlert:E}},e,s.createElement(Bn,{...l,onClose:()=>c({visible:!1,title:""})}))},Wn=()=>{const e=d.useContext(No);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Wh({blurred:e,elementRef:t,document:n=window.document}){const r=d.useRef(!1);e&&t.current&&n.activeElement===t.current&&(r.current=!0),d.useLayoutEffect(()=>{var o;!e&&r.current&&((o=t.current)==null||o.focus(),r.current=!1)},[e])}const qh=(e,t)=>{d.useEffect(()=>{t?e==null||e.startTyping():e==null||e.endTyping()},[e,t])},Kh=h.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,jh=h.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;}`,Yh=h.default.div`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;${B.light`
|
|
290
|
-
background-color: ${
|
|
413
|
+
`,Mp=()=>{var u;const{stringSet:e}=Q(),{conversation:t}=ee(),{channelSource:n,goToActiveConversation:r,scrollSource:o}=he(),s=Se(n.channel),a=c.useRef(s);if(c.useEffect(()=>{if(!a.current&&s){const h=setTimeout(()=>{o.actions.scrollToBottom()},100);return()=>clearTimeout(h)}a.current=s},[s,o.actions.scrollToBottom]),!((u=n.channel)!=null&&u.isAIAgent)||!s)return null;const l=t.startNewConversationButton({onActivate:r});return i.createElement(Op,null,i.createElement(Rp,{variant:"button",color:p.themedColor.textHighEmphasis,...l},e.TALK_TO_AGENT))},Op=_.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Rp=_.default(D)`border-radius:6px;box-sizing:border-box;padding:10px 20px;border:1px solid ${p.themedColor.textDisabled};cursor:pointer;user-select:none;`,Np=()=>{var q,te,re,K;const{Template:e}=Nt.useContext(),{Template:t}=Je.useContext(),{Template:n}=pn.useContext(),{components:r}=bn.useContext(),{stringSet:o,format:s}=Q(),{conversation:a}=ee(),{config:l,cache:u,agentPreviewConfigs:d,chatSDK:m,state:h}=ne(),{userSession:g,aiAgentInfo:C,connectionError:b}=_e(),{conversation:v,channelSource:f,messageSource:y,scrollSource:E,state:{input:x,streamAnimation:S}}=he(),{isActionbookTester:I}=pt(),{filteredMessages:k,shouldShowOriginalDate:M,renderAgentPreviewWelcomeMessages:U}=xp(),F=os(f.channel),[G,L]=c.useState(null),[P,N]=c.useState(null);c.useEffect(()=>{E.actions.onTypingIndicatorUpdate(!!F)},[!!F,E.actions.onTypingIndicatorUpdate]),Tp(),bp({enabled:y.initialized&&y.messages.length>0});const w=(T,V=!1)=>{var H;return V?C:((H=f.channel)==null?void 0:H.members.find(j=>j.userId===T.sender.userId))??T.sender},$=T=>{if(T.sendingStatus==="failed"&&!x.disabled)return()=>N(T)},O=({message:T,index:V})=>{const H=Ni(T),j=k[V-1],se=k[V+1],le=k[k.length-1],Re=T===le,Ae=Tt(T,C.userId),B=!(C.isUserFeedbackEnabled&&Ae&&!$e.isWelcomeMessage(T)),Z=Di(T,j,se,B),X=!Ti.isSameDay((j==null?void 0:j.createdAt)??0,T.createdAt)&&M(V)&&!I,ge=xe=>{L({files:xe.files.map(et=>({...et,timestamp:T.createdAt})),index:xe.index})},ve=xe=>{ge({files:[xe],index:0})},Be=()=>{T.isFileMessage()&&fr(T.url)},lt=X?i.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:T.createdAt}):null,Le={data:T.data,maxBodyWidth:h.expanded?Y.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:T.extendedMessagePayload,createdAt:T.createdAt,groupType:Z,onClickMedia:ve,onClickMediaFiles:ge,onClickFile:Be},Ve=()=>{if(pe.isOutgoing(T,g.userId))return"outgoingmessage";if(pe.isIncoming(T,g.userId))return"incomingmessage"},ct=T.createdAt!=null&&T.createdAt!==0?s(T.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,Qe=(()=>{var et,Et,Te,J,ue,Ie;const xe=(et=T.message)==null?void 0:et.trim();if(T.isFileMessage()){const $t=((Et=T.name)==null?void 0:Et.trim())||"";return ht({markdownText:xe,comparisonText:$t,plainText:a.file.label($t,T.type)})}if(T.isMultipleFilesMessage()){const $t=((ue=(J=(Te=T.fileInfoList)==null?void 0:Te[0])==null?void 0:J.fileName)==null?void 0:ue.trim())||"",wr=((Ie=T.fileInfoList)==null?void 0:Ie.length)??0;return ht({markdownText:xe,comparisonText:$t,plainText:wr>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(wr):""})}return xe?ht({markdownText:xe}):dr("")})(),Ci=(()=>{if(pe.isAdmin(T))return mt({message:Qe.text,messageFormat:Qe.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(pe.isOutgoing(T,g.userId))return mt({sender:o.A11Y_MESSAGE_SENDER_YOU,message:Qe.text,messageFormat:"plain",time:ct,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(pe.isIncoming(T,g.userId))return mt({sender:w(T,Ae).nickname,message:Qe.text,messageFormat:Qe.format,time:ct,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),vi=(()=>{var xe,et,Et;if(pe.isAdmin(T))return pe.isCSAT(T)?v?i.createElement(n,{...Le,...v,isResolvedWhenDeterminedByUser:aa(v),messageType:"admin.csat",onSubmitCSAT:async Te=>{var J;await((J=f.channel)==null?void 0:J.submitCSAT(Te))},onScrollToBottom:()=>E.actions.scrollToBottom()}):null:i.createElement(n,{...Le,messageType:"admin",message:T.message});if(pe.isSteward(T))return i.createElement(Jf,{steward:T.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:T.channelUrl,messageId:T.messageId})}});if(pe.isOutgoing(T,g.userId)){const Te={...Le,message:T.message,sender:w(T),sendingStatus:T.sendingStatus,onClickFailedMessage:$(T)};if(T.isUserMessage())return i.createElement(e,{messageType:"user",...Te});if(T.isFileMessage()){const[J,ue]=((xe=T.metaArrays.find(Ie=>Ie.key===Bo))==null?void 0:xe.value)??[];return i.createElement(e,{messageType:"file",file:T,metadata:{aspectRatio:J&&ue?`${J}/${ue}`:"1/1",localFile:(et=T.messageParams)==null?void 0:et.file},...Te})}if(T.isMultipleFilesMessage()){const{files:J,metadata:ue}=co(T);return i.createElement(e,{messageType:"multipleFiles",files:J,metadata:ue,...Te})}}if(pe.isIncoming(T,g.userId)){const Te={...Le,sender:w(T,Ae),message:T.message,suggestedRepliesVisible:Re,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:Ae,isStreaming:$e.isStreaming(T),isHandedOff:je(f.channel),isConversationClosed:Se(f.channel),isFeedbackEnabled:C.isUserFeedbackEnabled,isFeedbackCommentEnabled:C.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(Et=l==null?void 0:l.conversation)==null?void 0:Et.senderAvatarEnabled,onClickSuggestedReply:async({reply:J})=>{y.sendUserMessage({message:J})},onRequestMessageTemplate:async J=>{const{template:ue}=await m.aiAgent.getMessageTemplate(J);return u.template.set(J,ue),ue},onGetCachedMessageTemplate:J=>u.template.get(J),onHandleTemplateInternalAction:J=>{if(J.type==="internal"&&J.internalData){const{method:ue,payload:Ie}=J.internalData;ue==="message.send"&&(Ie!=null&&Ie.message)&&y.sendUserMessage({message:Ie.message})}},onFeedbackUpdate:J=>{const ue={messageId:T.messageId,channelUrl:T.channelUrl};if(!J)return m.aiAgent.deleteMessageFeedback(ue);const Ie={...ue,rating:xm(J.rating),comment:J.comment};return $e.hasFeedback(T)?m.aiAgent.updateMessageFeedback(Ie):m.aiAgent.createMessageFeedback(Ie)},onSubmitForm:({key:J,data:ue})=>m.aiAgent.submitForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:J,formData:ue}),onCancelForm:({key:J})=>m.aiAgent.cancelForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:J}),onStreamAnimationStart:()=>{S.start(T.messageId)},onStreamAnimationProgress:()=>{E.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{S.stop(T.messageId),E.actions.onStreamingUpdate(!1)}};if(T.isUserMessage())return i.createElement(t,{messageType:"user",...Te});if(T.isFileMessage())return i.createElement(t,{messageType:"file",file:T,...Te});if(T.isMultipleFilesMessage()){const{files:J}=co(T);return i.createElement(t,{messageType:"multipleFiles",files:J,...Te})}}})();return i.createElement("div",{key:H,id:`${we}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Ci,"data-message-listitem":"","data-layout-id":Ve()},lt,vi)};return i.createElement(Dp,{id:`${we}-message-list`},i.createElement(_f,{ref:E.ref,onScroll:E.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:k,renderMessage:O,onLoadPrev:y.loadPrevious,onLoadNext:y.loadNext,depsForResetScrollPositionToBottom:[y.initialized,y.messages.length!==0],bottomSpacerHeight:E.state.bottomSpace,ariaLabel:o.A11Y_MESSAGE_LIST,loading:!y.initialized||!f.channel,empty:k.length===0&&!F,error:!!(b||f.error),LoadingComponent:i.createElement(At,{type:"loading"}),EmptyComponent:(()=>{const T=U();return T?i.createElement("div",{style:{width:"100%"}},T):i.createElement(At,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(At,{type:"error",label:(b==null?void 0:b.message)??((q=f.error)==null?void 0:q.message),action:f.error?{label:o.RETRY,onClick:()=>f.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(wp,{style:{marginTop:16}}),U()),messageBottomArea:i.createElement(i.Fragment,null,F&&i.createElement("div",{id:`${we}-message-item`,role:"listitem",tabIndex:-1,"aria-label":mt({sender:F.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:k.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:F.isBot,sender:F.user,thinkingMessage:F.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(te=l==null?void 0:l.conversation)==null?void 0:te.senderAvatarEnabled})),((re=l==null?void 0:l.conversation)==null?void 0:re.isTalkToAgentViewEnabled)&&i.createElement(Mp,null)),overlayArea:i.createElement(i.Fragment,null,((K=l==null?void 0:l.conversation)==null?void 0:K.newMessageIndicatorEnabled)&&E.state.isAwayFromBottom&&y.newMessages.length>0&&i.createElement($p,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(y.newMessages),onClick:()=>E.actions.scrollToBottom()}),E.state.isAwayFromBottom&&y.newMessages.length===0&&!F&&i.createElement(r.ScrollToBottomButton,{onClick:()=>E.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),G&&i.createElement(Sf,{files:G.files,initialIndex:G.index,onClose:()=>L(null),visible:!0}),P&&i.createElement(Ke,{visible:!0,onClose:()=>N(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(Ke.ActionItem,{onClick:()=>{y.resendMessage(P),N(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(Ke.ActionItem,{destructive:!0,onClick:()=>{y.deleteMessage(P),N(null)}},o.FAILED_MESSAGE_REMOVE)))},Dp=_.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,$p=_.default(ap)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Pp=()=>i.createElement(Np,null),Fp=()=>{var o;const{origin:e}=pt(),{appId:t,aiAgentId:n}=ke(),{channelSource:r}=he();return(o=r.channel)!=null&&o.conversation?i.createElement(Bp,null,i.createElement(Xn,{style:{gap:4}},i.createElement(z,{color:p.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement(D,{as:"i",color:p.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(Xn,{role:"button",style:{gap:4},onClick:()=>{var u,d;const s=e??window.location.origin,a=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,l=`${s}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},i.createElement(D,{variant:"body3",color:p.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:p.themedColor.primary}},"conversation link")),i.createElement(z,{color:p.themedColor.primary,size:14,type:"copy"}))):null},Xn=_.default.div`display:flex;justify-content:center;align-items:center;`,Bp=_.default(Xn)`flex-direction:column;padding-block:16px;background-color:${p.themedColor.bg_100_500};gap:8px;`,Hp=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>ze(o.type)),r=e.some(o=>!ze(o.type));return n&&r?ze(t.type)?e.filter(o=>ze(o.type)):[t]:r?[t]:e},Up=(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}},Zs=c.createContext(void 0),Vp=({children:e})=>{var L,P;const{chatSDK:t}=ne(),{createAttachmentRules:n}=_e(),{stringSet:r}=Q(),{channelSource:o,state:s}=he(),[a,l]=c.useState([]),{announceError:u}=gr(),[d,m]=c.useState(null),h=n({channel:o.channel,uploadSizeLimit:(L=t.appInfo)==null?void 0:L.uploadSizeLimit}),g=((P=s==null?void 0:s.input)==null?void 0:P.disabled)??!1,C=h.isEnabled(),b=h.maxAttachmentCount,v=()=>m(null),f=N=>m(N),y=()=>{f({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",b.toString())})},E=N=>{f({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",N.toString())}),u({type:"fileSizeExceeded",maxSizeMB:N})},x=N=>{f({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",N.toString())})},S=N=>N.map(w=>({file:w,preview:{url:URL.createObjectURL(w),type:w.type,name:w.name}})),I=N=>{l(w=>[...w,...S(N)])},k=N=>{l(w=>(w.forEach($=>URL.revokeObjectURL($.preview.url)),S(N)))},M=N=>{const{passed:w,failedBySize:$,failedByType:O}=Up(N,h),q=$.length+O.length,te=N.length===1?$[0]:void 0;return te?E(h.getUploadSizeLimitInMB(te.type)):q>0&&x(q),w},U=N=>{if(!C||g||N.length===0)return;if(a.length>=b||a.length+N.length>b){y();return}const w=Hp(N),$=a.every(re=>ze(re.file.type)),O=w.every(re=>ze(re.type));if(a.length>0&&$!==O){f({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>{const re=M(w);re.length>0&&k(re)}});return}const q=M(w);if(q.length===0)return;a.length>0&&$&&O?I(q):k(q)},F=N=>{l(w=>{var O;const $=(O=w[N])==null?void 0:O.preview;return $&&URL.revokeObjectURL($.url),w.filter((q,te)=>te!==N)})},G=()=>{l(N=>(N.forEach(w=>URL.revokeObjectURL(w.preview.url)),[]))};return i.createElement(Zs.Provider,{value:{files:a,addFiles:U,removeFile:F,clearFiles:G,isFileUploadEnabled:C,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:f}},e,i.createElement(pr,{visible:!!d,...d??{},onClose:v}))},yr=()=>{const e=c.useContext(Zs);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Gp({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const o=c.useRef(!1);e&&t.current&&n.activeElement===t.current&&(o.current=!0),c.useLayoutEffect(()=>{var s;!e&&o.current&&(r==null||r(),(s=t.current)==null||s.focus(),o.current=!1)},[e,r])}const zp=()=>{const{announceError:e}=st();return c.useCallback(t=>{e({type:"sendFailed"},t)},[e])},Wp=1e3,qp=(e,t,n)=>{const{announcementsActive:r,setIsSuppressed:o}=st(),s=n??!0,a=c.useRef(!1),l=c.useRef(void 0),u=c.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]);c.useLayoutEffect(()=>{o(a.current)},[r,o]),Pl(t,u,{enabled:s,idleMs:Wp})},Kp=({enabled:e=!0,focusRoot:t})=>{const[n,r]=c.useState(!1),o=c.useRef(!1),s=c.useRef(!1);c.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const g=h;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=c.useCallback(()=>{if(s.current){s.current=!1,r(!1);return}r(o.current)},[]),l=c.useCallback(()=>{r(!1)},[]),u=c.useCallback(()=>{s.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:a,onBlur:l}}},Yp=_.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,jp=_.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;}`,Xp=_.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;${W.light`
|
|
414
|
+
background-color: ${p.color.background50};
|
|
291
415
|
`}
|
|
292
|
-
${
|
|
293
|
-
background-color: ${
|
|
416
|
+
${W.dark`
|
|
417
|
+
background-color: ${p.color.background500};
|
|
294
418
|
`}
|
|
295
419
|
path {
|
|
296
|
-
fill: ${
|
|
420
|
+
fill: ${p.themedColor.textMidEmphasis};
|
|
297
421
|
}
|
|
298
422
|
|
|
299
423
|
&:hover {
|
|
300
424
|
path {
|
|
301
|
-
fill: ${
|
|
425
|
+
fill: ${p.themedColor.textHighEmphasis};
|
|
302
426
|
}
|
|
303
427
|
}
|
|
304
428
|
|
|
429
|
+
&:focus-visible {
|
|
430
|
+
opacity: 1;
|
|
431
|
+
outline: 2px solid ${p.color.primary.main};
|
|
432
|
+
outline-offset: 2px;
|
|
433
|
+
}
|
|
434
|
+
|
|
305
435
|
circle {
|
|
306
|
-
stroke: ${
|
|
436
|
+
stroke: ${p.themedColor.bg_50_600};
|
|
307
437
|
}
|
|
308
|
-
`,
|
|
309
|
-
|
|
438
|
+
`,Zp=()=>{const e=Mt(),{conversation:t}=ee(),{files:n,removeFile:r,isFileUploadEnabled:o}=yr();return o&&n.length>0?i.createElement(Yp,null,n.map(({preview:{type:a,name:l,url:u}},d)=>{const m=t.file.removeButton(l),g=t.file.preview({name:l,mimeType:a,selected:!0}).props["aria-label"];return i.createElement(jp,{key:u},i.createElement(Xp,{type:"button",title:m["aria-label"],"aria-label":m["aria-label"],$mobile:e,onClick:()=>r(d)},i.createElement(z,{type:"close-filled",color:p.themedColor.textMidEmphasis})),a.startsWith("image/")?i.createElement("img",{alt:g,src:u}):i.createElement(Er,{name:l,mimeType:a,type:Qn(l,a),ariaLabel:g}))})):null},Jp={textArea:R.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Js=_.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${be}`,To=_.default.div`width:100%;position:relative;background-color:${p.themedColor.bg_100_500};border-radius:20px;`,Io=_.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,wo=_.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:${p.themedColor.textHighEmphasis};resize:none;width:100%;height:${ms}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${bs&&Jp.textArea};${({$focusVisible:e})=>e&&R.css`
|
|
439
|
+
outline: 2px solid ${p.themedColor.primary};
|
|
440
|
+
outline-offset: 2px;
|
|
441
|
+
`}
|
|
442
|
+
|
|
443
|
+
&::placeholder {
|
|
444
|
+
color: ${p.themedColor.textLowEmphasis};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
&:disabled {
|
|
448
|
+
cursor: not-allowed;
|
|
449
|
+
&::placeholder {
|
|
450
|
+
color: ${p.themedColor.textDisabled};
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
${({$blocked:e})=>e&&R.css`cursor:not-allowed;&::placeholder{color:${p.themedColor.textDisabled};}`}
|
|
455
|
+
`,Qp=_.default.input`display:none;`;_.default.div`display:flex;align-items:center;gap:24px;`;const e_=_.default(Js)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${p.themedColor.bg_100_500};path{fill:${p.themedColor.textHighEmphasis};}}&:active{background-color:${p.themedColor.bg_200_400};}}`,ko=_.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Lo=e=>e.startsWith("image/"),Mo=({disabled:e})=>{var k,M,U,F,G;const{stringSet:t}=Q(),{conversation:n}=ee(),{config:r}=ne(),o=c.useRef(null),s=c.useRef(null),[a,l]=c.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=yr(),g=m.includes(Bn),C=g?["image/*"]:m.filter(Lo),b=g?[Bn]:m.filter(L=>!Lo(L)),v=!!((U=(M=(k=r==null?void 0:r.conversation)==null?void 0:k.input)==null?void 0:M.gallery)!=null&&U.photoEnabled),f=!!((G=(F=r==null?void 0:r.conversation)==null?void 0:F.input)!=null&&G.fileEnabled),y=()=>g||C.length>0,E=()=>g||b.length>0,x=L=>{const P=L.currentTarget.files;P&&u(Array.from(P)),L.target.value=""},S=()=>{l(!0)},I=c.useMemo(()=>{const L=[];return v&&L.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:C.join(","),inputRef:o,onSelect:()=>{if(!y()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var P;return(P=o.current)==null?void 0:P.click()},100)}}),f&&L.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:s,onSelect:()=>{if(!E()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var P;return(P=s.current)==null?void 0:P.click()},100)}}),L},[C,m,t,v,f]);return d?i.createElement(i.Fragment,null,i.createElement(e_,{...n.messageInput.attachFileButton.props,disabled:e,onClick:S},i.createElement(z,{type:"add",color:e?p.themedColor.textDisabled:p.color.primary.main,size:20}),n.messageInput.attachFileButton.descriptionNode),I.map(L=>i.createElement(Qp,{key:L.type,type:"file",ref:L.inputRef,multiple:L.type==="image",onChange:x,accept:L.accept})),i.createElement(Ke,{visible:a,onClose:()=>l(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},I.map(L=>i.createElement(Ke.ActionItem,{key:L.type,onClick:L.onSelect,icon:L.icon},L.label)))):null},t_=()=>{const e=c.useRef(null),[t,n]=c.useState(""),{stringSet:r}=Q(),{conversation:o}=ee(),{rootElement:s}=ne(),a=He(s),{focusHandlers:l,isFocusVisible:u,suppressNextFocusVisible:d}=Kp({focusRoot:a}),{channelSource:m,messageSource:h,state:g}=he(),{files:C,addFiles:b,clearFiles:v}=yr(),f=zp(),y=c.useRef(!1),{_mode:E,disabled:x,disabledBy:S}=g.input,I=E==="readOnly",k=o.messageInput.textInput(r.A11Y_MESSAGE_INPUT),M=(()=>{if(!x)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}})();Pu({onDropFiles:K=>{b(K)}}),Gp({blurred:E==="disabled",elementRef:e,document:a,onRecoverFocus:()=>{d()}}),qp(m.channel,t,!x);const U=t.trim().length>0,F=C.length>0,G=!x&&(U||F),L=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},P=()=>{var K;d(),(K=e.current)==null||K.focus()};c.useEffect(()=>{var K;E!=="readOnly"||!y.current||(d(),(K=e.current)==null||K.focus(),y.current=!1)},[E,d]);const N=K=>{y.current=!1,f(K)},w=()=>{y.current=!1},$=async K=>{try{await K(),w()}catch{N(e.current)}},O=async()=>{if(x)return;const K=t.trim();if(!K&&!C.length)return;const T=[...C];if(y.current=!0,L(),P(),T.length===0){await $(()=>h.sendUserMessage({message:K}));return}if(T.length===1)await $(()=>h.sendFileMessage({message:K,file:T[0].file}));else{const V=T.map(({file:H})=>({file:H}));await $(()=>h.sendMultipleFilesMessage({message:K,fileInfoList:V}))}},q=K=>{const T=Array.from(K.clipboardData.files);T.length>0&&(K.preventDefault(),b(T))},te=K=>{K.key!=="Enter"||K.nativeEvent.isComposing||K.shiftKey||(K.preventDefault(),O())},re=K=>{if(x){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const T=Math.min(Ic,e.current.scrollHeight);ms<T&&(e.current.style.height=`${T}px`)}n(K.target.value)};return E==="disabled"?i.createElement(ko,null,i.createElement(Mo,{disabled:!0}),i.createElement(To,null,i.createElement(Io,null,i.createElement(wo,{rows:1,...k,disabled:!0,placeholder:M,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):i.createElement(ko,{"data-message-composer":""},i.createElement(Mo,{disabled:x}),i.createElement(To,null,i.createElement(Zp,null),i.createElement(Io,null,i.createElement(wo,{ref:e,rows:1,...k,readOnly:I,"aria-disabled":I?"true":void 0,placeholder:M,maxLength:5e3,$blocked:x,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:te,onChange:re,onFocus:l.onFocus,onBlur:l.onBlur,onPaste:q}))),G&&i.createElement(Js,{...o.messageInput.sendButton.props,onClick:()=>O()},i.createElement(z,{type:"send",color:p.color.primary.main,size:20}),o.messageInput.sendButton.descriptionNode))},n_=_.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:${p.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${W.light`
|
|
456
|
+
color: ${p.color.information.light};
|
|
310
457
|
`};
|
|
311
|
-
${
|
|
312
|
-
color: ${
|
|
458
|
+
${W.dark`
|
|
459
|
+
color: ${p.color.information.main};
|
|
313
460
|
`};
|
|
314
461
|
}
|
|
315
|
-
`,ng=d.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),rg=()=>{const{aiAgentInfo:e,userSession:t}=se(),{messageSource:n,channelSource:r}=ne(),[o,i]=d.useState(null),a=Pn("special-notice",r.channel),l=d.useCallback(()=>r.channel?a?n.messages.some(c=>it(c,(t==null?void 0:t.userId)??"")):!0:null,[r.channel,a,n.messages,t==null?void 0:t.userId]);return d.useEffect(()=>{o||i(l())},[l,o]),o||!e.specialNotice?null:s.createElement(tg,null,s.createElement(ng,null,e.specialNotice))},og=()=>s.createElement(sg,null,s.createElement(rg,null),s.createElement(Gh,null,s.createElement(eg,null))),sg=h.default.div`z-index:0;border:none;width:100%;`,ig=()=>{var o;const{testerType:e}=Xe(),{channelSource:t}=ne(),n=me(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?s.createElement(Uh,null):s.createElement(og,null)},Fo=({start:e,title:t,titleAlign:n="start",end:r})=>{const o=d.useRef(null),i=d.useRef(null),[a,l]=d.useState(0),[c,u]=d.useState(0);return d.useLayoutEffect(()=>{o.current&&l(o.current.offsetWidth),i.current&&u(i.current.offsetWidth)},[e,r]),s.createElement(ag,null,s.createElement(lg,null,n==="center"&&t&&s.createElement(cg,{$sideWidth:Math.max(a,c)},s.createElement(dg,null,t)),s.createElement(ug,null,s.createElement(mg,{ref:o},e),(n==="start"||n==="end")&&t&&s.createElement(gg,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),s.createElement(hg,{ref:i},r))))},ag=h.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${m.themedColor.textDisabled};`,lg=h.default.div`position:relative;height:56px;padding:11px 12px;`,cg=h.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;`,dg=h.default.div`max-width:100%;overflow:hidden;`,ug=h.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,mg=h.default.div`flex-shrink:0;display:flex;align-items:center;`,hg=h.default.div`flex-shrink:0;display:flex;align-items:center;`,gg=h.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;`,ht=()=>dt()?24:16,fg=()=>{const{state:e}=j(),t=ht(),n=()=>{e.setOpened(!1)};return s.createElement(xe,{"aria-label":"close messenger",type:"close",size:t,onClick:n})},pg=()=>{const{enableCloseConversationButton:e,dispatcher:t}=j(),{channelSource:n}=ne(),r=n.channel,o=ht(),i=(r==null?void 0:r.isAIAgent)&&e,a=!kn(r);if(!i)return null;const l=async()=>{r&&await t.send(Ue.CloseConversation({channelUrl:r.url}))};return s.createElement(xe,{"aria-label":"close conversation",type:"mute",size:o,disabled:a,onClick:l})},Eg=()=>{const{state:e,enableExpandButton:t}=j(),n=ht();return t?s.createElement(xe,{"aria-label":"expand",type:e.expanded?"collapse":"expand",size:n,onClick:()=>e.setExpanded(!e.expanded)}):null},_g=({label:e,children:t,position:n="top",disabled:r})=>r?t:s.createElement(An,null,t,s.createElement(xg,{$position:n},s.createElement(vg,{variant:"caption1"},e),s.createElement(bg,{$position:n}))),bg=({$position:e})=>s.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"},s.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:m.themedColor.textHighEmphasis})),Cg={top:M.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:M.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},An=h.default.div`position:relative;`,xg=h.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${ze.TOOLTIP};${({$position:e})=>Cg[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${An}:hover &,${An}:focus-within &{opacity:1;}`,vg=h.default(T)`padding:6px 8px;background:${m.themedColor.textHighEmphasis};color:${m.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,yg=()=>{const{logger:e}=j(),{stringSet:t}=K(),{channelSource:n}=ne(),r=n.channel,o=ht(),i=Pn("handoff-button",r),a=!kn(r)||He(r),[l,c]=d.useState(!1),u=async()=>{c(!1);try{const g=await(r==null?void 0:r.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};return i?s.createElement(s.Fragment,null,s.createElement(_g,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:a},s.createElement(xe,{"aria-label":"request handoff",type:"agent",size:o,disabled:a,onClick:()=>c(!0)})),s.createElement(Ze,{rootElementId:ae.WINDOW,visible:l,onClose:()=>c(!1)},s.createElement(Oo,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>c(!1),onConfirm:u}))):null},Sg=()=>{const{stringSet:e}=K(),{onNavigateToConversationList:t}=ne();return t?s.createElement(xe,{type:"menu",size:24,onClick:()=>t(),"aria-label":e.A11Y_OPEN_CONVERSATION_LIST}):null},Bo=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=se(),{fallbackIcon:o,url:i}=so({channel:e,aiAgentInfo:r,userSession:n}),a=M.useTheme();return i?s.createElement(xo,{src:i,size:t}):s.createElement(Ag,{$size:t,$bgColor:a.colors.base.primary},s.createElement(F,{type:o,size:t*.55,color:a.colors.base.primaryContrastContent}))},Ag=h.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;`,Tg=()=>{var l,c;const{channelSource:e}=ne(),{aiAgentInfo:t,userSession:n}=se(),{config:r}=de(),o=e.channel,i=so({channel:o,userSession:n,aiAgentInfo:t}),a=(c=(l=r==null?void 0:r.conversation)==null?void 0:l.header)==null?void 0:c.avatarEnabled;return s.createElement(Ig,null,a&&s.createElement(Bo,{channel:o,size:34}),s.createElement(wg,{variant:"h2",color:m.themedColor.textHighEmphasis},i.title))},Ig=h.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;overflow:hidden;`,wg=h.default(T)`text-overflow:ellipsis;overflow:hidden;white-space:nowrap;padding:2px 0;`,kg=e=>{const{components:t}=We.useContext();return s.createElement(Fo,{start:s.createElement(t.StartArea,null),title:s.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:s.createElement(t.EndArea,null)})},Mg=()=>{const{components:e}=We.useContext();return s.createElement(e.MenuButton,null)},$g=()=>{const{components:e}=We.useContext();return s.createElement(e.Title,null)},Lg=()=>{const{components:e}=We.useContext();return s.createElement(Og,null,s.createElement(e.HandoffButton,null),s.createElement(e.ConversationCloseButton,null),s.createElement(e.ExpandButton,null),s.createElement(e.CloseButton,null))},We=fe({template:kg,components:{StartArea:Mg,TitleArea:$g,EndArea:Lg,MenuButton:Sg,Title:Tg,HandoffButton:yg,ConversationCloseButton:pg,ExpandButton:Eg,CloseButton:fg}}),Rg=()=>{const{isActionbookTester:e}=Xe(),{Template:t}=We.useContext();return e?null:s.createElement(t,{titleAlign:"start"})},Og=h.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Uo=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:o,style:i,closedChannelUrl:a,onClearClosedChannelUrl:l})=>{const{Template:c}=Kt.useContext();return s.createElement(fo,{onNavigateToConversationList:t,channelUrl:n??a,onClearChannelUrl:r??l,shouldMarkAsRead:o},s.createElement(xn,null,s.createElement(xn.Consumer,null,u=>s.createElement(s.Fragment,null,s.createElement(Ng,{style:i,...u},s.createElement(c,null)),e))))},Dg=()=>{const{components:e}=Kt.useContext();return s.createElement(s.Fragment,null,s.createElement(e.Header,null),s.createElement(e.Body,null),s.createElement(e.Footer,null))},Kt=fe({template:Dg,components:{Header:Rg,Body:Bh,Footer:ig}}),Ng=h.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,{Provider:Pg,Context:Fg,useContext:qn}=te("ConversationList");function Ho({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=be,children:r}){return s.createElement(ji,{conversationListLimit:e,conversationListFilter:t},o=>s.createElement(Pg,{value:{...o,onOpenConversationView:n}},r))}const Bg=({channel:e})=>s.createElement(Bo,{channel:e}),Tn=99,Ug=e=>{var c;const{channel:t,onClick:n}=e,{stringSet:r,format:o}=K(),i=ci(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),a=di(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}),l=t.unreadMessageCount;return s.createElement(Hg,{role:"button",onClick:()=>n==null?void 0:n()},s.createElement(Vg,null,s.createElement(Bg,{...e})),s.createElement(zg,null,s.createElement(Gg,null,(c=t.lastMessage)!=null&&c.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?s.createElement(Eo,{variant:"subtitle1",color:m.themedColor.textHighEmphasis},i):s.createElement(T,{variant:"subtitle1",color:m.themedColor.textHighEmphasis,maxTextLines:1},i),s.createElement(Wg,null,me(t)&&s.createElement(s.Fragment,null,s.createElement(T,{variant:"caption1",color:m.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),s.createElement(qg,null)),s.createElement(T,{variant:"caption2",color:m.themedColor.textLowEmphasis,maxTextLines:1},a))),l>0&&s.createElement(Kg,{$count:l},s.createElement(T,{variant:"caption3",color:m.themedColor.textHighEmphasisInverse},l<=Tn?l:`${Tn}+`))))},Kn=fe({template:Ug,components:{}}),Hg=h.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:pointer;`,Vg=h.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,zg=h.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 ${m.themedColor.textDisabled};`,Gg=h.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;`,Wg=h.default.div`display:flex;align-items:center;gap:6px;`,qg=h.default.div`width:2px;height:2px;border-radius:1px;background-color:${m.themedColor.textLowEmphasis};`,Kg=h.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${m.themedColor.error};${({$count:e})=>e<=Tn&&M.css`
|
|
462
|
+
`,r_=c.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),o_=()=>{const{aiAgentInfo:e,userSession:t}=_e(),{messageSource:n,channelSource:r}=he(),[o,s]=c.useState(null),a=cr("special-notice",r.channel),l=c.useCallback(()=>r.channel?a?n.messages.some(u=>Tt(u,(t==null?void 0:t.userId)??"")):!0:null,[r.channel,a,n.messages,t==null?void 0:t.userId]);return c.useEffect(()=>{o||s(l())},[l,o]),o||!e.specialNotice?null:i.createElement(n_,null,i.createElement(r_,null,e.specialNotice))},s_=()=>i.createElement(i_,null,i.createElement(o_,null),i.createElement(Vp,null,i.createElement(t_,null))),i_=_.default.div`z-index:0;border:none;width:100%;`,a_=()=>{var o;const{testerType:e}=pt(),{channelSource:t}=he(),n=Se(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(Fp,null):i.createElement(s_,null)},Qs=({start:e,title:t,titleAlign:n="start",end:r})=>{const o=c.useRef(null),s=c.useRef(null),[a,l]=c.useState(0),[u,d]=c.useState(0);return c.useLayoutEffect(()=>{o.current&&l(o.current.offsetWidth),s.current&&d(s.current.offsetWidth)},[e,r]),i.createElement(l_,null,i.createElement(c_,null,n==="center"&&t&&i.createElement(u_,{$sideWidth:Math.max(a,u)},i.createElement(d_,null,t)),i.createElement(m_,null,i.createElement(h_,{ref:o},e),(n==="start"||n==="end")&&t&&i.createElement(f_,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(g_,{ref:s},r))))},l_=_.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${p.themedColor.textDisabled};`,c_=_.default.div`position:relative;height:56px;padding:11px 12px;`,u_=_.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;`,d_=_.default.div`max-width:100%;overflow:hidden;`,m_=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,h_=_.default.div`flex-shrink:0;display:flex;align-items:center;`,g_=_.default.div`flex-shrink:0;display:flex;align-items:center;`,f_=_.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;`,Dt=()=>Mt()?24:16,p_=()=>{const{state:e}=ne(),{messenger:t}=ee(),n=Dt(),r=()=>{e.setOpened(!1)};return i.createElement(Ue,{...t.closeButton,type:"close",size:n,onClick:r})},__=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ne(),{channelSource:n}=he(),{conversation:r}=ee(),o=n.channel,s=Dt(),a=(o==null?void 0:o.isAIAgent)&&e,l=!tr(o);if(!a)return null;const u=async()=>{o&&await t.send(rt.CloseConversation({channelUrl:o.url}))};return i.createElement(i.Fragment,null,i.createElement(Ue,{...r.closeConversationButton.props,type:"mute",size:s,disabled:l,onClick:u}),r.closeConversationButton.descriptionNode)},E_=()=>{const{state:e,enableExpandButton:t}=ne(),{messenger:n}=ee(),r=Dt();return t?i.createElement(Ue,{...n.expandButton(e.expanded),type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},b_=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(Zn,null,t,i.createElement(y_,{$position:n},i.createElement(S_,{variant:"caption1"},e),i.createElement(C_,{$position:n}))),C_=({$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:p.themedColor.textHighEmphasis})),v_={top:R.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:R.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Zn=_.default.div`position:relative;`,y_=_.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${ot.TOOLTIP};${({$position:e})=>v_[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Zn}:hover &,${Zn}:focus-within &{opacity:1;}`,S_=_.default(D)`padding:6px 8px;background:${p.themedColor.textHighEmphasis};color:${p.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,A_=2e3,Oo=0,x_=1500,jt=Symbol("header-focus-status-pause"),Ro="data-sb-header-focus-protected",T_="[data-message-composer]",No=new WeakMap,$n=e=>{const t=No.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return No.set(e,n),n},Pn=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},Zt=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},I_=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),Zt(e)},w_=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)})},k_=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(T_),!1),ei=()=>{const{setStatusPauseState:e}=st(),t=c.useRef(Symbol("header-focus-target")),n=c.useRef(!1),r=c.useRef(0),o=c.useRef(null),s=c.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),a=c.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+x_,s();const u=$n(e);Pn(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(jt,!0),Zt(u),u.maxPauseTimeout=setTimeout(()=>{I_(u),e(jt,!1)},A_)},[s,e]),l=c.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=$n(e),h=d instanceof HTMLElement&&Date.now()<=r.current;Pn(m,t.current),h&&(s(),o.current=setTimeout(()=>{if(o.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const C=d.ownerDocument.activeElement,b=C instanceof HTMLElement&&C.hasAttribute(Ro);if(C===d||b||!k_(C))return;const v=w_(d);d.focus({preventScroll:!0}),v()},Oo)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(Zt(m),e(jt,!1))},Oo))},[s,e]);return c.useEffect(()=>()=>{const u=$n(e);n.current=!1,s(),Pn(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(Zt(u),e(jt,!1))},[s,e]),{[Ro]:"true",onFocus:a,onBlur:l}},L_=()=>{const{logger:e}=ne(),{stringSet:t}=Q(),{channelSource:n}=he(),{conversation:r}=ee(),o=n.channel,s=Dt(),a=cr("handoff-button",o),l=!tr(o)||je(o),[u,d]=c.useState(!1),m=ei(),h=async()=>{d(!1);try{const g=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};return a?i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(b_,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(Ue,{...r.handoffButton.props,type:"agent",size:s,disabled:l,...m,onClick:()=>d(!0)})),r.handoffButton.descriptionNode),i.createElement(ft,{rootElementId:ce.WINDOW,visible:u,onClose:()=>d(!1)},i.createElement(js,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h}))):null},M_=()=>{const{conversation:e}=ee(),{onNavigateToConversationList:t}=he();return t?i.createElement(i.Fragment,null,i.createElement(Ue,{...e.menuButton.props,...Tc,type:"menu",size:24,onClick:()=>t()}),e.menuButton.descriptionNode):null},ti=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=_e(),{fallbackIcon:o,url:s}=ur({channel:e,aiAgentInfo:r,userSession:n}),a=R.useTheme();return s?i.createElement(Ns,{src:s,size:t,"aria-hidden":"true"}):i.createElement(O_,{"aria-hidden":"true",$size:t,$bgColor:a.colors.base.primary},i.createElement(z,{type:o,size:t*.55,color:a.colors.base.primaryContrastContent}))},O_=_.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;`,R_=()=>{var m,h;const{channelSource:e}=he(),{aiAgentInfo:t,userSession:n}=_e(),{conversation:r}=ee(),{config:o}=ke(),s=e.channel,a=ur({channel:s,userSession:n,aiAgentInfo:t}),l=(h=(m=o==null?void 0:o.conversation)==null?void 0:m.header)==null?void 0:h.avatarEnabled,u=ei(),d=r.headerTitle(a.title);return i.createElement(N_,null,l&&i.createElement(ti,{channel:s,size:34}),i.createElement(D_,{...d,...u},a.title))},N_=_.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;overflow:hidden;`,D_=_.default(D).attrs({variant:"h2",color:p.themedColor.textHighEmphasis})`
|
|
463
|
+
margin: 0;
|
|
464
|
+
flex: 1;
|
|
465
|
+
min-width: 0;
|
|
466
|
+
text-overflow: ellipsis;
|
|
467
|
+
overflow: hidden;
|
|
468
|
+
white-space: nowrap;
|
|
469
|
+
padding: 2px 0;
|
|
470
|
+
|
|
471
|
+
&:focus {
|
|
472
|
+
outline: none;
|
|
473
|
+
}
|
|
474
|
+
`,$_=e=>{const{components:t}=at.useContext();return i.createElement(Qs,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null)})},P_=()=>{const{components:e}=at.useContext();return i.createElement(e.MenuButton,null)},F_=()=>{const{components:e}=at.useContext();return i.createElement(e.Title,null)},B_=()=>{const{components:e}=at.useContext();return i.createElement(U_,null,i.createElement(e.HandoffButton,null),i.createElement(e.ConversationCloseButton,null),i.createElement(e.ExpandButton,null),i.createElement(e.CloseButton,null))},at=Pe({template:$_,components:{StartArea:P_,TitleArea:F_,EndArea:B_,MenuButton:M_,Title:R_,HandoffButton:L_,ConversationCloseButton:__,ExpandButton:E_,CloseButton:p_}}),H_=()=>{const{isActionbookTester:e}=pt(),{Template:t}=at.useContext();return e?null:i.createElement(t,{titleAlign:"start"})},U_=_.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,ni=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:o,announcementsEnabled:s,style:a,closedChannelUrl:l,onClearClosedChannelUrl:u})=>{const{Template:d}=Cn.useContext();return i.createElement(xs,{onNavigateToConversationList:t,channelUrl:n??l,onClearChannelUrl:r??u,shouldMarkAsRead:o},i.createElement(Kn,null,i.createElement(Kn.Consumer,null,m=>i.createElement(Jc,{announcementsActive:s},i.createElement(V_,null),i.createElement(z_,{style:a,...m},i.createElement(d,null)),e))))},V_=()=>(Zu(),Gu(),Yu(),null),G_=e=>{const{components:t}=Cn.useContext();return i.createElement(i.Fragment,null,i.createElement(t.Header,null),i.createElement(t.Body,null),i.createElement(t.Footer,null))},Cn=Pe({template:G_,components:{Header:H_,Body:Pp,Footer:a_}}),z_=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,{Provider:W_,Context:q_,useContext:vn}=me("ConversationList");function ri({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=oe,children:r}){return i.createElement(pl,{conversationListLimit:e,conversationListFilter:t},o=>i.createElement(W_,{value:{...o,onOpenConversationView:n}},r))}const K_=({channel:e})=>i.createElement(ti,{channel:e}),Jn=99,Y_=e=>{var f,y;const{channel:t,onClick:n}=e,{stringSet:r,format:o}=Q(),{userSession:s,aiAgentInfo:a}=_e(),{conversationList:l}=ee(),u=ur({channel:t,userSession:s,aiAgentInfo:a}),d=wa(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=ka(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}),h=t.unreadMessageCount,g=(f=t.lastMessage)!=null&&f.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,C=Se(t)?r.CONVERSATION_LIST__ENDED:Jo(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),b=n?()=>n():void 0,v=l.item({agent:g,status:C,time:m,unreadCount:h,onActivate:b});return i.createElement(j_,{"data-testid":"sb-conversation-list-item",$clickable:!!b,...v.props},i.createElement(X_,null,i.createElement(K_,{...e})),i.createElement(Z_,null,i.createElement(J_,null,(y=t.lastMessage)!=null&&y.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?i.createElement(Ls,{variant:"subtitle1",color:p.themedColor.textHighEmphasis},d):i.createElement(D,{variant:"subtitle1",color:p.themedColor.textHighEmphasis,maxTextLines:1},d),i.createElement(Q_,null,Se(t)&&i.createElement(i.Fragment,null,i.createElement(D,{variant:"caption1",color:p.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),i.createElement(eE,null)),i.createElement(D,{variant:"caption2",color:p.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&i.createElement(tE,{$count:h},i.createElement(D,{variant:"caption3",color:p.themedColor.textHighEmphasisInverse},h<=Jn?h:`${Jn}+`))),v.descriptionNode)},Sr=Pe({template:Y_,components:{}}),j_=_.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"};`,X_=_.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,Z_=_.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 ${p.themedColor.textDisabled};`,J_=_.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;`,Q_=_.default.div`display:flex;align-items:center;gap:6px;`,eE=_.default.div`width:2px;height:2px;border-radius:1px;background-color:${p.themedColor.textLowEmphasis};`,tE=_.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${p.themedColor.error};${({$count:e})=>e<=Jn&&R.css`
|
|
316
475
|
width: 20px;
|
|
317
476
|
`}
|
|
318
|
-
`,
|
|
477
|
+
`,nE=({items:e,renderItem:t,onEndReached:n})=>{const r=o=>{const s=o.target;s.scrollHeight-s.scrollTop===s.clientHeight&&(n==null||n())};return i.createElement(rE,{onScroll:o=>r(o)},e.map((o,s)=>t(o,s)))},rE=_.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,oE=()=>{const{stringSet:e}=Q(),{listSource:t,onOpenConversationView:n}=vn(),{Template:r}=Sr.useContext();return t.initialized?t.channels.length===0?i.createElement(At,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):i.createElement(nE,{items:t.channels,renderItem:o=>{var s,a,l;return i.createElement(r,{key:o.url,channel:o,onClick:()=>n(o.url,Se(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(At,{type:"loading"})},sE=()=>{const{stringSet:e}=Q(),{_aiAgentSDK:t}=ke(),{language:n,countryCode:r,context:o}=ne(),{aiAgentInfo:s,refreshActiveChannel:a,createConversation:l}=_e(),{onOpenConversationView:u}=vn(),{conversationList:d}=ee(),m=async()=>{var h;if(s.isMultipleActiveConversationsEnabled){const g=await l({aiAgentId:s.userId,language:n,country:r,context:o});(h=t.session)==null||h._updateActiveChannel({url:g,status:"open"}),u(g,"open")}else{const g=await a();u(g,"open")}};return i.createElement(iE,{...d.footer.button({onActivate:m})},i.createElement(aE,{variant:"h1"},e.TALK_TO_AGENT))},iE=_.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,aE=_.default(D)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,lE=()=>{const{state:e}=ne(),{messenger:t}=ee(),n=Dt(),r=()=>{e.setOpened(!1)};return i.createElement(Ue,{...t.closeButton,type:"close",size:n,onClick:r})},cE=()=>{const{stringSet:e}=Q();return i.createElement(uE,{forwardedAs:"h2",variant:"h2",color:p.themedColor.textHighEmphasis},e.CONVERSATION_LIST__HEADER_TITLE)},uE=_.default(D)`margin:0;padding:0 4px;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,dE=e=>{const{components:t}=_t.useContext();return i.createElement(Qs,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null)})},mE=()=>null,hE=()=>{const{components:e}=_t.useContext();return i.createElement(e.Title,null)},gE=()=>{const{components:e}=_t.useContext();return i.createElement(e.CloseButton,null)},_t=Pe({template:dE,components:{StartArea:mE,TitleArea:hE,EndArea:gE,Title:cE,CloseButton:lE}}),fE=()=>{const{Template:e}=_t.useContext();return i.createElement(e,{titleAlign:"start"})},oi=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,style:o})=>{const{Template:s}=yn.useContext();return i.createElement(ri,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},i.createElement(_E,{style:o},i.createElement(s,null)),n)},pE=()=>{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=Pe({template:pE,components:{Header:fE,Body:oE,Footer:sE}}),_E=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,EE=R.css`:where(#${ce.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,bE=[EE,Bc,Hc],CE=(e,...t)=>R.createGlobalStyle(e,...bE,...t),vE=CE``,yE=Ia(Cn,Je,Nt,pn,bn,yn,at,Sr,_t,En);function si({appearance:e,rootElement:t,logger:n,language:r,languageCode:o,stringSet:s,children:a,messageTemplate:l,theme:u}){return Wc(Oc,t),i.createElement(R.StyleSheetManager,{target:t},i.createElement(Vc,{rootElement:t,logger:n,appearance:e,theme:u},i.createElement(bl,{internalVariables:l==null?void 0:l.__internalVariables},i.createElement(Fc,{stringSet:s,logger:n,language:r,languageCode:o},i.createElement(yE,null,a,i.createElement(vE,null))))))}const Ar=c.forwardRef(function({rootElement:t=document.body,logLevel:n=ie.LogLevel.WARN,language:r=navigator.language,userSessionInfo:o,children:s,chatParams:a,...l},u){var h,g,C;yt.level!==n&&(yt.level=n),zc("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const d=gs(r),m=fs.has(d)?d:Lt;return i.createElement("div",{id:ce.ENTRY,lang:m,style:{width:"fit-content",height:"fit-content",...l.entryStyle}},i.createElement(si,{logger:yt,rootElement:t,appearance:(h=l.agentPreviewConfigs)==null?void 0:h.appearance,stringSet:l.stringSet,language:m,messageTemplate:l.messageTemplate,theme:l.theme},i.createElement(eu,{rootElement:t,language:r,logger:yt,dispatcher:ii,chatParams:{...a,...l.customApiHost&&{customApiHost:l.customApiHost},...l.customWebSocketHost&&{customWebSocketHost:l.customWebSocketHost}},chatSDK:l.customChatSDK,_forceCreateChannel:(g=l.agentPreviewConfigs)==null?void 0:g.forceCreateChannel,_agentVersion:(C=l.agentPreviewConfigs)==null?void 0:C.agentVersion,...l},i.createElement(Cu,{ref:u,userSessionInfo:o},i.createElement(ef,{...l._UNSAFE_INTERNAL_dashboardTester},i.createElement(Xc,null,s,i.createElement("div",{id:ce.MODAL_ROOT,dir:l.dir})))))))}),yt=new qo(ie.LogLevel.WARN),ii=new Wo(yt),{Provider:SE,useContext:xr}=me("PageChildren"),ai=({children:e})=>{const[t,n]=c.useState(null),[r,o]=c.useState(null);return i.createElement(SE,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:o}},e)},li=({children:e,isOpened:t})=>{const{dir:n,rootElement:r}=ne(),o=He(r,!0);return c.useEffect(()=>{const s="sb-agent-block-scroll";return t?o.body.classList.add(s):o.body.classList.remove(s),()=>{o.body.classList.remove(s)}},[o,t]),i.createElement(AE,{dir:n,$visible:t},e)},AE=_.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${ot.WINDOW};visibility:${({$visible:e})=>e?"visible":"hidden"};`,xE=48,TE=2/3;function ci({className:e,children:t,isOpened:n,onClick:r,ariaLabel:o,"aria-label":s,"aria-describedby":a,type:l,imageUrl:u,dir:d,animated:m=!0,backgroundColor:h,size:g=xE}){const C=$s(),b=m&&!C,v=zn(h),f=Math.round(g*TE),y=s??o;return i.createElement(kE,{dir:d,id:ce.LAUNCHER,className:e,"aria-label":y??"Sendbird AIAgent Launcher","aria-describedby":a,onClick:r,$animated:b,$backgroundColor:h,$prefersReducedMotion:C,$size:g},i.createElement(LE,{$isOpened:n,$animated:b,$fillColor:v,$iconSize:f,$prefersReducedMotion:C},i.createElement(Do.Open,{url:u,isDefaultIcon:l==="default_icon",size:f})),i.createElement(ME,{$isOpened:n,$animated:b,$fillColor:v,$iconSize:f,$prefersReducedMotion:C},i.createElement(Do.Close,{size:f})),t)}const IE=R.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,wE=R.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===xt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,ui=R.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>R.css`
|
|
319
478
|
ellipse,
|
|
320
479
|
path {
|
|
321
480
|
fill: ${e};
|
|
@@ -325,15 +484,25 @@
|
|
|
325
484
|
}
|
|
326
485
|
`}
|
|
327
486
|
}
|
|
328
|
-
`,
|
|
487
|
+
`,kE=_.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&&IE}`,di=_.default.span.attrs({"aria-hidden":"true"})`
|
|
488
|
+
position: absolute;
|
|
489
|
+
width: 100%;
|
|
490
|
+
height: 100%;
|
|
491
|
+
border-radius: 50%;
|
|
492
|
+
overflow: hidden;
|
|
493
|
+
user-select: none;
|
|
494
|
+
display: flex;
|
|
495
|
+
justify-content: center;
|
|
496
|
+
align-items: center;
|
|
497
|
+
`,LE=_.default(di)`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)")};${wE}${ui}`,ME=_.default(di)`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)")};${ui}`,Do={Open:e=>e.url?i.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):i.createElement(z,{size:e.size,type:"delight"}),Close:({size:e})=>i.createElement(z,{size:e,type:"chevron-down"})},$o=(e,t)=>Array.from(e.querySelectorAll(t)).find(Ot)??null,mi=e=>$o(e,xc)??$o(e,vs),OE=e=>{const t=mi(e)??e;t===e&&!t.hasAttribute("tabindex")&&t.setAttribute("tabindex","-1"),t.focus()},RE=(e,t)=>{c.useEffect(()=>{if(!e||!t.current)return;let n=!1;return Ce(()=>{n||!t.current||OE(t.current)}),()=>{n=!0}},[e,t])};function hi({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:o}=R.useTheme(),{dir:s,rootElement:a,state:l}=ne(),{launcher:u}=ee(),{launcherInfo:d,statsTrackers:m}=_e(),h=(r??n)==="ConversationList",g=u.button({isOpened:l.opened,opensConversationList:h}),C=He(a);c.useLayoutEffect(()=>{m.initialRender.setPresentMethod("launcher_toggle")},[m]),DE();const b=E=>C.querySelector(`#${E}`),v=()=>{Ce(()=>{const E=b(ce.WINDOW),x=E?mi(E):null;x==null||x.focus()})},f=()=>{Ce(()=>{var E;(E=b(ce.LAUNCHER))==null||E.focus()})},y=()=>{const E=!l.opened;l.setOpened(E),E?v():f()};return i.createElement(ci,{dir:s,className:e,isOpened:l.opened,onClick:y,type:d.type,imageUrl:d.imageUrl,backgroundColor:o.base.primary,size:t,...g.props},g.descriptionNode)}const NE=1e3*60;function DE(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ne(),o=c.useRef(null);c.useEffect(()=>{if(!r)return;function s(){o.current&&(clearTimeout(o.current),o.current=null)}function a(){e.connectionState===ie.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")},NE)}t.opened?a():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const gi=c.createContext(null);function Tr(){const e=c.useContext(gi);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function fi({children:e}){const t=Tr();return typeof e=="function"?e(t):i.createElement(i.Fragment,null,e)}const $E=R.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,PE=R.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,FE=R.css`animation-name:${$E};animation-duration:0.3s;animation-fill-mode:forwards;`,BE=R.css``,HE=R.css`animation-name:${PE};animation-duration:0.3s;animation-fill-mode:forwards;`,UE=R.css`visibility:hidden;`,VE=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return FE;case"entered":return BE;case"exiting":return HE;case"exited":return UE;default:return""}}}${({$active:e})=>e?R.css`
|
|
329
498
|
z-index: 999;
|
|
330
|
-
`:
|
|
331
|
-
`;function
|
|
499
|
+
`:R.css`z-index:1;pointer-events:none;`}
|
|
500
|
+
`;function Jt({initialId:e,children:t}){const[n,r]=c.useState([e]),o=n[n.length-1],s=c.useCallback((f,y)=>{r(E=>[...E,f]),h(E=>({...E,[f]:!0})),y!=null&&y.reset&&v(E=>({...E,[f]:(E[f]||0)+1})),C(E=>({...E,[f]:"entering"})),setTimeout(()=>{C(E=>({...E,[f]:"entered"}))},300)},[]),a=c.useCallback(()=>{r(f=>{if(f.length<=1)return f;const y=f[f.length-1];return C(E=>({...E,[y]:"exiting"})),setTimeout(()=>{C(E=>({...E,[y]:"exited"})),r(E=>E.slice(0,-1))},300),f})},[]),l=c.useMemo(()=>({navigation:{navigate:s,pop:a},activeScreenId:o}),[s,a,o]),u=c.useMemo(()=>c.Children.toArray(t).filter(f=>f.type===fi),[t]),d=c.useMemo(()=>{const f={};return u.forEach(y=>{const{id:E,lazy:x,children:S}=y.props;f[E]={lazy:x,element:typeof S=="function"?S(l):S}}),f},[u,l]),[m,h]=c.useState(()=>{const f={};return Object.entries(d).forEach(([y,{lazy:E}])=>{E===!1&&(f[y]=!0)}),f[e]=!0,f}),[g,C]=c.useState(()=>{const f={};return Object.keys(d).forEach(y=>{y===e?f[y]="entered":f[y]="exited"}),f}),[b,v]=c.useState({});return i.createElement(gi.Provider,{value:l},i.createElement(GE,null,Object.keys(d).map(f=>{var S;if(!m[f])return null;const y=g[f]||"exited",E=f===o,x=`${f}-${b[f]||0}`;return i.createElement(VE,{key:x,$transitionState:y,$active:E},(S=d[f])==null?void 0:S.element)})))}const GE=_.default.div`position:relative;width:100%;height:100%;`;Jt.Screen=fi;const ye={conv:"conv",convList:"conv-list"},Po=({isOpened:e,activeScreenId:t})=>e&&t===ye.conv,zE=({screenId:e,conversationKey:t,navigationKey:n})=>e===ye.conv?`${e}:${t??""}`:n?`${e}:${n}`:e,WE=({initialRoute:e,isOpened:t,selectedChannelUrl:n,setSelectedChannelUrl:r})=>{const{announceScreenEntry:o}=gr(),s=c.useRef(null),a=c.useRef(null),l=c.useRef(0),[u,d]=c.useState(0),m=c.useCallback(b=>{const v=zE(b);s.current!==v&&(s.current=v,a.current=b,b.screenId===ye.convList&&o({screen:"conversationList"}))},[o]),h=c.useCallback((b,v)=>{const f={screenId:ye.conv,conversationKey:v};r(v),b.navigate(ye.conv),a.current=f,t&&m(f)},[m,t,r]),g=c.useCallback(b=>{l.current+=1;const v=l.current,f={screenId:ye.convList,navigationKey:`visit:${v}`};a.current=f,d(v),b.navigate(ye.convList)},[]),C=c.useCallback(()=>{var v;const b=((v=a.current)==null?void 0:v.screenId)===ye.convList?a.current:{screenId:ye.convList};m(b)},[m]);return c.useEffect(()=>{if(t){const b=a.current?a.current.screenId===ye.conv?{screenId:ye.conv,conversationKey:n??a.current.conversationKey}:a.current:{screenId:e,conversationKey:e===ye.conv?n:void 0};b.screenId!==ye.convList&&m(b)}else s.current=null,a.current=null},[m,e,t,n]),{announceConversationListScreen:C,conversationListAnnouncementToken:u,navigateToConversationList:g,openConversation:h}},nt={conv:"conv",convList:"conv-list"},qE=e=>e===nt.convList?"ConversationList":"Conversation",pi=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:o})=>{const{conversationChildren:s,conversationListChildren:a}=xr(),l=(()=>{switch(t){case"Conversation":return nt.conv;case"ConversationList":return nt.convList;default:return nt.conv}})(),{announceConversationListScreen:u,conversationListAnnouncementToken:d,navigateToConversationList:m,openConversation:h}=WE({initialRoute:l,isOpened:e,selectedChannelUrl:n,setSelectedChannelUrl:r}),g=i.createElement(i.Fragment,null,i.createElement(KE,{onOpenConversationView:(C,b)=>h(C,b)}),i.createElement(jE,{onActiveRouteChange:o}));return i.createElement(Jt,{initialId:l},i.createElement(Jt.Screen,{id:nt.conv},({navigation:C,activeScreenId:b})=>i.createElement(ni,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>m(C),announcementsEnabled:Po({isOpened:e,activeScreenId:b}),shouldMarkAsRead:Po({isOpened:e,activeScreenId:b})},g,s)),i.createElement(Jt.Screen,{id:nt.convList,lazy:!0},({navigation:C,activeScreenId:b})=>{const v=e&&b===nt.convList;return i.createElement(oi,{onOpenConversationView:f=>{h(C,f)}},i.createElement(YE,{announcementToken:d,enabled:v,onAnnounce:u}),g,a)}))},KE=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=_e(),{navigation:n}=Tr();return t(({channel:r})=>{e(n,r.url)}),null},YE=({announcementToken:e,enabled:t,onAnnounce:n})=>{const{listSource:r}=vn();return c.useEffect(()=>{if(!t||!r.initialized)return;const o=setTimeout(()=>{n()},0);return()=>{clearTimeout(o)}},[e,t,r.initialized,n]),null},jE=({onActiveRouteChange:e})=>{const{activeScreenId:t}=Tr();return c.useEffect(()=>{e==null||e(qE(t))},[t,e]),null},XE=`#${ce.WINDOW} [role="dialog"][aria-modal="true"], #${ce.MODAL_ROOT} [role="dialog"][aria-modal="true"]`,ZE=e=>!!e.querySelector(XE),_i=(e,t)=>c.useCallback(n=>{var r;if(n.key==="Escape"&&e){const s=n.currentTarget.getRootNode();if(ZE(s))return;n.stopPropagation(),t(!1),(r=s.querySelector(`#${ce.LAUNCHER}`))==null||r.focus()}},[e,t]),JE=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:o,state:s}=ne(),a=_i(t,s.setOpened),l=c.useRef(null);return RE(t,l),i.createElement(QE,null,i.createElement(eb,{ref:l,dir:o,id:ce.WINDOW,$isExpanded:e,$isOpened:t,onKeyDown:a},n),r)},QE=_.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,eb=_.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&&nb};${({$isExpanded:e})=>e&&tb};`,tb=R.css`width:743px;height:723px;`,nb=R.css`z-index:${ot.WINDOW};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;`,rb=c.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const o=Mt(),[s,a]=c.useState(t),[l,u]=c.useState(n.entryPoint??"Conversation"),d=o?li:JE;return i.createElement(Ar,{enableExpandButton:!o,ref:r,...n},i.createElement(Es,null,({state:m})=>i.createElement(ai,null,i.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,launcher:i.createElement(hi,{entryPoint:n.entryPoint,activeRoute:l})},i.createElement(pi,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:a,onActiveRouteChange:u})),e)))}),{Provider:ob,useContext:Ir}=me("FixedMessengerStyle");function Ei(e,t,n,r=0){const{top:o,bottom:s,start:a,end:l}=n;let u="",d="";switch(e){case"start":d=`inset-inline-start: ${De(a)}`;break;case"end":d=`inset-inline-end: ${De(l)}`;break}switch(t){case"top":u=`top: calc(${De(o)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${De(s)} + ${r}px)`;break}return R.css`${u};${d};`}function sb(e){const{horizontal:t,vertical:n,margin:r,launcherSize:o}=Ir();return i.createElement(ib,{...e,size:o,$horizontal:t,$vertical:n,$margin:r})}const ib=_.default(hi)`position:fixed;z-index:${ot.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>Ei(e,t,n)};`,ab=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r,state:o}=ne(),{horizontal:s,vertical:a,margin:l,launcherSize:u}=Ir(),d=_i(t,o.setOpened);return i.createElement(lb,{dir:r,id:ce.WINDOW,"aria-hidden":t?void 0:"true",inert:t?void 0:!0,$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:a,$margin:l,$launcherSize:u,onKeyDown:d},n)},lb=_.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})=>Ei(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;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
|
|
332
501
|
[dir='rtl'] &:not([dir='ltr']),
|
|
333
502
|
&[dir='rtl'] {
|
|
334
503
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
335
504
|
}
|
|
336
505
|
|
|
337
|
-
${({$isOpened:e})=>e&&
|
|
338
|
-
${({$isExpanded:e})=>e&&
|
|
339
|
-
`,
|
|
506
|
+
${({$isOpened:e})=>e&&ub};
|
|
507
|
+
${({$isExpanded:e})=>e&&cb};
|
|
508
|
+
`,cb=R.css`width:743px;height:723px;`,ub=R.css`z-index:${ot.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;`,bi={top:24,bottom:24,start:24,end:24},db=c.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[o,s]=c.useState(t),[a,l]=c.useState(n.entryPoint??"Conversation"),[u,d]=c.useState("end-bottom"),[m,h]=c.useState(bi),[g,C]=c.useState(48),b=Mt(),v=b?li:ab,{horizontal:f,vertical:y}=c.useMemo(()=>{const[E,x]=u.split("-");return{horizontal:E==="start"?"start":"end",vertical:x==="top"?"top":"bottom"}},[u]);return i.createElement(Ar,{enableExpandButton:!b,ref:r,...n},i.createElement(Es,null,({state:E})=>i.createElement(ob,{value:{horizontal:f,vertical:y,margin:m,launcherSize:g,setPosition:d,setMargin:h,setLauncherSize:C}},i.createElement(ai,null,i.createElement(v,{isExpanded:E.expanded,isOpened:E.opened},i.createElement(pi,{isOpened:E.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:s,onActiveRouteChange:l})),i.createElement(sb,{entryPoint:n.entryPoint,activeRoute:a}),e))))}),mb=e=>{var o,s,a,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=Ir();return c.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...bi,...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},hb=({children:e})=>{const{setConversationChildren:t}=xr();return c.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},gb=({children:e})=>{const{setConversationListChildren:t}=xr();return c.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},fb=Object.assign(db,{Style:mb,ConversationChildren:hb,ConversationListChildren:gb}),pb=e=>{const{refreshActiveChannel:t}=_e(),[n,r]=c.useState(!1),o=c.useRef(null),s=c.useRef(null);return c.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]),c.useCallback(()=>new Promise((a,l)=>{o.current=a,s.current=l,e().then(()=>r(!0)).catch(l)}),[e])};Xo.set(ie.SendbirdPlatform.JS,{deviceOSPlatform:Vi()?ie.DeviceOsPlatform.MOBILE_WEB:ie.DeviceOsPlatform.WEB,messengerVersion:wc,keyValueStorage:Lc(),networkStateAdapter:kc()});exports.ANCHOR_REL=mr;exports.AgentProviderContainer=Ar;exports.AgentUIProviderContainer=si;exports.AnonymousSessionInfo=Vn;exports.CSATType=Ne;exports.Commands=rt;exports.Conversation=ni;exports.ConversationContext=Nu;exports.ConversationContextProvider=xs;exports.ConversationHeaderLayout=at;exports.ConversationLayout=Cn;exports.ConversationList=oi;exports.ConversationListContext=q_;exports.ConversationListContextProvider=ri;exports.ConversationListHeaderLayout=_t;exports.ConversationListItemLayout=Sr;exports.ConversationListLayout=yn;exports.DefaultMessenger=rb;exports.DeskTicketPriority=sr;exports.DeskTicketStatus=or;exports.FixedMessenger=fb;exports.IncomingMessageLayout=Je;exports.LauncherBase=ci;exports.LogLevel=er;exports.ManualSessionInfo=Ko;exports.MessageListUILayout=bn;exports.MessageLogs=Ks;exports.OutgoingMessageLayout=Nt;exports.PlaceholderLayout=En;exports.SystemMessageLayout=pn;exports.cssVars=p;exports.escapeMarkdownSyntax=Hi;exports.mapCommonStringsToReactFormat=hs;exports.messengerDispatcher=ii;exports.useAIAgentContext=ke;exports.useConversationContext=he;exports.useConversationListContext=vn;exports.useLocalizationContext=Q;exports.useMessengerContext=ne;exports.useMessengerSessionContext=_e;exports.useRefreshActiveChannel=pb;
|