@sendbird/ai-agent-messenger-react 1.21.1 → 1.21.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.js +242 -236
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var js=Object.defineProperty;var Ys=(e,t,n)=>t in e?js(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var C=(e,t,n)=>Ys(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Z=require("@sendbird/chat"),u=require("react"),w=require("styled-components"),Fe=require("date-fns"),Xs=require("date-fns/locale/en-US"),ee=require("@sendbird/chat/aiAgent"),ke=require("@sendbird/chat/message"),tt=require("@sendbird/chat/groupChannel"),Le=require("@sendbird/uikit-tools"),Zs=require("react-dom"),Js=require("date-fns/isSameDay"),an=require("@sendbird/react-uikit-message-template-view"),Qs=require("@sendbird/uikit-message-template"),eo=require("dompurify"),to=require("@emotion/is-prop-valid"),Rt=e=>e&&e.__esModule?e:{default:e};function no(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 ro=Rt(Z),o=no(u),h=Rt(w),Dr=Rt(eo),so=Rt(to),Ke="sb-agent",Nr="KEY_IMG_ASPECT_RATIO",ln="*/*",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},fe=e=>!!e&&"sender"in e,oo=e=>fe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),ao=(e,t,n,r=!0)=>{if(!r||!fe(e))return"single";const s=()=>{if(!t||!fe(t))return!1;const c=t.sender.userId===e.sender.userId,d=Fe.isSameMinute(t.createdAt,e.createdAt);return c&&d},a=()=>{if(!n||!fe(n))return!1;const c=n.sender.userId===e.sender.userId,d=Fe.isSameMinute(n.createdAt,e.createdAt);return c&&d},i=s(),l=a();return i&&l?"middle":i?"bottom":l?"top":"single"},rt=(e,t)=>(()=>{var r;return fe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,We={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>fe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>fe(e)&&(e.sender.userId===t||e.sendingStatus===ke.SendingStatus.PENDING)},we=e=>e.startsWith("image/"),Pr=e=>e.startsWith("video/"),vn=(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"},Fr=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},yn=e=>{switch(e){case"top":case"middle":return H.GAP_GROUPED;default:return H.GAP_UNGROUPED}},io=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(a,...i)=>{const[l,c,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),s=d+a.length,a}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(a=>a.type!=="text"?a:{...a,value:t(a.value)}):r},lo=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),co=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),uo=e=>e.replace(/~~/g,"\\~\\~"),mo=e=>{let t=e;return t=lo(t),t=co(t),t=uo(t),t},ho=typeof navigator<"u"&&navigator.product==="ReactNative",Kn=(e,t)=>{const n=r=>!t||t.length===0?!0:fe(r)&&t.includes(r.sendingStatus);return ho?e.find(n):e.findLast(n)};function Ce(){}function go(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function fo(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 cn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Me={isStreaming(e){const t=cn(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(rt(e,t)){const r=cn(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)}},Xt=`@${Ke}`,po=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Xt}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const a=fo(`${e}/${t}/${s}`);return`${Xt}-udata/${a}`},anonUserSession:()=>`${Xt}-session/${e}/${t}`};return{template:{set:(s,a)=>n.set(r.template(s),a),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const a=n.get(r.messengerSession(s));return a?JSON.parse(a):null}catch{return null}},setSettings:(s,a)=>{try{delete a.auto_created_user;const i=JSON.stringify(a);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const a=JSON.stringify(s);n.set(r.anonUserSession(),a)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Br=(e,t,n={})=>{let r=null,s=null,a=null;const{leading:i=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(a===null||m-a>=t)i?(e(...d),a=m):(s=d,a=m);else if(s=d,l&&!r){const p=t-(m-a);r=setTimeout(()=>{s&&l&&(e(...s),a=Date.now()),r=null,s=null},p)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,a=null},c};class Ur{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",tt.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 s,a,i,l,c,d,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(s=this.filter)==null?void 0:s.aiAgentChannelFilter,aiAgentConversationStatusFilter:(a=this.filter)==null?void 0:a.aiAgentConversationStatusFilter,aiAgentIds:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.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=Br(p=>{this._query.belongsTo(p)?this._addChannelsToView([p],!1):this._removeChannelsFromView([p.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new tt.GroupChannelHandler({onChannelChanged:p=>{p.isGroupChannel()&&this._throttledOnChannelChanged(p)},onChannelDeleted:p=>{this._removeChannelsFromView([p])}}),this._connectionHandler=new Z.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 a,i;const n=new Set(((a=this.filter)==null?void 0:a.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let s;r?s=((i=r.lastMessage)==null?void 0:i.createdAt)??r.createdAt:s=this._query.lastResponseAt,this._timestamp>s&&(this._timestamp=s)}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,d)=>[c,d])),s=[],a=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const d=r.get(c.url);if(d===void 0)continue;const m=un(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),a.push(c)):s.push(c);const E=this._pinnedChannels.findIndex(x=>(r.get(x.url)??1/0)>d),v=E===-1?this._pinnedChannels.length:E;this._pinnedChannels.splice(v,0,c)}return{addedChannels:s,updatedChannels:a,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const r=[],s=[],a=[];for(const i of t){if(!this._query.belongsTo(i)){r.push(i.url);continue}const l=un(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=Eo(this._channels,i,this._order).place,p=m===this._channels.length;c?p?(n||!this.hasMore)&&(this._channels.push(i),s.push(i)):(this._channels.splice(m,0,i),s.push(i)):(this._channels.splice(m,0,i),a.push(i))}return{addedChannels:s,updatedChannels:a,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var p,E,v,x,b;const r=new Set(((p=this.filter)==null?void 0:p.pinnedChannelUrls)??[]),s=[],a=[];for(const g of t)r.has(g.url)?s.push(g):a.push(g);const i=this._upsertPinnedChannelsToArray(s),l=this._upsertRegularChannelsToArray(a,n),c=i.addedChannels.concat(l.addedChannels),d=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((v=(E=this._collectionEventHandler)==null?void 0:E.onChannelsAdded)==null||v.call(E,{},c)),d.length>0&&((b=(x=this._collectionEventHandler)==null?void 0:x.onChannelsUpdated)==null||b.call(x,{},d)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var s,a,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((i=(a=this._collectionEventHandler)==null?void 0:a.onChannelsDeleted)==null||i.call(a,{},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)),Eo=(e,t,n)=>{if(e.length>0){const r=un(e,t);let s=0,a=e.length-1,i=Math.floor((s+a)/2);for(;s<a;){const c=jn(e[i],t,n);if(c>0)a=i,i=Math.floor((s+a)/2);else if(c<0)s=i+1,i=Math.floor((s+a)/2);else return{place:i,oldPosition:r}}return{place:jn(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},jn=(e,t,n)=>{switch(n){case tt.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 Hr{constructor(t){C(this,"subscribers",{});this.logger=t}async send(t){const n=bo(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(a=>a(t.payload));await Promise.all(s).catch(a=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,a)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const bo=()=>{let e=Ce,t=Ce;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var ue=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e))(ue||{});class st{constructor(t={}){C(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Be={CloseConversation:e=>new _o(e),MessengerSettingsUpdated:e=>new Co(e),ActiveChannelUpdated:e=>new xo(e),AnonymousSessionTokenExpired:()=>new vo,AuthTokenRefreshed:()=>new yo};class _o extends st{constructor(){super(...arguments);C(this,"type","conv.close")}}class Co extends st{constructor(){super(...arguments);C(this,"type","messenger.settings.updated")}}class xo extends st{constructor(){super(...arguments);C(this,"type","active.channel.updated")}}class vo extends st{constructor(){super(...arguments);C(this,"type","anon.token.expired")}}class yo extends st{constructor(){super(...arguments);C(this,"type","auth.token.refreshed")}}var Sn=(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))(Sn||{});class Vr{constructor(t){C(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ke}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ke}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ke}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ke}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ke}/error]`,...t)}}class zr{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 dn{constructor(){C(this,"userId");C(this,"authToken");C(this,"sessionHandler")}}const So=e=>({onSessionTokenRequired:t=>{t(null),e.send(Be.AnonymousSessionTokenExpired())}}),Ao="ai_agent:stats",To="conversation_initial_render",Io=800220;var X=(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))(X||{});class wo{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??Io,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(Ao,t)):!1}}class ko extends wo{constructor(){super(...arguments);C(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return To}buildPayload(){const n=this.getDuration(X.AUTH),r=this.getDuration(X.GET_CHANNEL),s=this.getDuration(X.GET_MESSAGES),a=this.getDuration(X.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(X.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...s!==null&&{get_messages_duration:s},...a!==null&&{total_duration_from_cache:a}},c={key:this.getMetricKey(),value:i!==null?String(i):"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 Mo{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 ko().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(X.TOTAL_DURATION).startTimer(X.TOTAL_DURATION_FROM_CACHE).startTimer(X.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(X.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(X.AUTH).setError(t instanceof Z.SendbirdError?t.code:void 0,t.message).stopTimer(X.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(X.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(X.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(X.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(X.GET_CHANNEL).setError(t instanceof Z.SendbirdError?t.code:void 0,t.message).stopTimer(X.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Z.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(X.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Z.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(X.TOTAL_DURATION).stopTimer(X.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 $o(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const a=++t,l=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===a&&(e=null)});return e={key:r,id:a,promise:l},l};return n.isPending=()=>e!==null,n}const Ie={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}}},Yn=e=>{var t,n,r,s,a,i,l,c,d,m,p,E,v,x;return e?{...Ie,...e,conversation:{...Ie.conversation,...e==null?void 0:e.conversation,header:{...(t=Ie.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=Ie.conversation)==null?void 0:r.input,...(s=e==null?void 0:e.conversation)==null?void 0:s.input,camera:{...(i=(a=Ie.conversation)==null?void 0:a.input)==null?void 0:i.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(m=(d=Ie.conversation)==null?void 0:d.input)==null?void 0:m.gallery,...(E=(p=e==null?void 0:e.conversation)==null?void 0:p.input)==null?void 0:E.gallery}},fileViewer:{...(v=Ie.conversation)==null?void 0:v.fileViewer,...(x=e==null?void 0:e.conversation)==null?void 0:x.fileViewer}}}:Ie},de=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")},An=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 Ue(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function Lo(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!Ue(e):!1}function Ro(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Xn(e){return!!e&&e<Date.now()}function Oo(e){return!e.title}function Do(e,t){var n;if(e)return Oo(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 No{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=Br(s=>{var a,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:de(s)?"closed":"open",conversationStatus:(a=s.conversation)==null?void 0:a.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new tt.GroupChannelHandler({onChannelChanged:s=>{var a,i;s.isGroupChannel()&&s.url===((a=this._session)==null?void 0:a.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new Z.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,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:de(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(a){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",a)}});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 Po{constructor(t){C(this,"_sdkUser");C(this,"_userSession");C(this,"_dispatcher");C(this,"_activeChannel");C(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Be.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});C(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Be.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 Gr=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)}},ot=e=>JSON.parse(e),Ot=e=>JSON.parse(e);function Fo(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Bo(e){const t={};function n(r,s=""){for(const[a,i]of Object.entries(r)){const l=s?`${s}.${a}`:a;i&&typeof i=="object"&&!Array.isArray(i)?n(i,l):t[l]=i}}return n(e),t}function Tn({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[a,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${a}:${i}) must be a {string, number, or boolean}`);const l=r?r(i):String(i),c=n(a);return s.replace(c,Gr(l))},e)}async function Uo({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([a,i])=>{const l=await r(i);return{regex:n(a),transformedValue:l}}))).reduce((a,{regex:i,transformedValue:l})=>a.replace(i,Gr(l)),e)}var mn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(mn||{});const qr=e=>typeof e=="object"&&e!==null,Zn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Ho=e=>!qr(e)||!Zn(e,"channel_url")||!Zn(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Vo={1:Ho};function zo(e){if(!qr(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Vo[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Go(e,t,n,r){const s=ro.default.init({appId:e,modules:[new tt.GroupChannelModule,new ee.AIAgentModule],localCacheEnabled:!0,options:new Z.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:Z.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function qo(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 Wo=[400300,400301,400302,400310];class In{constructor(t,n,r){C(this,"chatSDK");C(this,"_logger");C(this,"_cache");C(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const a=new Z.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(a),this.chatSDK.aiAgent.addEventHandler(mn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),i=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",i);const l=zo(i);(l==null?void 0:l.category)===mn.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(a){const i=a;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(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",i.message,i.code),i}});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 s;if(t.userId===""){const a=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",a),a}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});C(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,a)=>{new Promise((i,l)=>t==null?void 0:t(i,l)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),a(i)})}});C(this,"_isCacheRestrictedError",t=>Wo.some(n=>t.code===n));C(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:a,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of a){const{key:c}=ot(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(a){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",a)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(qo(t.chatSDK),n=t.chatSDK):n=Go(t.appId,t.extensions,t.messengerVersion,t.chatParams),new In(n,t.logger,t.cache)}}const ft=new Map,Wr={set:(e,t)=>{ft.set(e,t)},get:e=>{if(ft.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=ft.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=ft.entries().next().value;return{platform:t[0],...t[1]}}},Ko=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class Jn extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`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=s}}var wn=(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))(wn||{}),kn=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(kn||{}),Kr=(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))(Kr||{});const jo=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Yo{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,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const a=await this._fetch(s,n);return r&&a.status===401?this._handleUnauthorized(a,s,n):this._toResult(a)});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 s=await this._parseErrorCode(t);if(!jo(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});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 Jn(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Jn(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 St{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 St({id:t.id,title:t.channelName??null,status:t.status2??wn.INITIALIZED,agent:(()=>{var a;const s=(a=t.recentAssignment)==null?void 0:a.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??kn.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class Mn{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 St._fromResponse(n,this)});C(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Ko({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 St._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Yo(t)}static init(t){return new Mn(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function Xo(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 Zo=1440*60*1e3;function Pe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Jo(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class At extends No{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",$o());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 i,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const s=this._getSessionCandidate(n),a=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;a!=null&&a.bot&&this._dispatcher.send(Be.MessengerSettingsUpdated({settings:a,source:"cache"}));try{const p=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=s.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=a==null?void 0:a.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let E;if(p.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),E={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:b,session_token:g,expire_at:_}=p.auto_created_user;this._cache.messenger.setAnonUser({userId:b,authToken:g,expireAt:_}),E={userId:b,authToken:g},this._logger.debug("AIAgent.authenticate: anonymous user created",b)}else E={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(E.userId,p),this._dispatcher.send(Be.MessengerSettingsUpdated({settings:p,source:"server"}));const v=(()=>{var b;return s.type==="anonymous"?So(this._dispatcher):(b=s.userSessionCandidate)==null?void 0:b.sessionHandler})(),x=await this._chatClient.connect(E,v,b=>{var g;this._logger.debug("AIAgent: session token refreshed"),(g=this._session)==null||g._updateAuthToken(b),this._deskClient.refreshDeskAuthToken(b)},()=>{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:b})=>{var g;if(b===Kr.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,2e3));const _=(g=this._session)==null?void 0:g.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(a==null?void 0:a.language)!==p.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Po({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=>{Pe(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});C(this,"searchConversation",async n=>{if(Pe(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}),s=[];for(;r.hasNext;){const a=await r.next();for(const i of a)Jo(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});C(this,"closeConversation",async n=>{var s;Pe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.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 Ur(this.chatSDK,n??{}));C(this,"patchContext",async(n,r)=>{Pe(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});C(this,"updateContext",async(n,r)=>{Pe(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});C(this,"getContextObject",async n=>{Pe(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});C(this,"refreshActiveChannel",async n=>{var i,l;Pe(this._session);const r=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:r});const s=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:this._session.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:r?(l=(i=this._cache.messenger.getSettings(this._session.userSession.userId))==null?void 0:i.active_channel)==null?void 0:l.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion}),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});C(this,"_getSessionCandidate",n=>n instanceof zr?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof dn?{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-Zo<=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 dn)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=Yn(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 Mo((r,s)=>this._chatClient.chatSDK.aiAgent.appendStat(r,s))}}static init(n){var p;const r=Wr.get(n.platform),s=n.logger??new Vr(n.logLevel??Sn.WARN),a=n.dispatcher??new Hr(s),i=n.useMMKVStorage?Xo(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=po({appId:n.appId,aiAgentId:n.aiAgentId,storage:i}),d=In.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:s,cache:c}),m=Mn.init({appId:n.appId,logger:s,customApiHost:(p=n.deskParams)==null?void 0:p.customApiHost});return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new At({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:m,cache:c,logger:s,dispatcher:a})}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=Yn(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=u.createContext(null),r=({children:i,value:l})=>o.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),s=({children:i})=>o.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),a=()=>{const i=u.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,a.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:a}};function pe(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:a}){const[i,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:i,updateTemplate:p=>l(()=>p),components:c,updateComponent:(p,E)=>d(v=>({...v,[p]:E}))};return o.createElement(t.Provider,{value:m},a)}function r({template:a,children:i}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{a&&l(a)},[a]),o.createElement(o.Fragment,null,i)}function s({children:a}){return o.createElement(n,null,a)}return s.defaults=e,s.useContext=()=>u.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(a=>{s[a]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(a,l)},[l]),null}}),s}function Qo(...e){return function({children:n}){return e.reduce((r,s)=>o.createElement(s,null,r),n)}}function ea(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 s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function ta(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),a=Fe.differenceInMinutes(r,s);return a<1?n.justNow:a<60?n.minutesAgo(a):Fe.isToday(s)?n.hoursAgo(Fe.differenceInHours(r,s)):t(s,n.dateShortFormat)}const na=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},pt=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Qn=(e,t)=>{const n=pt(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=na(e);return r?`#${pt(r[0])}${pt(r[1])}${pt(r[2])}${n}`:e},jr=te("AIAgent"),ra=jr.Provider,ce=jr.useContext;function sa(e){const t=oa(e);return o.createElement(ra,{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 oa(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=At.init(e);else{const s=aa(n.current,e);(s.appId||s.aiAgentId||s.chatSDK)&&(t.current.dispose(),t.current=At.init({...e,chatParams:s.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.useEffect(()=>()=>{var s;(s=t.current)==null||s.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r}function aa(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 ia=(e,t,n)=>Le.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),nt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Yr(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function la(e){const t=Yr(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function ca(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function ua(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),a=r-s;let i=0,l=0;const c=(r+s)/2;return r!==s&&(l=c>.5?a/(2-r-s):a/(r+s)),r===e?i=(t-n)/a+(t<n?6:0):r===t?i=(n-e)/a+2:r===n&&(i=(e-t)/a+4),i/=6,[i,l,c]}function da(e,t,n){let r,s,a;if(t===0)r=s=a=n;else{const i=function(m,p,E){return E<0&&(E+=1),E>1&&(E-=1),E<.16666666666666666?m+(p-m)*6*E:E<.5?p:E<.6666666666666666?m+(p-m)*(.6666666666666666-E)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=i(c,l,e+1/3),s=i(c,l,e),a=i(c,l,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(a*255)]}function Et(e,t,n){const[r,s,a]=la(e),[i,l,c]=ua(r,s,a),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[p,E,v]=da(i,m,d);return ca([Math.round(p),Math.round(E),Math.round(v)])}function ma(e,t="light"){return{extraDark:Et(e,.6,1.2),dark:Et(e,.85,1.1),main:e,light:Et(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Et(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function hn(e){const t=Yr(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,a=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+a*.114>n?nt.BLACK:nt.WHITE}function ha(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const ga=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400}}),bt={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)"}},Zt={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 er(e){const t=fa(e),{colors:n,aiAgentColorVariables:r}=pa(e,t),s=ba(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:s}}function fa({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===bt.primary.main?bt.primary:ma(n,e):bt.primary;return{...bt,primary:r,...t}}function pa({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const a=s.primary.main,i=t??hn(a),l=n??nt.DEFAULT_BOT_MSG_BG,c=r??hn(l);return{colors:(e==="light"?ha:ga)(s,a,i,l,c),aiAgentColorVariables:{primary_color:a,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function Ea(e,t,n){const r={...e};return n.forEach(s=>{const a=t[s];a!=null&&(r[s]=a)}),r}function ba({typography:e}){if(!e)return Zt;const t={...Zt};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Zt[n],a=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Ea(s,r,a)}}),t}const{Provider:_a,useContext:$n}=te("AIAgentTheme");function Ca({logger:e,palette:t,typography:n,appearance:r,children:s}){const a=u.useRef(null),[i,l]=u.useState(()=>er({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=u.useCallback((d,m)=>{m&&(a.current=m);const p=(r==null?void 0:r.theme)??d,E=a.current?a.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=er({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 u.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&c(i.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),o.createElement(_a,{value:{theme:i,updateTheme:c}},s)}const Jt=25*1024*1024,tr=1,nr=new Set(["image/png","image/jpeg","image/jpg"]),rr=new Set(["application/pdf"]),xa={off:"off",always:"always",handed_off_only:"handed_off_only"},va=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:tr,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Jt,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:nr,supportedFileMimeTypes:rr})),n=u.useCallback(({active_channel:s,upload_restriction:a})=>{t({maxAttachmentCount:(a==null?void 0:a.max_attachment_count)??tr,attachmentMode:xa[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(a==null?void 0:a.default_upload_size_limit)??Jt,uploadSizeLimitPerType:new Map(Object.entries((a==null?void 0:a.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((a==null?void 0:a.supported_image_mime_types)??nr),supportedFileMimeTypes:new Set((a==null?void 0:a.supported_file_mime_types)??rr)})},[]),r=u.useCallback(s=>{const{channel:a,uploadSizeLimit:i=Jt}=s,l=(d=!0)=>a!=null&&a.isAIAgent?d?Ue(a):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,p=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,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 Ue(a);default:return!0}},get supportedMimeTypes(){return l()?[ln]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:c,getUploadSizeLimitInMB:d=>c(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},sr=(...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)")},Ze=e=>({...e,context:e.context??{}}),{Provider:ya,useContext:at}=te("AIAgentMessengerSession"),Sa=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:a,logger:i}=ce(),{updateTheme:l}=$n(),[c,d]=u.useState(void 0),[m,p]=u.useState(void 0),[E,v]=u.useState(null),[x,b]=u.useState(null),[g,_]=u.useState(null),[y,I]=u.useState(null),{updateBaseAttachmentRules:A,createAttachmentRules:$}=va();u.useEffect(()=>{const T=r.onMessengerSettingsUpdated(({settings:z})=>{const{appearance:Y,bot:G,launcher:ye}=z;l(Y.selected_theme,Y),_({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}),I({type:ye.image_type||"default_icon",imageUrl:ye.image_url}),A(z)}),B=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&&b(G=>G?{...G,authToken:z}:null)});return()=>{T(),B(),N()}},[r,l,A]);const k=u.useCallback(async()=>{d(void 0);try{const T=await r.authenticate(e),B=r.session;return v(B.sdkUser),b(B.userSession),p(B.activeChannel),T}catch(T){throw d(T),T}},[r,e]),S=u.useCallback(async()=>{await r.deauthenticate(),v(null),p(void 0),b(null),_(null),I(null)},[r]),R=u.useCallback(async()=>{if(!r.session)throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready");return p(void 0),await r.refreshActiveChannel()},[r,i]),P=u.useCallback(async T=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(T)},[r]),O=u.useCallback(async T=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(T)},[r]);return u.useImperativeHandle(n,()=>{const T=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:k,deauthenticate:S,updateContext:async(...B)=>{const N=sr(...B);if(N.type==="active"){const G=await(await T()).updateContext(a,N.context);return Ze(G)}const z=await s.aiAgent.updateContext(N.aiAgentId,N.channelUrl,N.context);return Ze(z)},patchContext:async(...B)=>{const N=sr(...B);if(N.type==="active"){const G=await(await T()).patchContext(a,N.context);return Ze(G)}const z=await s.aiAgent.patchContext(N.aiAgentId,N.channelUrl,N.context);return Ze(z)},getContextObject:async()=>{const N=await(await T()).getContextObject(a);return Ze(N)}}},[k,S,m,s,a,i]),o.createElement(ya,{value:{sdkUser:E,userSessionInfo:e,userSession:x,activeChannel:m,setActiveChannel:p,refreshActiveChannel:R,createConversation:P,searchConversation:O,connectionError:c,aiAgentInfo:g,launcherInfo:y,authenticate:k,deauthenticate:S,createAttachmentRules:$,statsTrackers:r.statsTrackers}},t)}),Ln=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useEffect(()=>{const s=new Z.ConnectionHandler({onDisconnected:a=>{var i,l;return(l=(i=r.current).onDisconnected)==null?void 0:l.call(i,a)},onConnected:a=>{var i,l;return(l=(i=r.current).onConnected)==null?void 0:l.call(i,a)},onReconnectStarted:()=>{var a,i;return(i=(a=r.current).onReconnectStarted)==null?void 0:i.call(a)},onReconnectSucceeded:()=>{var a,i;return(i=(a=r.current).onReconnectSucceeded)==null?void 0:i.call(a)},onReconnectFailed:()=>{var a,i;return(i=(a=r.current).onReconnectFailed)==null?void 0:i.call(a)},onConnectionLost:()=>{var a,i;return(i=(a=r.current).onConnectionLost)==null?void 0:i.call(a)},onConnectionDelayed:a=>{var i,l;return(l=(i=r.current).onConnectionDelayed)==null?void 0:l.call(i,a)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])};function Aa(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:s}=ce(),{sdkUser:a,statsTrackers:i}=at(),l=Le.useForceUpdate(),[c,d]=u.useState(void 0),[m,p]=u.useState(void 0),[E,v]=u.useState(!1);function x(g){g.isAIAgent&&!g.conversation&&(v(!0),s.initConversationIfNeeded(g).finally(()=>v(!1)))}async function b(){var g,_,y;if(!a){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),p(void 0),v(!1),e){i.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const I=await t.groupChannel.getChannel(e);x(I),d(I),i.initialRender.onGetChannelComplete((g=I.conversation)==null?void 0:g.id),I.url===((_=s.session)==null?void 0:_.activeChannel.url)&&s.session._updateActiveChannel({url:I.url,status:de(I)?"closed":"open",conversationStatus:(y=I.conversation)==null?void 0:y.status}),n.debug("useChannel.getChannel: fetched channel",I)}catch(I){i.initialRender.onGetChannelError(I),I instanceof Z.SendbirdError&&p(I),n.error("useChannel.getChannel: error",I)}}}return u.useEffect(()=>{b()},[t,a,e,r]),Ln(t,{async onReconnectSucceeded(){if(!c)return;const g=await c.refresh();x(g),d(g)}}),Le.useGroupChannelHandler(t,{onChannelChanged:g=>{g.isGroupChannel()&&g.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",g.url),d(g),l())}}),{channel:c,channelFetchError:m,getChannel:b,isInitializingConversation:E}}const Ta=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload;return n==null?void 0:n.user_input_disabled_by},Ia=e=>{var i;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,s=!!r&&!r.submitted_at&&!r.canceled_at,a=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return s&&!a},wa=()=>{const{chatSDK:e,networkStateAdapter:t}=ce(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Ln(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),u.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(a=>a==="reconnecting"&&e.connectionState===Z.ConnectionState.OPEN?"connected":a)})},[t,e]),n},ka=3e4,Ma=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,a]=u.useState(!1),i=u.useRef(null),l=t&&rt(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),a(!1)},d=E=>{i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},E)},m=Date.now()-l,p=ka-m;return n||p<=0?c():d(p),()=>{i.current&&clearTimeout(i.current)}},[n,l]),s&&e},Xr=e=>{const{chatSDK:t}=ce(),[n,r]=u.useState([]);return Le.useGroupChannelHandler(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const a=s.getTypingUsers();r(a)}}}),n},$a=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,a]=u.useState(!1),i=Xr(e);return u.useEffect(()=>{if(!t)return;const l=i.some(d=>d.userId===n),c=rt(t,n)&&(Me.isStreaming(t)||r);a(c||l)},[i,t,n,r]),s},La=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:a}=at(),i=wa(),l=$a({channel:e,lastMessage:Kn(t,[ke.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),c=Ma({shouldApply:!!(e!=null&&e.isAIAgent)&&!Ue(e),isBlockedWhileAIResponding:l,lastMessage:Kn(t,[ke.SendingStatus.PENDING,ke.SendingStatus.SUCCEEDED]),currentUserId:(a==null?void 0:a.userId)??""});if(!e||i==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(i==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(de(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Lo(e))return{disabled:!0,disabledBy:"handoff_pending"};if(Ia(e))return{disabled:!0,disabledBy:"form_active"};const d=Ta(e);return d?{disabled:!0,disabledBy:d}:l||c||r?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},Ra=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(s=>{t(a=>{if(a.has(s))return a;const i=new Set(a);return i.add(s),i})},[]),r=u.useCallback(s=>{t(a=>{if(!a.has(s))return a;const i=new Set(a);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Oa}=te("AIAgentConversation");function Da({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:a,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Ce,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:p}){var O;const E=()=>d&&(g==null?void 0:g.markAsRead()),{chatSDK:v,logger:x,dispatcher:b}=ce(),{channel:g,channelFetchError:_,getChannel:y,isInitializingConversation:I}=Aa(t),{statsTrackers:A}=at();u.useEffect(()=>{if(t)return A.initialRender.setChannelUrl(t),()=>{A.initialRender.cleanup()}},[t,A]);const $=ia(v,g,{replyType:ke.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:T=>r==null?void 0:r(T),onMessagesUpdated:T=>s==null?void 0:s(T),onCacheResult:T=>A.initialRender.onCacheResult(T),onApiResult:T=>A.initialRender.onApiResult(T),logger:x,markAsRead:E,sortComparator:p}),k=Ra(),S=La({channel:g,messages:$.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:I});u.useEffect(()=>{E()},[d,g]);const R=de(g);u.useEffect(()=>{a==null||a(R)},[R,a]),u.useEffect(()=>{const T=async B=>{const N=typeof(B==null?void 0:B.channelUrl)=="string";g&&N&&B.channelUrl!==g.url||(x.debug("conversation.dispatcher: try to close conversation",g),g!=null&&g.conversation&&g.conversation.status===ee.ConversationStatus.OPEN&&(await g.closeConversation(),i==null||i()))};return b.subscribe(ue.ConversationClose,T),()=>{b.unsubscribe(ue.ConversationClose,T)}},[b,g,x,(O=g==null?void 0:g.conversation)==null?void 0:O.status,i]);const P={conversation:(g==null?void 0:g.conversation)??void 0,channelSource:{channel:g,error:_,refetch:()=>y(),closeConversation:async()=>{de(g)||await(g==null?void 0:g.closeConversation())}},messageSource:{messages:$.messages,newMessages:$.newMessages,initialized:$.initialized,loadPrevious:()=>$.loadPrevious(),loadNext:()=>$.loadNext(),deleteMessage:T=>$.deleteMessage(T),resendMessage:T=>$.resendMessage(T),resetNewMessages:()=>$.resetNewMessages(),sendUserMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendUserMessage(T,c);return c==null||c(B),B},sendFileMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendFileMessage(T,c);return c==null||c(B),B},sendMultipleFilesMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendMultipleFilesMessage(T,c);return c==null||c(B),B}},state:{streamAnimation:k,input:S}};return o.createElement(Oa,{value:P},e)}function Na(e,t){var v,x,b,g,_,y,I,A,$,k;const[n,r]=u.useState(!1),[s,a]=u.useState(null),[i,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),p=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),a(null),l([]);try{c==null||c.dispose();const S=new Ur(e,t);S.setConversationListCollectionHandler({onChannelsAdded:()=>{l(S.channels)},onChannelsUpdated:()=>{l(S.channels)},onChannelsDeleted:()=>{l(S.channels)}}),await S.loadMore(),d(S),a(null)}catch(S){d(null),a(S)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(v=t.filter)==null?void 0:v.aiAgentChannelFilter,(b=(x=t.filter)==null?void 0:x.aiAgentConversationStatusFilter)==null?void 0:b.join(),(_=(g=t.filter)==null?void 0:g.aiAgentIds)==null?void 0:_.join(),(y=t.filter)==null?void 0:y.deskChannelFilter,(A=(I=t.filter)==null?void 0:I.pinnedChannelUrls)==null?void 0:A.join(),($=t.filter)==null?void 0:$.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),E=u.useCallback(async()=>{if(c)try{await c.loadMore()}catch(S){a(S)}},[c]);return Ln(e,{onConnected:()=>p()}),u.useEffect(()=>{p()},[p]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:s,channels:i,loadMore:E}}const{Provider:Pa}=te("AIAgentConversationList");function Fa({conversationListLimit:e,conversationListFilter:t,children:n}){var p,E;const{chatSDK:r,aiAgentId:s,queryParams:a}=ce(),i={aiAgentIds:[s],aiAgentConversationStatusFilter:[ee.ConversationStatus.CLOSED,ee.ConversationStatus.OPEN]},l=e??((p=a==null?void 0:a.conversationListParams)==null?void 0:p.limit),c={...i,...(E=a==null?void 0:a.conversationListParams)==null?void 0:E.filter,...t},d=Na(r,{limit:l,filter:c}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return o.createElement(Pa,{value:m},n)}function Ba(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:Ua,useContext:Zr}=te("MessageTemplateFetching");function Ha({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[s,a]=u.useState({}),i=u.useCallback((d,m)=>{a(p=>({...p,[d]:{fetching:!1,error:!1,...p[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:p,suspense:E=!1})=>{const v=m(p);if(v)return v;const x=r.current[p];if(x)return x;E||i(p,{fetching:!0});const b=d(p).catch(g=>{throw E||i(p,{error:!0}),g}).finally(()=>{E||i(p,{fetching:!1}),delete r.current[p]});return r.current[p]=b,b},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const p=Ba(m());return n.current[d]=p,p},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return o.createElement(Ua,{value:c},e)}const Dt={VARIABLE:e=>new RegExp(`\\{${e}\\}`,"g"),VIEW_VARIABLE:e=>new RegExp(`"{@${e}}"`,"g")};function Re({uiTemplateString:e,variables:t={}}){const n=Bo(t);return Tn({template:e,variables:n,variableKeyPattern:r=>Dt.VARIABLE(r)})}function Oe({theme:e,uiTemplateString:t,colorVariables:n={}}){return Tn({template:t,variables:n,variableKeyPattern:r=>Dt.VARIABLE(r),variableValueTransformer:r=>Fo(e,r)})}function Va({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:s,onRequestTemplate:a}){const l=Object.values(n).flat().map(d=>d.key);return[...new Set(l)].some(d=>!a(d))?null:Tn({template:t,variables:n,variableKeyPattern:d=>Dt.VIEW_VARIABLE(d),variableValueTransformer:d=>{const m=d.map(({key:p,variables:E})=>{const v=a(p),{ui_template:x,color_variables:b}=ot(v);let g=JSON.stringify(x);return g=Re({uiTemplateString:g,variables:s}),g=Oe({theme:e,uiTemplateString:g,colorVariables:b}),g=Oe({theme:e,uiTemplateString:g,colorVariables:r}),g=Re({uiTemplateString:g,variables:E}),Ot(g)});return JSON.stringify(m)}})}async function za({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:s,onRequestTemplate:a}){return Uo({template:t,variables:n,variableKeyPattern:i=>Dt.VIEW_VARIABLE(i),variableValueTransformer:async i=>{const l=i.map(async({key:d,variables:m})=>{const p=await a(d),{ui_template:E,color_variables:v}=ot(p);let x=JSON.stringify(E);return x=Re({uiTemplateString:x,variables:s}),x=Oe({theme:e,uiTemplateString:x,colorVariables:v}),x=Oe({theme:e,uiTemplateString:x,colorVariables:r}),x=Re({uiTemplateString:x,variables:m}),Ot(x)}),c=await Promise.all(l);return JSON.stringify(c)}})}const Ga=({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:s,color_variables:a}=ot(e);let i=JSON.stringify(s);if(Object.keys(r.viewVariables??{}).length>0){const c=Va({...r,uiTemplateString:i,aiAgentColorVariables:t,internalVariables:n});if(c===null)return null;i=c}return i=Re({...r,uiTemplateString:i,variables:n}),i=Oe({...r,uiTemplateString:i,colorVariables:a}),i=Oe({...r,uiTemplateString:i,colorVariables:t}),i=Re({...r,uiTemplateString:i}),Ot(i)},qa=async({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:s,color_variables:a}=ot(e);let i=JSON.stringify(s);return Object.keys(r.viewVariables??{}).length>0&&(i=await za({...r,uiTemplateString:i,aiAgentColorVariables:t,internalVariables:n})),i=Re({...r,uiTemplateString:i,variables:n}),i=Oe({...r,uiTemplateString:i,colorVariables:a}),i=Oe({...r,uiTemplateString:i,colorVariables:t}),i=Re({...r,uiTemplateString:i}),Ot(i)},Wa=e=>{const{aiAgentColorVariables:t={}}=e,{internalVariables:n}=Zr();return u.useState(()=>{const r=e.onGetCachedTemplate(e.templateKey);return r?Ga({...e,rawTemplate:r,aiAgentColorVariables:t,internalVariables:n,onRequestTemplate:e.onGetCachedTemplate}):null})},Ka=e=>{const[t]=Wa(e);if(t)return t;const{aiAgentColorVariables:n={}}=e,{internalVariables:r,fetchTemplate:s,suspend:a}=Zr();return a(e.templateKey,async()=>{const l=await s({...e,suspense:!0});return await qa({...e,rawTemplate:l,aiAgentColorVariables:n,internalVariables:r})}).value},ja="remove_powered_by",Rn=(e,t)=>{var s,a;const{chatSDK:n}=ce(),{aiAgentInfo:r}=at();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&An(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(a=n==null?void 0:n.appInfo)==null?void 0:a.applicationAttributes;return u.useMemo(()=>!(Array.isArray(i)&&i.includes(ja)),[i])}throw new Error("Unsupported feature")},Ya={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"},Xa={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Za={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Ja={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}}},Qa={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:a}=e;if(a){if(a.min_select!==void 0&&r.length<a.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(a.min_select):n.minSelect};if(a.max_select!==void 0&&r.length>a.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(a.max_select):n.maxSelect}}return{isValid:!0}}},ei={text:Xa,number:Za,"single-select":Ja,"multi-select":Qa},ti={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Jr(e){return ei[e.type]||ti}function or(e){return Jr(e).getValueOrDefault(e)}function ni(e,t,n={}){const r={...Ya,...n};return Jr(e).validate(e,t,r)}const ri=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[a,i]=u.useState({}),[l,c]=u.useState(()=>{const b={};return e.fields.forEach(g=>{b[g.key]=or(g)}),b}),d=u.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);u.useEffect(()=>{if(d==="submitted"||d==="canceled"){const b={};let g=!1;e.fields.forEach(_=>{const y=or(_);JSON.stringify(l[_.key])!==JSON.stringify(y)&&(g=!0),b[_.key]=y}),g&&c(b)}},[d]);const m=(b,g)=>{c(_=>({..._,[b]:g})),i(_=>({..._,[b]:void 0}))},p=e.fields.map(b=>{var y,I,A;const g=l[b.key]??null,_={key:b.key,label:b.label,error:a[b.key],required:b.required};return b.type==="text"?{..._,type:"text",layout:b.layout,value:g,...b.placeholder&&{placeholder:b.placeholder},...((y=b.rules)==null?void 0:y.max_length)&&{maxLength:b.rules.max_length}}:b.type==="number"?{..._,type:"number",layout:b.layout,value:g,...b.placeholder&&{placeholder:b.placeholder},...((I=b.rules)==null?void 0:I.max)&&{max:b.rules.max}}:b.type==="single-select"?{..._,type:"single-select",layout:b.layout,value:g,options:b.options}:b.type==="multi-select"?{..._,type:"multi-select",layout:b.layout,value:g,options:b.options,...((A=b.rules)==null?void 0:A.max_select)&&{maxSelect:b.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:p,getField:b=>p.find(g=>g.key===b),updateFieldValue:m,submit:async()=>{const b={};let g=!1;for(const _ of e.fields){const y=l[_.key]??null,I=ni(_,y,n);I.isValid||(b[_.key]=I.error,g=!0)}if(i(b),!g&&r){const _={};e.fields.forEach(y=>{_[y.key]=l[y.key]??null}),await r(_)}},cancel:async()=>{await(s==null?void 0:s())}}},si=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},oi=e=>{const{aiAgentInfo:t}=at(),r=Xr(e)[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),a=s?si(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:a}},Qr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[a]=e.members.filter(i=>i.userId!==t.userId);return a})(),s={ai(a){return{fallbackIcon:a,url:n.profileUrl,title:n.nickname}},human(a){return{fallbackIcon:a,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(a){return{fallbackIcon:a,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?Ue(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},ar=e=>u.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 ai=new Set(["free_text","single_choice"]),ii=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[a,i]=ar({csatType:t,csat:n,csatReason:r,isResolved:s}),[l,c]=ar({followUpItem:!1}),d=u.useMemo(()=>{var g;const v=a.csat,x=typeof v=="number",b=(g=e.follow_up)==null?void 0:g.find(_=>x?_.scores.includes(v):_.always_visible??!1);if(ai.has(b==null?void 0:b.response_type))return b},[a.csat,e.follow_up]),m=(()=>{var v;if(typeof n=="number")return"submitted";if((t===he.AI_AGENT_CSAT_5||t===he.HELPDESK_CSAT_5)&&typeof a.csat=="number")return"submittable";if(t===he.AI_AGENT_CSAT_5_WITH_CRE){const x=typeof a.csat=="number",b=!((v=e.cre)!=null&&v.required)||typeof a.isResolved=="boolean";if(x&&b)return"submittable"}return"unsubmittable"})(),p=u.useCallback(()=>typeof a.csat>"u"?!1:d!=null&&d.required&&!a.csatReason?(c({followUpItem:!0}),!1):!0,[a,d,c]);return u.useEffect(()=>{r||(i({csatReason:""}),c({followUpItem:!1}))},[r,d,i,c]),{params:a,setParams:i,error:l,setError:c,followUpItem:d,state:m,validateParams:p,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Qt=5,li=250,ci=50,ir=e=>Math.max(0,e-ci),ui=e=>e<1e3?{speed:Qt*.5,chunkSize:2}:e<2e3?{speed:Qt*.8,chunkSize:2}:{speed:Qt*.6,chunkSize:3},di=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:s,onAnimationComplete:a}=e,[i,l]=u.useState(()=>ir(t.length)),c=u.useRef(null),d=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=u.useRef({onStart:r,onProgress:s,onComplete:a}).current,p=u.useRef({startCalled:!1,completeCalled:!1}).current,E=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,v=n,x=i<t.length,b=E.initialEnabled&&(v||x);return u.useLayoutEffect(()=>{m.onStart=r,m.onProgress=s,m.onComplete=a,E.textLength=t.length,E.enabled=n}),u.useLayoutEffect(()=>{var g;E.initialEnabled&&(p.startCalled||(p.startCalled=!0,(g=m.onStart)==null||g.call(m)),l(_=>t.length<_?t.length:_))},[t]),u.useEffect(()=>{if(!E.initialEnabled)return;let g=ir(t.length);d.lastUpdate=0,d.startTime=0,d.lastProgressCall=0;const _=y=>{var O;d.lastUpdate===0&&(d.lastUpdate=y,d.startTime=y,d.lastProgressCall=y);const I=E.textLength,A=y-d.lastUpdate,$=y-d.startTime,{speed:k,chunkSize:S}=ui($),R=k*S;A>=R&&g<I&&(g=Math.min(g+S,I),l(g),d.lastUpdate=y),y-d.lastProgressCall>=li&&(d.lastProgressCall=y,(O=m.onProgress)==null||O.call(m)),(g<I||E.enabled)&&(c.current=requestAnimationFrame(_))};return c.current=requestAnimationFrame(_),()=>{var y;c.current&&cancelAnimationFrame(c.current),p.startCalled&&!p.completeCalled&&(p.completeCalled=!0,(y=m.onComplete)==null||y.call(m))}},[]),u.useEffect(()=>{var I;const g=E.initialEnabled&&p.startCalled,_=!n,y=i>=t.length&&t.length>0;g&&_&&y&&!p.completeCalled&&(p.completeCalled=!0,(I=m.onComplete)==null||I.call(m))},[n,i,t.length]),{streamText:E.initialEnabled?t.slice(0,i):t,isAnimating:b}},mi="1.21.1",le="sb-agent",me={ENTRY:`${le}-entry`,MODAL_ROOT:`${le}-modal-root`,WINDOW:`${le}-window`,LAUNCHER:`${le}-launcher`},_t=2147483647,Ve={MODAL:_t-1,TOOLTIP:_t-2,WINDOW:_t-3,LAUNCHER:_t-4},es=36,hi=100,gi=mi,On="noopener noreferrer nofollow";function fi(){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 Ct={};function pi(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Ct[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Ct[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Ct[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(Ct).filter(t=>t.startsWith(e))}}}}const Ei='@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}',bi={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",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"}},gn={language:"en",strings:bi,dateLocale:Xs.enUS},ts=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,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}),_i=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Nt},Nt="en",Ci=new Set([Nt,"ko","es","pt","fr","hi","it","de","tr","ja"]),xi=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},lr=ts(gn.strings),vi={...lr,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:lr.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"},Tt={language:gn.language,dateLocale:gn.dateLocale,stringSet:vi},yi=Object.freeze(Object.defineProperty({__proto__:null,default:Tt},Symbol.toStringTag,{value:"Module"})),fn=new Map([[Nt,Tt]]);async function Si(e){const t=fn.get(e);if(t)return t;try{if(Ci.has(e)){const{default:n}=await xi(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/DbxUqtQc.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>yi),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/DTCJ6-eC.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/7UVs65zS.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/DfRVurNO.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/JLk8Bvao.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/BRnfdIkb.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMS5Zb7W.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/Dl0262MS.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DFmkiYPE.cjs"))}),`./languages/${e}.ts`,3);return fn.set(e,n),n}return Tt}catch{return Tt}}const{Provider:Ai,useContext:K}=te("Localization"),Ti=({language:e=navigator.language,logger:t,stringSet:n,children:r})=>{const[s,a]=u.useState(fn.get(Nt));return u.useEffect(()=>{const i=_i(e);s.language!==i&&(t==null||t.debug("localization.useEffect: update language",{from:s.language,to:i}),Si(i).then(a))},[e,t]),o.createElement(Ai,{value:{language:s.language,stringSet:{...s.stringSet,...n},dateLocale:s.dateLocale,format:(i,l,c)=>Fe.format(i,l,{locale:s.dateLocale,...c})}},r)},It="data-sb-agent-theme",cr=e=>(t,...n)=>{let r="";return t.forEach((s,a)=>{r+=s+(n[a]??"")}),`[${It}='${e}'] & { ${r} }`},F={light:cr("light"),dark:cr("dark")},Ii=w.css(({theme:e})=>{const{palette:t}=e;return`
|
|
1
|
+
"use strict";var js=Object.defineProperty;var Ys=(e,t,n)=>t in e?js(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var C=(e,t,n)=>Ys(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Z=require("@sendbird/chat"),u=require("react"),w=require("styled-components"),Fe=require("date-fns"),Xs=require("date-fns/locale/en-US"),ee=require("@sendbird/chat/aiAgent"),ke=require("@sendbird/chat/message"),tt=require("@sendbird/chat/groupChannel"),Le=require("@sendbird/uikit-tools"),Zs=require("react-dom"),Js=require("date-fns/isSameDay"),an=require("@sendbird/react-uikit-message-template-view"),Qs=require("@sendbird/uikit-message-template"),eo=require("dompurify"),to=require("@emotion/is-prop-valid"),Rt=e=>e&&e.__esModule?e:{default:e};function no(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 ro=Rt(Z),o=no(u),h=Rt(w),Dr=Rt(eo),so=Rt(to),Ke="sb-agent",Nr="KEY_IMG_ASPECT_RATIO",ln="*/*",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},fe=e=>!!e&&"sender"in e,oo=e=>fe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),ao=(e,t,n,r=!0)=>{if(!r||!fe(e))return"single";const s=()=>{if(!t||!fe(t))return!1;const c=t.sender.userId===e.sender.userId,d=Fe.isSameMinute(t.createdAt,e.createdAt);return c&&d},a=()=>{if(!n||!fe(n))return!1;const c=n.sender.userId===e.sender.userId,d=Fe.isSameMinute(n.createdAt,e.createdAt);return c&&d},i=s(),l=a();return i&&l?"middle":i?"bottom":l?"top":"single"},rt=(e,t)=>(()=>{var r;return fe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,We={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>fe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>fe(e)&&(e.sender.userId===t||e.sendingStatus===ke.SendingStatus.PENDING)},we=e=>e.startsWith("image/"),Pr=e=>e.startsWith("video/"),vn=(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"},Fr=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},yn=e=>{switch(e){case"top":case"middle":return H.GAP_GROUPED;default:return H.GAP_UNGROUPED}},io=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(a,...i)=>{const[l,c,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),s=d+a.length,a}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(a=>a.type!=="text"?a:{...a,value:t(a.value)}):r},lo=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),co=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),uo=e=>e.replace(/~~/g,"\\~\\~"),mo=e=>{let t=e;return t=lo(t),t=co(t),t=uo(t),t},ho=typeof navigator<"u"&&navigator.product==="ReactNative",Kn=(e,t)=>{const n=r=>!t||t.length===0?!0:fe(r)&&t.includes(r.sendingStatus);return ho?e.find(n):e.findLast(n)};function Ce(){}function go(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function fo(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 cn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Me={isStreaming(e){const t=cn(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(rt(e,t)){const r=cn(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)}},Xt=`@${Ke}`,po=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Xt}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const a=fo(`${e}/${t}/${s}`);return`${Xt}-udata/${a}`},anonUserSession:()=>`${Xt}-session/${e}/${t}`};return{template:{set:(s,a)=>n.set(r.template(s),a),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const a=n.get(r.messengerSession(s));return a?JSON.parse(a):null}catch{return null}},setSettings:(s,a)=>{try{delete a.auto_created_user;const i=JSON.stringify(a);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const a=JSON.stringify(s);n.set(r.anonUserSession(),a)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Br=(e,t,n={})=>{let r=null,s=null,a=null;const{leading:i=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(a===null||m-a>=t)i?(e(...d),a=m):(s=d,a=m);else if(s=d,l&&!r){const p=t-(m-a);r=setTimeout(()=>{s&&l&&(e(...s),a=Date.now()),r=null,s=null},p)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,a=null},c};class Ur{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",tt.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 s,a,i,l,c,d,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(s=this.filter)==null?void 0:s.aiAgentChannelFilter,aiAgentConversationStatusFilter:(a=this.filter)==null?void 0:a.aiAgentConversationStatusFilter,aiAgentIds:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.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=Br(p=>{this._query.belongsTo(p)?this._addChannelsToView([p],!1):this._removeChannelsFromView([p.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new tt.GroupChannelHandler({onChannelChanged:p=>{p.isGroupChannel()&&this._throttledOnChannelChanged(p)},onChannelDeleted:p=>{this._removeChannelsFromView([p])}}),this._connectionHandler=new Z.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 a,i;const n=new Set(((a=this.filter)==null?void 0:a.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let s;r?s=((i=r.lastMessage)==null?void 0:i.createdAt)??r.createdAt:s=this._query.lastResponseAt,this._timestamp>s&&(this._timestamp=s)}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,d)=>[c,d])),s=[],a=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const d=r.get(c.url);if(d===void 0)continue;const m=un(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),a.push(c)):s.push(c);const E=this._pinnedChannels.findIndex(x=>(r.get(x.url)??1/0)>d),v=E===-1?this._pinnedChannels.length:E;this._pinnedChannels.splice(v,0,c)}return{addedChannels:s,updatedChannels:a,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const r=[],s=[],a=[];for(const i of t){if(!this._query.belongsTo(i)){r.push(i.url);continue}const l=un(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=Eo(this._channels,i,this._order).place,p=m===this._channels.length;c?p?(n||!this.hasMore)&&(this._channels.push(i),s.push(i)):(this._channels.splice(m,0,i),s.push(i)):(this._channels.splice(m,0,i),a.push(i))}return{addedChannels:s,updatedChannels:a,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var p,E,v,x,b;const r=new Set(((p=this.filter)==null?void 0:p.pinnedChannelUrls)??[]),s=[],a=[];for(const g of t)r.has(g.url)?s.push(g):a.push(g);const i=this._upsertPinnedChannelsToArray(s),l=this._upsertRegularChannelsToArray(a,n),c=i.addedChannels.concat(l.addedChannels),d=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((v=(E=this._collectionEventHandler)==null?void 0:E.onChannelsAdded)==null||v.call(E,{},c)),d.length>0&&((b=(x=this._collectionEventHandler)==null?void 0:x.onChannelsUpdated)==null||b.call(x,{},d)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var s,a,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((i=(a=this._collectionEventHandler)==null?void 0:a.onChannelsDeleted)==null||i.call(a,{},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)),Eo=(e,t,n)=>{if(e.length>0){const r=un(e,t);let s=0,a=e.length-1,i=Math.floor((s+a)/2);for(;s<a;){const c=jn(e[i],t,n);if(c>0)a=i,i=Math.floor((s+a)/2);else if(c<0)s=i+1,i=Math.floor((s+a)/2);else return{place:i,oldPosition:r}}return{place:jn(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},jn=(e,t,n)=>{switch(n){case tt.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 Hr{constructor(t){C(this,"subscribers",{});this.logger=t}async send(t){const n=bo(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(a=>a(t.payload));await Promise.all(s).catch(a=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,a)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const bo=()=>{let e=Ce,t=Ce;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var ue=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e))(ue||{});class st{constructor(t={}){C(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Be={CloseConversation:e=>new _o(e),MessengerSettingsUpdated:e=>new Co(e),ActiveChannelUpdated:e=>new xo(e),AnonymousSessionTokenExpired:()=>new vo,AuthTokenRefreshed:()=>new yo};class _o extends st{constructor(){super(...arguments);C(this,"type","conv.close")}}class Co extends st{constructor(){super(...arguments);C(this,"type","messenger.settings.updated")}}class xo extends st{constructor(){super(...arguments);C(this,"type","active.channel.updated")}}class vo extends st{constructor(){super(...arguments);C(this,"type","anon.token.expired")}}class yo extends st{constructor(){super(...arguments);C(this,"type","auth.token.refreshed")}}var Sn=(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))(Sn||{});class Vr{constructor(t){C(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ke}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ke}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ke}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ke}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ke}/error]`,...t)}}class zr{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 dn{constructor(){C(this,"userId");C(this,"authToken");C(this,"sessionHandler")}}const So=e=>({onSessionTokenRequired:t=>{t(null),e.send(Be.AnonymousSessionTokenExpired())}}),Ao="ai_agent:stats",To="conversation_initial_render",Io=800220;var X=(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))(X||{});class wo{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??Io,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(Ao,t)):!1}}class ko extends wo{constructor(){super(...arguments);C(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return To}buildPayload(){const n=this.getDuration(X.AUTH),r=this.getDuration(X.GET_CHANNEL),s=this.getDuration(X.GET_MESSAGES),a=this.getDuration(X.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(X.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...s!==null&&{get_messages_duration:s},...a!==null&&{total_duration_from_cache:a}},c={key:this.getMetricKey(),value:i!==null?String(i):"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 Mo{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 ko().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(X.TOTAL_DURATION).startTimer(X.TOTAL_DURATION_FROM_CACHE).startTimer(X.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(X.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(X.AUTH).setError(t instanceof Z.SendbirdError?t.code:void 0,t.message).stopTimer(X.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(X.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(X.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(X.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(X.GET_CHANNEL).setError(t instanceof Z.SendbirdError?t.code:void 0,t.message).stopTimer(X.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Z.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(X.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Z.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(X.TOTAL_DURATION).stopTimer(X.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 $o(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const a=++t,l=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===a&&(e=null)});return e={key:r,id:a,promise:l},l};return n.isPending=()=>e!==null,n}const Ie={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}}},Yn=e=>{var t,n,r,s,a,i,l,c,d,m,p,E,v,x;return e?{...Ie,...e,conversation:{...Ie.conversation,...e==null?void 0:e.conversation,header:{...(t=Ie.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=Ie.conversation)==null?void 0:r.input,...(s=e==null?void 0:e.conversation)==null?void 0:s.input,camera:{...(i=(a=Ie.conversation)==null?void 0:a.input)==null?void 0:i.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(m=(d=Ie.conversation)==null?void 0:d.input)==null?void 0:m.gallery,...(E=(p=e==null?void 0:e.conversation)==null?void 0:p.input)==null?void 0:E.gallery}},fileViewer:{...(v=Ie.conversation)==null?void 0:v.fileViewer,...(x=e==null?void 0:e.conversation)==null?void 0:x.fileViewer}}}:Ie},de=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")},An=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 Ue(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function Lo(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!Ue(e):!1}function Ro(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Xn(e){return!!e&&e<Date.now()}function Oo(e){return!e.title}function Do(e,t){var n;if(e)return Oo(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 No{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=Br(s=>{var a,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:de(s)?"closed":"open",conversationStatus:(a=s.conversation)==null?void 0:a.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new tt.GroupChannelHandler({onChannelChanged:s=>{var a,i;s.isGroupChannel()&&s.url===((a=this._session)==null?void 0:a.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new Z.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,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:de(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(a){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",a)}});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 Po{constructor(t){C(this,"_sdkUser");C(this,"_userSession");C(this,"_dispatcher");C(this,"_activeChannel");C(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Be.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});C(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Be.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 Gr=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)}},ot=e=>JSON.parse(e),Ot=e=>JSON.parse(e);function Fo(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Bo(e){const t={};function n(r,s=""){for(const[a,i]of Object.entries(r)){const l=s?`${s}.${a}`:a;i&&typeof i=="object"&&!Array.isArray(i)?n(i,l):t[l]=i}}return n(e),t}function Tn({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[a,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${a}:${i}) must be a {string, number, or boolean}`);const l=r?r(i):String(i),c=n(a);return s.replace(c,Gr(l))},e)}async function Uo({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([a,i])=>{const l=await r(i);return{regex:n(a),transformedValue:l}}))).reduce((a,{regex:i,transformedValue:l})=>a.replace(i,Gr(l)),e)}var mn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(mn||{});const qr=e=>typeof e=="object"&&e!==null,Zn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Ho=e=>!qr(e)||!Zn(e,"channel_url")||!Zn(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Vo={1:Ho};function zo(e){if(!qr(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Vo[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Go(e,t,n,r){const s=ro.default.init({appId:e,modules:[new tt.GroupChannelModule,new ee.AIAgentModule],localCacheEnabled:!0,options:new Z.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:Z.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function qo(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 Wo=[400300,400301,400302,400310];class In{constructor(t,n,r){C(this,"chatSDK");C(this,"_logger");C(this,"_cache");C(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const a=new Z.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(a),this.chatSDK.aiAgent.addEventHandler(mn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),i=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",i);const l=zo(i);(l==null?void 0:l.category)===mn.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(a){const i=a;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(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",i.message,i.code),i}});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 s;if(t.userId===""){const a=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",a),a}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});C(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,a)=>{new Promise((i,l)=>t==null?void 0:t(i,l)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),a(i)})}});C(this,"_isCacheRestrictedError",t=>Wo.some(n=>t.code===n));C(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:a,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of a){const{key:c}=ot(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(a){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",a)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(qo(t.chatSDK),n=t.chatSDK):n=Go(t.appId,t.extensions,t.messengerVersion,t.chatParams),new In(n,t.logger,t.cache)}}const ft=new Map,Wr={set:(e,t)=>{ft.set(e,t)},get:e=>{if(ft.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=ft.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=ft.entries().next().value;return{platform:t[0],...t[1]}}},Ko=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class Jn extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`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=s}}var wn=(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))(wn||{}),kn=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(kn||{}),Kr=(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))(Kr||{});const jo=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Yo{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,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const a=await this._fetch(s,n);return r&&a.status===401?this._handleUnauthorized(a,s,n):this._toResult(a)});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 s=await this._parseErrorCode(t);if(!jo(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});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 Jn(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Jn(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 St{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 St({id:t.id,title:t.channelName??null,status:t.status2??wn.INITIALIZED,agent:(()=>{var a;const s=(a=t.recentAssignment)==null?void 0:a.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??kn.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class Mn{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 St._fromResponse(n,this)});C(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Ko({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 St._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Yo(t)}static init(t){return new Mn(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function Xo(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 Zo=1440*60*1e3;function Pe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Jo(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class At extends No{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",$o());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 i,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const s=this._getSessionCandidate(n),a=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;a!=null&&a.bot&&this._dispatcher.send(Be.MessengerSettingsUpdated({settings:a,source:"cache"}));try{const p=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=s.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=a==null?void 0:a.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let E;if(p.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),E={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:b,session_token:g,expire_at:_}=p.auto_created_user;this._cache.messenger.setAnonUser({userId:b,authToken:g,expireAt:_}),E={userId:b,authToken:g},this._logger.debug("AIAgent.authenticate: anonymous user created",b)}else E={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(E.userId,p),this._dispatcher.send(Be.MessengerSettingsUpdated({settings:p,source:"server"}));const v=(()=>{var b;return s.type==="anonymous"?So(this._dispatcher):(b=s.userSessionCandidate)==null?void 0:b.sessionHandler})(),x=await this._chatClient.connect(E,v,b=>{var g;this._logger.debug("AIAgent: session token refreshed"),(g=this._session)==null||g._updateAuthToken(b),this._deskClient.refreshDeskAuthToken(b)},()=>{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:b})=>{var g;if(b===Kr.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,2e3));const _=(g=this._session)==null?void 0:g.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(a==null?void 0:a.language)!==p.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Po({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=>{Pe(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});C(this,"searchConversation",async n=>{if(Pe(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}),s=[];for(;r.hasNext;){const a=await r.next();for(const i of a)Jo(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});C(this,"closeConversation",async n=>{var s;Pe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.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 Ur(this.chatSDK,n??{}));C(this,"patchContext",async(n,r)=>{Pe(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});C(this,"updateContext",async(n,r)=>{Pe(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});C(this,"getContextObject",async n=>{Pe(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});C(this,"refreshActiveChannel",async n=>{var l,c,d;Pe(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const a=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(c=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:c.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??a.active_channel.channel_url;const i=a.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,a),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});C(this,"_getSessionCandidate",n=>n instanceof zr?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof dn?{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-Zo<=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 dn)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=Yn(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 Mo((r,s)=>this._chatClient.chatSDK.aiAgent.appendStat(r,s))}}static init(n){var p;const r=Wr.get(n.platform),s=n.logger??new Vr(n.logLevel??Sn.WARN),a=n.dispatcher??new Hr(s),i=n.useMMKVStorage?Xo(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=po({appId:n.appId,aiAgentId:n.aiAgentId,storage:i}),d=In.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:s,cache:c}),m=Mn.init({appId:n.appId,logger:s,customApiHost:(p=n.deskParams)==null?void 0:p.customApiHost});return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new At({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:m,cache:c,logger:s,dispatcher:a})}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=Yn(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=u.createContext(null),r=({children:i,value:l})=>o.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),s=({children:i})=>o.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),a=()=>{const i=u.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,a.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:a}};function pe(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:a}){const[i,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:i,updateTemplate:p=>l(()=>p),components:c,updateComponent:(p,E)=>d(v=>({...v,[p]:E}))};return o.createElement(t.Provider,{value:m},a)}function r({template:a,children:i}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{a&&l(a)},[a]),o.createElement(o.Fragment,null,i)}function s({children:a}){return o.createElement(n,null,a)}return s.defaults=e,s.useContext=()=>u.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(a=>{s[a]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(a,l)},[l]),null}}),s}function Qo(...e){return function({children:n}){return e.reduce((r,s)=>o.createElement(s,null,r),n)}}function ea(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 s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function ta(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),a=Fe.differenceInMinutes(r,s);return a<1?n.justNow:a<60?n.minutesAgo(a):Fe.isToday(s)?n.hoursAgo(Fe.differenceInHours(r,s)):t(s,n.dateShortFormat)}const na=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},pt=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Qn=(e,t)=>{const n=pt(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=na(e);return r?`#${pt(r[0])}${pt(r[1])}${pt(r[2])}${n}`:e},jr=te("AIAgent"),ra=jr.Provider,ce=jr.useContext;function sa(e){const t=oa(e);return o.createElement(ra,{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 oa(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=At.init(e);else{const s=aa(n.current,e);(s.appId||s.aiAgentId||s.chatSDK)&&(t.current.dispose(),t.current=At.init({...e,chatParams:s.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.useEffect(()=>()=>{var s;(s=t.current)==null||s.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r}function aa(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 ia=(e,t,n)=>Le.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),nt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Yr(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function la(e){const t=Yr(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function ca(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function ua(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),a=r-s;let i=0,l=0;const c=(r+s)/2;return r!==s&&(l=c>.5?a/(2-r-s):a/(r+s)),r===e?i=(t-n)/a+(t<n?6:0):r===t?i=(n-e)/a+2:r===n&&(i=(e-t)/a+4),i/=6,[i,l,c]}function da(e,t,n){let r,s,a;if(t===0)r=s=a=n;else{const i=function(m,p,E){return E<0&&(E+=1),E>1&&(E-=1),E<.16666666666666666?m+(p-m)*6*E:E<.5?p:E<.6666666666666666?m+(p-m)*(.6666666666666666-E)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=i(c,l,e+1/3),s=i(c,l,e),a=i(c,l,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(a*255)]}function Et(e,t,n){const[r,s,a]=la(e),[i,l,c]=ua(r,s,a),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[p,E,v]=da(i,m,d);return ca([Math.round(p),Math.round(E),Math.round(v)])}function ma(e,t="light"){return{extraDark:Et(e,.6,1.2),dark:Et(e,.85,1.1),main:e,light:Et(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Et(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function hn(e){const t=Yr(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,a=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+a*.114>n?nt.BLACK:nt.WHITE}function ha(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const ga=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400}}),bt={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)"}},Zt={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 er(e){const t=fa(e),{colors:n,aiAgentColorVariables:r}=pa(e,t),s=ba(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:s}}function fa({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===bt.primary.main?bt.primary:ma(n,e):bt.primary;return{...bt,primary:r,...t}}function pa({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const a=s.primary.main,i=t??hn(a),l=n??nt.DEFAULT_BOT_MSG_BG,c=r??hn(l);return{colors:(e==="light"?ha:ga)(s,a,i,l,c),aiAgentColorVariables:{primary_color:a,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function Ea(e,t,n){const r={...e};return n.forEach(s=>{const a=t[s];a!=null&&(r[s]=a)}),r}function ba({typography:e}){if(!e)return Zt;const t={...Zt};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Zt[n],a=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Ea(s,r,a)}}),t}const{Provider:_a,useContext:$n}=te("AIAgentTheme");function Ca({logger:e,palette:t,typography:n,appearance:r,children:s}){const a=u.useRef(null),[i,l]=u.useState(()=>er({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=u.useCallback((d,m)=>{m&&(a.current=m);const p=(r==null?void 0:r.theme)??d,E=a.current?a.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=er({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 u.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&c(i.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),o.createElement(_a,{value:{theme:i,updateTheme:c}},s)}const Jt=25*1024*1024,tr=1,nr=new Set(["image/png","image/jpeg","image/jpg"]),rr=new Set(["application/pdf"]),xa={off:"off",always:"always",handed_off_only:"handed_off_only"},va=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:tr,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Jt,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:nr,supportedFileMimeTypes:rr})),n=u.useCallback(({active_channel:s,upload_restriction:a})=>{t({maxAttachmentCount:(a==null?void 0:a.max_attachment_count)??tr,attachmentMode:xa[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(a==null?void 0:a.default_upload_size_limit)??Jt,uploadSizeLimitPerType:new Map(Object.entries((a==null?void 0:a.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((a==null?void 0:a.supported_image_mime_types)??nr),supportedFileMimeTypes:new Set((a==null?void 0:a.supported_file_mime_types)??rr)})},[]),r=u.useCallback(s=>{const{channel:a,uploadSizeLimit:i=Jt}=s,l=(d=!0)=>a!=null&&a.isAIAgent?d?Ue(a):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,p=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,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 Ue(a);default:return!0}},get supportedMimeTypes(){return l()?[ln]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:c,getUploadSizeLimitInMB:d=>c(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},sr=(...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)")},Ze=e=>({...e,context:e.context??{}}),{Provider:ya,useContext:at}=te("AIAgentMessengerSession"),Sa=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:a,logger:i}=ce(),{updateTheme:l}=$n(),[c,d]=u.useState(void 0),[m,p]=u.useState(void 0),[E,v]=u.useState(null),[x,b]=u.useState(null),[g,_]=u.useState(null),[y,I]=u.useState(null),{updateBaseAttachmentRules:A,createAttachmentRules:$}=va();u.useEffect(()=>{const T=r.onMessengerSettingsUpdated(({settings:z})=>{const{appearance:Y,bot:G,launcher:ye}=z;l(Y.selected_theme,Y),_({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}),I({type:ye.image_type||"default_icon",imageUrl:ye.image_url}),A(z)}),B=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&&b(G=>G?{...G,authToken:z}:null)});return()=>{T(),B(),N()}},[r,l,A]);const k=u.useCallback(async()=>{d(void 0);try{const T=await r.authenticate(e),B=r.session;return v(B.sdkUser),b(B.userSession),p(B.activeChannel),T}catch(T){throw d(T),T}},[r,e]),S=u.useCallback(async()=>{await r.deauthenticate(),v(null),p(void 0),b(null),_(null),I(null)},[r]),R=u.useCallback(async()=>{if(!r.session){if(x)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(x==null?void 0:x.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(p(void 0),await r.refreshActiveChannel())},[r,i,x]),P=u.useCallback(async T=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(T)},[r]),O=u.useCallback(async T=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(T)},[r]);return u.useImperativeHandle(n,()=>{const T=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:k,deauthenticate:S,updateContext:async(...B)=>{const N=sr(...B);if(N.type==="active"){const G=await(await T()).updateContext(a,N.context);return Ze(G)}const z=await s.aiAgent.updateContext(N.aiAgentId,N.channelUrl,N.context);return Ze(z)},patchContext:async(...B)=>{const N=sr(...B);if(N.type==="active"){const G=await(await T()).patchContext(a,N.context);return Ze(G)}const z=await s.aiAgent.patchContext(N.aiAgentId,N.channelUrl,N.context);return Ze(z)},getContextObject:async()=>{const N=await(await T()).getContextObject(a);return Ze(N)}}},[k,S,m,s,a,i]),o.createElement(ya,{value:{sdkUser:E,userSessionInfo:e,userSession:x,activeChannel:m,setActiveChannel:p,refreshActiveChannel:R,createConversation:P,searchConversation:O,connectionError:c,aiAgentInfo:g,launcherInfo:y,authenticate:k,deauthenticate:S,createAttachmentRules:$,statsTrackers:r.statsTrackers}},t)}),Ln=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useEffect(()=>{const s=new Z.ConnectionHandler({onDisconnected:a=>{var i,l;return(l=(i=r.current).onDisconnected)==null?void 0:l.call(i,a)},onConnected:a=>{var i,l;return(l=(i=r.current).onConnected)==null?void 0:l.call(i,a)},onReconnectStarted:()=>{var a,i;return(i=(a=r.current).onReconnectStarted)==null?void 0:i.call(a)},onReconnectSucceeded:()=>{var a,i;return(i=(a=r.current).onReconnectSucceeded)==null?void 0:i.call(a)},onReconnectFailed:()=>{var a,i;return(i=(a=r.current).onReconnectFailed)==null?void 0:i.call(a)},onConnectionLost:()=>{var a,i;return(i=(a=r.current).onConnectionLost)==null?void 0:i.call(a)},onConnectionDelayed:a=>{var i,l;return(l=(i=r.current).onConnectionDelayed)==null?void 0:l.call(i,a)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])};function Aa(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:s}=ce(),{sdkUser:a,statsTrackers:i}=at(),l=Le.useForceUpdate(),[c,d]=u.useState(void 0),[m,p]=u.useState(void 0),[E,v]=u.useState(!1);function x(g){g.isAIAgent&&!g.conversation&&(v(!0),s.initConversationIfNeeded(g).finally(()=>v(!1)))}async function b(){var g,_,y;if(!a){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),p(void 0),v(!1),e){i.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const I=await t.groupChannel.getChannel(e);x(I),d(I),i.initialRender.onGetChannelComplete((g=I.conversation)==null?void 0:g.id),I.url===((_=s.session)==null?void 0:_.activeChannel.url)&&s.session._updateActiveChannel({url:I.url,status:de(I)?"closed":"open",conversationStatus:(y=I.conversation)==null?void 0:y.status}),n.debug("useChannel.getChannel: fetched channel",I)}catch(I){i.initialRender.onGetChannelError(I),I instanceof Z.SendbirdError&&p(I),n.error("useChannel.getChannel: error",I)}}}return u.useEffect(()=>{b()},[t,a,e,r]),Ln(t,{async onReconnectSucceeded(){if(!c)return;const g=await c.refresh();x(g),d(g)}}),Le.useGroupChannelHandler(t,{onChannelChanged:g=>{g.isGroupChannel()&&g.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",g.url),d(g),l())}}),{channel:c,channelFetchError:m,getChannel:b,isInitializingConversation:E}}const Ta=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload;return n==null?void 0:n.user_input_disabled_by},Ia=e=>{var i;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,s=!!r&&!r.submitted_at&&!r.canceled_at,a=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return s&&!a},wa=()=>{const{chatSDK:e,networkStateAdapter:t}=ce(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Ln(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),u.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(a=>a==="reconnecting"&&e.connectionState===Z.ConnectionState.OPEN?"connected":a)})},[t,e]),n},ka=3e4,Ma=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,a]=u.useState(!1),i=u.useRef(null),l=t&&rt(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),a(!1)},d=E=>{i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},E)},m=Date.now()-l,p=ka-m;return n||p<=0?c():d(p),()=>{i.current&&clearTimeout(i.current)}},[n,l]),s&&e},Xr=e=>{const{chatSDK:t}=ce(),[n,r]=u.useState([]);return Le.useGroupChannelHandler(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const a=s.getTypingUsers();r(a)}}}),n},$a=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,a]=u.useState(!1),i=Xr(e);return u.useEffect(()=>{if(!t)return;const l=i.some(d=>d.userId===n),c=rt(t,n)&&(Me.isStreaming(t)||r);a(c||l)},[i,t,n,r]),s},La=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:a}=at(),i=wa(),l=$a({channel:e,lastMessage:Kn(t,[ke.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),c=Ma({shouldApply:!!(e!=null&&e.isAIAgent)&&!Ue(e),isBlockedWhileAIResponding:l,lastMessage:Kn(t,[ke.SendingStatus.PENDING,ke.SendingStatus.SUCCEEDED]),currentUserId:(a==null?void 0:a.userId)??""});if(!e||i==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(i==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(de(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Lo(e))return{disabled:!0,disabledBy:"handoff_pending"};if(Ia(e))return{disabled:!0,disabledBy:"form_active"};const d=Ta(e);return d?{disabled:!0,disabledBy:d}:l||c||r?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},Ra=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(s=>{t(a=>{if(a.has(s))return a;const i=new Set(a);return i.add(s),i})},[]),r=u.useCallback(s=>{t(a=>{if(!a.has(s))return a;const i=new Set(a);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Oa}=te("AIAgentConversation");function Da({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:a,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Ce,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:p}){var O;const E=()=>d&&(g==null?void 0:g.markAsRead()),{chatSDK:v,logger:x,dispatcher:b}=ce(),{channel:g,channelFetchError:_,getChannel:y,isInitializingConversation:I}=Aa(t),{statsTrackers:A}=at();u.useEffect(()=>{if(t)return A.initialRender.setChannelUrl(t),()=>{A.initialRender.cleanup()}},[t,A]);const $=ia(v,g,{replyType:ke.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:T=>r==null?void 0:r(T),onMessagesUpdated:T=>s==null?void 0:s(T),onCacheResult:T=>A.initialRender.onCacheResult(T),onApiResult:T=>A.initialRender.onApiResult(T),logger:x,markAsRead:E,sortComparator:p}),k=Ra(),S=La({channel:g,messages:$.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:I});u.useEffect(()=>{E()},[d,g]);const R=de(g);u.useEffect(()=>{a==null||a(R)},[R,a]),u.useEffect(()=>{const T=async B=>{const N=typeof(B==null?void 0:B.channelUrl)=="string";g&&N&&B.channelUrl!==g.url||(x.debug("conversation.dispatcher: try to close conversation",g),g!=null&&g.conversation&&g.conversation.status===ee.ConversationStatus.OPEN&&(await g.closeConversation(),i==null||i()))};return b.subscribe(ue.ConversationClose,T),()=>{b.unsubscribe(ue.ConversationClose,T)}},[b,g,x,(O=g==null?void 0:g.conversation)==null?void 0:O.status,i]);const P={conversation:(g==null?void 0:g.conversation)??void 0,channelSource:{channel:g,error:_,refetch:()=>y(),closeConversation:async()=>{de(g)||await(g==null?void 0:g.closeConversation())}},messageSource:{messages:$.messages,newMessages:$.newMessages,initialized:$.initialized,loadPrevious:()=>$.loadPrevious(),loadNext:()=>$.loadNext(),deleteMessage:T=>$.deleteMessage(T),resendMessage:T=>$.resendMessage(T),resetNewMessages:()=>$.resetNewMessages(),sendUserMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendUserMessage(T,c);return c==null||c(B),B},sendFileMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendFileMessage(T,c);return c==null||c(B),B},sendMultipleFilesMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendMultipleFilesMessage(T,c);return c==null||c(B),B}},state:{streamAnimation:k,input:S}};return o.createElement(Oa,{value:P},e)}function Na(e,t){var v,x,b,g,_,y,I,A,$,k;const[n,r]=u.useState(!1),[s,a]=u.useState(null),[i,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),p=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),a(null),l([]);try{c==null||c.dispose();const S=new Ur(e,t);S.setConversationListCollectionHandler({onChannelsAdded:()=>{l(S.channels)},onChannelsUpdated:()=>{l(S.channels)},onChannelsDeleted:()=>{l(S.channels)}}),await S.loadMore(),d(S),a(null)}catch(S){d(null),a(S)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(v=t.filter)==null?void 0:v.aiAgentChannelFilter,(b=(x=t.filter)==null?void 0:x.aiAgentConversationStatusFilter)==null?void 0:b.join(),(_=(g=t.filter)==null?void 0:g.aiAgentIds)==null?void 0:_.join(),(y=t.filter)==null?void 0:y.deskChannelFilter,(A=(I=t.filter)==null?void 0:I.pinnedChannelUrls)==null?void 0:A.join(),($=t.filter)==null?void 0:$.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),E=u.useCallback(async()=>{if(c)try{await c.loadMore()}catch(S){a(S)}},[c]);return Ln(e,{onConnected:()=>p()}),u.useEffect(()=>{p()},[p]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:s,channels:i,loadMore:E}}const{Provider:Pa}=te("AIAgentConversationList");function Fa({conversationListLimit:e,conversationListFilter:t,children:n}){var p,E;const{chatSDK:r,aiAgentId:s,queryParams:a}=ce(),i={aiAgentIds:[s],aiAgentConversationStatusFilter:[ee.ConversationStatus.CLOSED,ee.ConversationStatus.OPEN]},l=e??((p=a==null?void 0:a.conversationListParams)==null?void 0:p.limit),c={...i,...(E=a==null?void 0:a.conversationListParams)==null?void 0:E.filter,...t},d=Na(r,{limit:l,filter:c}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return o.createElement(Pa,{value:m},n)}function Ba(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:Ua,useContext:Zr}=te("MessageTemplateFetching");function Ha({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[s,a]=u.useState({}),i=u.useCallback((d,m)=>{a(p=>({...p,[d]:{fetching:!1,error:!1,...p[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:p,suspense:E=!1})=>{const v=m(p);if(v)return v;const x=r.current[p];if(x)return x;E||i(p,{fetching:!0});const b=d(p).catch(g=>{throw E||i(p,{error:!0}),g}).finally(()=>{E||i(p,{fetching:!1}),delete r.current[p]});return r.current[p]=b,b},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const p=Ba(m());return n.current[d]=p,p},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return o.createElement(Ua,{value:c},e)}const Dt={VARIABLE:e=>new RegExp(`\\{${e}\\}`,"g"),VIEW_VARIABLE:e=>new RegExp(`"{@${e}}"`,"g")};function Re({uiTemplateString:e,variables:t={}}){const n=Bo(t);return Tn({template:e,variables:n,variableKeyPattern:r=>Dt.VARIABLE(r)})}function Oe({theme:e,uiTemplateString:t,colorVariables:n={}}){return Tn({template:t,variables:n,variableKeyPattern:r=>Dt.VARIABLE(r),variableValueTransformer:r=>Fo(e,r)})}function Va({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:s,onRequestTemplate:a}){const l=Object.values(n).flat().map(d=>d.key);return[...new Set(l)].some(d=>!a(d))?null:Tn({template:t,variables:n,variableKeyPattern:d=>Dt.VIEW_VARIABLE(d),variableValueTransformer:d=>{const m=d.map(({key:p,variables:E})=>{const v=a(p),{ui_template:x,color_variables:b}=ot(v);let g=JSON.stringify(x);return g=Re({uiTemplateString:g,variables:s}),g=Oe({theme:e,uiTemplateString:g,colorVariables:b}),g=Oe({theme:e,uiTemplateString:g,colorVariables:r}),g=Re({uiTemplateString:g,variables:E}),Ot(g)});return JSON.stringify(m)}})}async function za({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:s,onRequestTemplate:a}){return Uo({template:t,variables:n,variableKeyPattern:i=>Dt.VIEW_VARIABLE(i),variableValueTransformer:async i=>{const l=i.map(async({key:d,variables:m})=>{const p=await a(d),{ui_template:E,color_variables:v}=ot(p);let x=JSON.stringify(E);return x=Re({uiTemplateString:x,variables:s}),x=Oe({theme:e,uiTemplateString:x,colorVariables:v}),x=Oe({theme:e,uiTemplateString:x,colorVariables:r}),x=Re({uiTemplateString:x,variables:m}),Ot(x)}),c=await Promise.all(l);return JSON.stringify(c)}})}const Ga=({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:s,color_variables:a}=ot(e);let i=JSON.stringify(s);if(Object.keys(r.viewVariables??{}).length>0){const c=Va({...r,uiTemplateString:i,aiAgentColorVariables:t,internalVariables:n});if(c===null)return null;i=c}return i=Re({...r,uiTemplateString:i,variables:n}),i=Oe({...r,uiTemplateString:i,colorVariables:a}),i=Oe({...r,uiTemplateString:i,colorVariables:t}),i=Re({...r,uiTemplateString:i}),Ot(i)},qa=async({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:s,color_variables:a}=ot(e);let i=JSON.stringify(s);return Object.keys(r.viewVariables??{}).length>0&&(i=await za({...r,uiTemplateString:i,aiAgentColorVariables:t,internalVariables:n})),i=Re({...r,uiTemplateString:i,variables:n}),i=Oe({...r,uiTemplateString:i,colorVariables:a}),i=Oe({...r,uiTemplateString:i,colorVariables:t}),i=Re({...r,uiTemplateString:i}),Ot(i)},Wa=e=>{const{aiAgentColorVariables:t={}}=e,{internalVariables:n}=Zr();return u.useState(()=>{const r=e.onGetCachedTemplate(e.templateKey);return r?Ga({...e,rawTemplate:r,aiAgentColorVariables:t,internalVariables:n,onRequestTemplate:e.onGetCachedTemplate}):null})},Ka=e=>{const[t]=Wa(e);if(t)return t;const{aiAgentColorVariables:n={}}=e,{internalVariables:r,fetchTemplate:s,suspend:a}=Zr();return a(e.templateKey,async()=>{const l=await s({...e,suspense:!0});return await qa({...e,rawTemplate:l,aiAgentColorVariables:n,internalVariables:r})}).value},ja="remove_powered_by",Rn=(e,t)=>{var s,a;const{chatSDK:n}=ce(),{aiAgentInfo:r}=at();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&An(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(a=n==null?void 0:n.appInfo)==null?void 0:a.applicationAttributes;return u.useMemo(()=>!(Array.isArray(i)&&i.includes(ja)),[i])}throw new Error("Unsupported feature")},Ya={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"},Xa={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Za={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Ja={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}}},Qa={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:a}=e;if(a){if(a.min_select!==void 0&&r.length<a.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(a.min_select):n.minSelect};if(a.max_select!==void 0&&r.length>a.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(a.max_select):n.maxSelect}}return{isValid:!0}}},ei={text:Xa,number:Za,"single-select":Ja,"multi-select":Qa},ti={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Jr(e){return ei[e.type]||ti}function or(e){return Jr(e).getValueOrDefault(e)}function ni(e,t,n={}){const r={...Ya,...n};return Jr(e).validate(e,t,r)}const ri=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[a,i]=u.useState({}),[l,c]=u.useState(()=>{const b={};return e.fields.forEach(g=>{b[g.key]=or(g)}),b}),d=u.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);u.useEffect(()=>{if(d==="submitted"||d==="canceled"){const b={};let g=!1;e.fields.forEach(_=>{const y=or(_);JSON.stringify(l[_.key])!==JSON.stringify(y)&&(g=!0),b[_.key]=y}),g&&c(b)}},[d]);const m=(b,g)=>{c(_=>({..._,[b]:g})),i(_=>({..._,[b]:void 0}))},p=e.fields.map(b=>{var y,I,A;const g=l[b.key]??null,_={key:b.key,label:b.label,error:a[b.key],required:b.required};return b.type==="text"?{..._,type:"text",layout:b.layout,value:g,...b.placeholder&&{placeholder:b.placeholder},...((y=b.rules)==null?void 0:y.max_length)&&{maxLength:b.rules.max_length}}:b.type==="number"?{..._,type:"number",layout:b.layout,value:g,...b.placeholder&&{placeholder:b.placeholder},...((I=b.rules)==null?void 0:I.max)&&{max:b.rules.max}}:b.type==="single-select"?{..._,type:"single-select",layout:b.layout,value:g,options:b.options}:b.type==="multi-select"?{..._,type:"multi-select",layout:b.layout,value:g,options:b.options,...((A=b.rules)==null?void 0:A.max_select)&&{maxSelect:b.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:p,getField:b=>p.find(g=>g.key===b),updateFieldValue:m,submit:async()=>{const b={};let g=!1;for(const _ of e.fields){const y=l[_.key]??null,I=ni(_,y,n);I.isValid||(b[_.key]=I.error,g=!0)}if(i(b),!g&&r){const _={};e.fields.forEach(y=>{_[y.key]=l[y.key]??null}),await r(_)}},cancel:async()=>{await(s==null?void 0:s())}}},si=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},oi=e=>{const{aiAgentInfo:t}=at(),r=Xr(e)[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),a=s?si(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:a}},Qr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[a]=e.members.filter(i=>i.userId!==t.userId);return a})(),s={ai(a){return{fallbackIcon:a,url:n.profileUrl,title:n.nickname}},human(a){return{fallbackIcon:a,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(a){return{fallbackIcon:a,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?Ue(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},ar=e=>u.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 ai=new Set(["free_text","single_choice"]),ii=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[a,i]=ar({csatType:t,csat:n,csatReason:r,isResolved:s}),[l,c]=ar({followUpItem:!1}),d=u.useMemo(()=>{var g;const v=a.csat,x=typeof v=="number",b=(g=e.follow_up)==null?void 0:g.find(_=>x?_.scores.includes(v):_.always_visible??!1);if(ai.has(b==null?void 0:b.response_type))return b},[a.csat,e.follow_up]),m=(()=>{var v;if(typeof n=="number")return"submitted";if((t===he.AI_AGENT_CSAT_5||t===he.HELPDESK_CSAT_5)&&typeof a.csat=="number")return"submittable";if(t===he.AI_AGENT_CSAT_5_WITH_CRE){const x=typeof a.csat=="number",b=!((v=e.cre)!=null&&v.required)||typeof a.isResolved=="boolean";if(x&&b)return"submittable"}return"unsubmittable"})(),p=u.useCallback(()=>typeof a.csat>"u"?!1:d!=null&&d.required&&!a.csatReason?(c({followUpItem:!0}),!1):!0,[a,d,c]);return u.useEffect(()=>{r||(i({csatReason:""}),c({followUpItem:!1}))},[r,d,i,c]),{params:a,setParams:i,error:l,setError:c,followUpItem:d,state:m,validateParams:p,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Qt=5,li=250,ci=50,ir=e=>Math.max(0,e-ci),ui=e=>e<1e3?{speed:Qt*.5,chunkSize:2}:e<2e3?{speed:Qt*.8,chunkSize:2}:{speed:Qt*.6,chunkSize:3},di=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:s,onAnimationComplete:a}=e,[i,l]=u.useState(()=>ir(t.length)),c=u.useRef(null),d=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=u.useRef({onStart:r,onProgress:s,onComplete:a}).current,p=u.useRef({startCalled:!1,completeCalled:!1}).current,E=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,v=n,x=i<t.length,b=E.initialEnabled&&(v||x);return u.useLayoutEffect(()=>{m.onStart=r,m.onProgress=s,m.onComplete=a,E.textLength=t.length,E.enabled=n}),u.useLayoutEffect(()=>{var g;E.initialEnabled&&(p.startCalled||(p.startCalled=!0,(g=m.onStart)==null||g.call(m)),l(_=>t.length<_?t.length:_))},[t]),u.useEffect(()=>{if(!E.initialEnabled)return;let g=ir(t.length);d.lastUpdate=0,d.startTime=0,d.lastProgressCall=0;const _=y=>{var O;d.lastUpdate===0&&(d.lastUpdate=y,d.startTime=y,d.lastProgressCall=y);const I=E.textLength,A=y-d.lastUpdate,$=y-d.startTime,{speed:k,chunkSize:S}=ui($),R=k*S;A>=R&&g<I&&(g=Math.min(g+S,I),l(g),d.lastUpdate=y),y-d.lastProgressCall>=li&&(d.lastProgressCall=y,(O=m.onProgress)==null||O.call(m)),(g<I||E.enabled)&&(c.current=requestAnimationFrame(_))};return c.current=requestAnimationFrame(_),()=>{var y;c.current&&cancelAnimationFrame(c.current),p.startCalled&&!p.completeCalled&&(p.completeCalled=!0,(y=m.onComplete)==null||y.call(m))}},[]),u.useEffect(()=>{var I;const g=E.initialEnabled&&p.startCalled,_=!n,y=i>=t.length&&t.length>0;g&&_&&y&&!p.completeCalled&&(p.completeCalled=!0,(I=m.onComplete)==null||I.call(m))},[n,i,t.length]),{streamText:E.initialEnabled?t.slice(0,i):t,isAnimating:b}},mi="1.21.2",le="sb-agent",me={ENTRY:`${le}-entry`,MODAL_ROOT:`${le}-modal-root`,WINDOW:`${le}-window`,LAUNCHER:`${le}-launcher`},_t=2147483647,Ve={MODAL:_t-1,TOOLTIP:_t-2,WINDOW:_t-3,LAUNCHER:_t-4},es=36,hi=100,gi=mi,On="noopener noreferrer nofollow";function fi(){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 Ct={};function pi(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Ct[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Ct[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Ct[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(Ct).filter(t=>t.startsWith(e))}}}}const Ei='@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}',bi={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",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"}},gn={language:"en",strings:bi,dateLocale:Xs.enUS},ts=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,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}),_i=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Nt},Nt="en",Ci=new Set([Nt,"ko","es","pt","fr","hi","it","de","tr","ja"]),xi=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},lr=ts(gn.strings),vi={...lr,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:lr.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"},Tt={language:gn.language,dateLocale:gn.dateLocale,stringSet:vi},yi=Object.freeze(Object.defineProperty({__proto__:null,default:Tt},Symbol.toStringTag,{value:"Module"})),fn=new Map([[Nt,Tt]]);async function Si(e){const t=fn.get(e);if(t)return t;try{if(Ci.has(e)){const{default:n}=await xi(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/DbxUqtQc.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>yi),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/DTCJ6-eC.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/7UVs65zS.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/DfRVurNO.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/JLk8Bvao.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/BRnfdIkb.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMS5Zb7W.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/Dl0262MS.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DFmkiYPE.cjs"))}),`./languages/${e}.ts`,3);return fn.set(e,n),n}return Tt}catch{return Tt}}const{Provider:Ai,useContext:K}=te("Localization"),Ti=({language:e=navigator.language,logger:t,stringSet:n,children:r})=>{const[s,a]=u.useState(fn.get(Nt));return u.useEffect(()=>{const i=_i(e);s.language!==i&&(t==null||t.debug("localization.useEffect: update language",{from:s.language,to:i}),Si(i).then(a))},[e,t]),o.createElement(Ai,{value:{language:s.language,stringSet:{...s.stringSet,...n},dateLocale:s.dateLocale,format:(i,l,c)=>Fe.format(i,l,{locale:s.dateLocale,...c})}},r)},It="data-sb-agent-theme",cr=e=>(t,...n)=>{let r="";return t.forEach((s,a)=>{r+=s+(n[a]??"")}),`[${It}='${e}'] & { ${r} }`},F={light:cr("light"),dark:cr("dark")},Ii=w.css(({theme:e})=>{const{palette:t}=e;return`
|
|
2
2
|
:root,
|
|
3
3
|
:host {
|
|
4
4
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|