@livechatta/sdk 1.0.0 → 1.0.1

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.
@@ -1,2 +1,2 @@
1
- "use strict";var t=require("socket.io-client");class e{constructor(t){if(!t.linkCode)throw new Error("LiveChatta: linkCode is required");if(!t.apiKey)throw new Error("LiveChatta: apiKey is required");if(!t.publicKey)throw new Error("LiveChatta: publicKey is required");this.linkCode=t.linkCode,this.apiKey=t.apiKey,this.baseUrl=(t.baseUrl||"https://api.livechatta.com").replace(/\/+$/,""),this.chatUsername=t.chatUsername,this.publicKey=t.publicKey,this.enableSocket=!1!==t.enableSocket,this.enableHttp=!1!==t.enableHttp,this.debug=!0===t.debug,this.ownerToken=t.ownerToken||void 0,this.memberToken=t.memberToken||void 0}get wsUrl(){try{const t=new URL(this.baseUrl);return t.protocol="https:"===t.protocol?"wss:":"ws:",t.toString().replace(/\/+$/,"")}catch(t){return this.baseUrl.replace(/^http/,"ws")}}get apiUrl(){return`${this.baseUrl}/api/v1`}get rootUrl(){return this.baseUrl}get externalUrl(){return`${this.baseUrl}/api/v1/external`}get embedUrl(){return`${this.baseUrl}/in/${this.linkCode}/embed/chat`}get appEmbedUrl(){return`${this.baseUrl}/in/${this.linkCode}/app/embed/chat`}}async function n(t,e){return"undefined"!=typeof window&&"undefined"!=typeof crypto&&void 0!==crypto.subtle?async function(t,e){const n=function(t){const e=t.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s/g,""),n=atob(e),r=new Uint8Array(n.length);for(let t=0;t<n.length;t++)r[t]=n.charCodeAt(t);return r.buffer}(t),r=await crypto.subtle.importKey("spki",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),s=(new TextEncoder).encode(JSON.stringify(e));return function(t){const e=new Uint8Array(t);let n="";for(let t=0;t<e.length;t++)n+=String.fromCharCode(e[t]);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.encrypt({name:"RSA-OAEP"},r,s))}(t,e):async function(t,e){const{publicEncrypt:n,constants:r}=await(import("crypto")),s=(new TextEncoder).encode(JSON.stringify(e));return n({key:t,padding:r.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},s).toString("base64url")}(t,e)}class r{constructor(t,e,n,r){this.apiKey=t,this.linkCode=e,this.chatUsername=n,this.publicKey=r,this.cachedToken=null}get hasPublicKey(){return!!this.publicKey}async getToken(){if(this.cachedToken)return this.cachedToken;if(this.publicKey){const t={apiKey:this.apiKey,linkCode:this.linkCode,chatUsername:this.chatUsername};this.cachedToken=await n(this.publicKey,t)}else this.cachedToken=this.apiKey;return this.cachedToken}invalidate(){this.cachedToken=null}async refresh(){return this.invalidate(),this.getToken()}}class s{constructor(){this.listeners=new Map,this.onceListeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),this}once(t,e){return this.onceListeners.has(t)||this.onceListeners.set(t,new Set),this.onceListeners.get(t).add(e),this}off(t,e){var n,r;return e?(null===(n=this.listeners.get(t))||void 0===n||n.delete(e),null===(r=this.onceListeners.get(t))||void 0===r||r.delete(e)):(this.listeners.delete(t),this.onceListeners.delete(t)),this}emit(t,...e){var n;null===(n=this.listeners.get(t))||void 0===n||n.forEach(t=>{try{t(...e)}catch(t){}});const r=this.onceListeners.get(t);return r&&(r.forEach(t=>{try{t(...e)}catch(t){}}),r.clear()),this}removeAllListeners(){return this.listeners.clear(),this.onceListeners.clear(),this}}function o(){if("undefined"!=typeof window){const t=window;if(t.Capacitor&&"function"==typeof t.Capacitor.getPlatform){const e=String(t.Capacitor.getPlatform()).toLowerCase();if("ios"===e)return{kind:"capacitor-ios",platform:"mobile-ios",isAppShell:!0};if("android"===e)return{kind:"capacitor-android",platform:"mobile-android",isAppShell:!0}}if(t.__TAURI_INTERNALS__||t.__TAURI__){const t="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent:"";return/Mac OS X|Macintosh/i.test(t)?{kind:"tauri-macos",platform:"desktop-macos",isAppShell:!0}:/Windows/i.test(t)?{kind:"tauri-windows",platform:"desktop-windows",isAppShell:!0}:{kind:"tauri-linux",platform:"desktop-linux",isAppShell:!0}}return t.ReactNativeWebView?{kind:"react-native",platform:"mobile-ios",isAppShell:!0}:{kind:"web",platform:"web",isAppShell:!1}}return{kind:"node",platform:"node",isAppShell:!1}}let a=null;function i(){return a||(a=o()),a}class h{async requestMedia(t){var e;const n=!t||!1!==t.audio,r=!(!t||!t.video),s=i();let o="prompt",a="prompt";if("capacitor-ios"===s.kind||"capacitor-android"===s.kind)try{const{Capacitor:t,registerPlugin:e}=await(import("@capacitor/core"));if(t&&t.isPluginAvailable&&t.isPluginAvailable("HopBridge")){const t=e("HopBridge"),n=await t.requestPermissions();o=(null==n?void 0:n.mic)||"prompt",a=(null==n?void 0:n.cam)||"prompt"}}catch(t){}if("undefined"!=typeof navigator&&(null===(e=navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia)){const t={};n&&(t.audio=!0),r&&(t.video=!0),t.audio||t.video||(t.audio=!0);try{(await navigator.mediaDevices.getUserMedia(t)).getTracks().forEach(t=>t.stop()),n&&(o="granted"),r&&(a="granted")}catch(t){n&&"granted"!==o&&(o="denied"),r&&"granted"!==a&&(a="denied")}}else o="unsupported",a="unsupported";return{granted:!(n&&"granted"!==o||r&&"granted"!==a),mic:o,cam:a}}async requestNotifications(){const t=i();if("capacitor-ios"===t.kind||"capacitor-android"===t.kind)try{const{registerPlugin:t}=await(import("@capacitor/core")),e=t("PushNotifications"),n=await e.requestPermissions();return"granted"===(null==n?void 0:n.receive)?"granted":(null==n?void 0:n.receive)||"prompt"}catch(t){return"unsupported"}if("undefined"==typeof Notification)return"unsupported";if("granted"===Notification.permission)return"granted";if("denied"===Notification.permission)return"denied";try{return await Notification.requestPermission()}catch(t){return"denied"}}}var c,l,u,p,d,E,m,y,T,g,C,S,v,O,A,b;function _(t){const e=t&&"object"==typeof t?t.code:void 0;return"string"==typeof e&&/^[A-Z][A-Z0-9_]{2,47}$/.test(e)?e:void 0}exports.ChatEvent=void 0,(c=exports.ChatEvent||(exports.ChatEvent={})).ALL_CONVERSATIONS="all-conversations",c.NEW_CONVERSATION="new-conversation",c.ENTER_CONVERSATION="enter-conversation",c.JOIN_CONVERSATION="join-conversation",c.EDIT_CONVERSATION="edit-conversation",c.MAKE_ADMIN_CONVERSATION="make-admin-conversation",c.TOGGLE_CONVERSATION="toggle-conversation",c.STATUS_CHANGE_CONVERSATION="status-change-conversation",c.MEMBER_STATUS_CHANGE_CONVERSATION="member-status-change-conversation",c.MEMBERSHIP_REVOKED="membership-revoked",c.SHARED_CHANNEL_INVITE="shared-channel-invite",c.SHARED_CHANNEL_UPDATED="shared-channel-updated",c.MESSAGE_STATUS_CHANGE="message-status-change",c.MESSAGE_REACTION="message-reaction",c.VALIDATE_PASSWORD="validate-password",c.ALL_MESSAGES="all-messages",c.NEW_MESSAGE="new-message",c.NEW_TYPING="new-typing",c.SAVE_DRAFT="save-draft",c.DRAFT_UPDATED="draft-updated",c.SET_STATUS="set-status",c.STATUS_UPDATED="status-updated",c.UPDATE_LIVE_LOCATION="update-live-location",c.LIVE_LOCATION_UPDATED="live-location-updated",c.STOP_LIVE_LOCATION="stop-live-location",c.LIVE_LOCATION_ENDED="live-location-ended",c.FORGOT_PASSWORD="forgot-password",c.CHANGE_PASSWORD="change-password",c.RESET_PASSWORD="reset-password",c.REFRESH_TOKEN="refresh-token",c.REVOKE_TOKEN="revoke-token",c.ONLINE="online",c.OFFLINE="offline",c.CHAT_ERROR="chat-error",c.AUTH_ERROR="auth-error",c.UNREAD_COUNT_UPDATE="unread-count-update",c.NOTIFICATION="notification",c.EDIT_MESSAGE="edit-message",c.FORWARD_MESSAGE="forward-message",c.FORWARD_POST="forward-post",c.MESSAGE_FAILED="message-failed",c.MESSAGE_READ="message-read",c.SEARCH_MESSAGES="search-messages",c.SCHEDULED_MESSAGE="scheduled-message",c.SEARCH_CHAT_USERS="search-chat-users",c.THREAD_MESSAGES="thread-messages",c.TOGGLE_BOOKMARK="toggle-bookmark",c.GET_BOOKMARKS="get-bookmarks",c.GET_ALL_BOOKMARKS="get-all-bookmarks",c.VOTE_POLL="vote-poll",c.CREATE_POST="create-post",c.GET_POSTS="get-posts",c.GET_STORIES="get-stories",c.VIEW_POST="view-post",c.REACT_TO_POST="react-to-post",c.REPLY_TO_POST="reply-to-post",c.UPDATE_POST="update-post",c.DELETE_POST="delete-post",c.GET_POST_MESSAGES="get-post-messages",c.ALL_THREADS="all-threads",c.NEW_STORY="new-story",c.TRANSLATE_MESSAGE="translate-message",c.SET_LANGUAGE="set-language",c.PIN_CONVERSATION="pin-conversation",c.CONVERSATION_MEMBERS="conversation-members",c.LINK_HANDLES="link-handles",c.LINK_HOPS="link-hops",c.LINK_USER_JOINED="link-user-joined",c.LINK_USER_UPDATED="link-user-updated",c.ONLINE_USERS="online-users",c.HEARTBEAT="heartbeat",c.HOP_START="hop-start",c.HOP_END="hop-end",c.HOP_JOIN="hop-join",c.HOP_LEAVE="hop-leave",c.HOP_CONNECT_TRANSPORT="hop-connect-transport",c.HOP_PRODUCE="hop-produce",c.HOP_CONSUME="hop-consume",c.HOP_RESUME_CONSUMER="hop-resume-consumer",c.HOP_MEDIA_CHANGE="hop-media-change",c.HOP_SCREENSHARE_START="hop-screenshare-start",c.HOP_SCREENSHARE_STOP="hop-screenshare-stop",c.HOP_RECORDING_START="hop-recording-start",c.HOP_RECORDING_STOP="hop-recording-stop",c.HOP_INVITE_DECLINE="hop-invite-decline",c.HOP_ADMIT="hop-admit",c.HOP_DENY="hop-deny",c.HOP_ICE_RESTART="hop-ice-restart",c.HOP_REJOIN_ROOM="hop-rejoin-room",c.HOP_AD_HOC_START="hop-ad-hoc-start",c.HOP_INVITE_REQUEST="hop-invite-request",c.HOP_GET_SESSION="hop-get-session",c.HOP_MEETING_CREATE="hop-meeting-create",c.HOP_MEETING_CANCEL="hop-meeting-cancel",c.HOP_MEETING_LIST="hop-meeting-list",c.HOP_LIST_PRODUCERS="hop-list-producers",c.HOP_LIST_PARTICIPANTS="hop-list-participants",c.HOP_MUTE_PARTICIPANT="hop-mute-participant",c.HOP_DROP_PARTICIPANT="hop-drop-participant",c.HOP_PIN_FOR_ALL="hop-pin-for-all",c.HOP_LIST_ACTIVE="hop-list-active",c.HOP_TRANSPORT_PARAMS="hop-transport-params",c.HOP_STARTED="hop-started",c.HOP_ENDED="hop-ended",c.HOP_PARTICIPANT_JOINED="hop-participant-joined",c.HOP_PARTICIPANT_LEFT="hop-participant-left",c.HOP_NEW_PRODUCER="hop-new-producer",c.HOP_PRODUCER_CLOSED="hop-producer-closed",c.HOP_INVITE="hop-invite",c.HOP_MEETING_UPDATED="hop-meeting-updated",c.HOP_LOBBY_WAITING="hop-lobby-waiting",c.HOP_DENIED="hop-denied",c.HOP_REDIRECT="hop-redirect",c.HOP_RECORDING_STARTED="hop-recording-started",c.HOP_RECORDING_STOPPED="hop-recording-stopped",c.HOP_RECORDING_READY="hop-recording-ready",c.HOP_RECORDING_ALREADY_ACTIVE="hop-recording-already-active",c.HOP_RECORDING_FORBIDDEN="hop-recording-forbidden",c.HOP_INVITE_DECLINED="hop-invite-declined",c.HOP_SCREENSHARE_STARTED="hop-screenshare-started",c.HOP_MEDIA_CHANGED="hop-media-changed",c.HOP_MEETING_REMINDER="hop-meeting-reminder",c.HOP_PARTICIPANT_MUTED="hop-participant-muted",c.HOP_PINNED_FOR_ALL="hop-pinned-for-all",c.HOP_PARTICIPANT_DROPPED="hop-participant-dropped",c.HOP_YOU_WERE_DROPPED="hop-you-were-dropped",c.HOP_INVITE_ANSWERED="hop-invite-answered",c.HOP_UNMUTE_REQUESTED="hop-unmute-requested",c.HOP_REACTION="hop-reaction",c.HOP_KEEP_WAITING="hop-keep-waiting",c.HOP_VOTE="hop-vote",c.HOP_VOTE_UPDATED="hop-vote-updated",c.HOP_RAISE_HAND="hop-raise-hand",c.HOP_NEW_VOTE_ROUND="hop-new-vote-round",c.HOP_VOTE_COMPLETE="hop-vote-complete",c.HOP_HOST_CHANGED="hop-host-changed",c.HOP_MAKE_HOST="hop-make-host",c.HOP_ADMITTED="hop-admitted",c.HOP_CO_HOST_ASSIGN="hop-co-host-assign",c.HOP_CO_HOST_ASSIGNED="hop-co-host-assigned",c.HOP_POLL_LAUNCH="hop-poll-launch",c.HOP_POLL_LAUNCHED="hop-poll-launched",c.HOP_POLL_VOTE="hop-poll-vote",c.HOP_POLL_VOTE_UPDATED="hop-poll-vote-updated",c.HOP_WHITEBOARD_SYNC="hop-whiteboard-sync",c.HOP_WHITEBOARD_DELTA="hop-whiteboard-delta",c.HOP_POLL_CLOSE="hop-poll-close",c.HOP_COLLAB_STATE="hop-collab-state",c.HOP_CAPTIONS_TOGGLE="hop-captions-toggle",c.HOP_CAPTION="hop-caption",c.HOP_RECORDING_LIST="hop-recording-list",c.HOP_CAPTIONS_STATE="hop-captions-state",c.HOP_CAPTION_TEXT="hop-caption-text",c.AI_CREDITS_UPDATED="ai-credits-updated",c.AI_CREDITS_EXHAUSTED="ai-credits-exhausted",c.WHITEBOARD_OPEN="whiteboard-open",c.WHITEBOARD_STROKE="whiteboard-stroke",c.WHITEBOARD_CLEAR="whiteboard-clear",c.WHITEBOARD_CLOSE="whiteboard-close",c.WHITEBOARD_SNAPSHOT="whiteboard-snapshot",c.CREATE_AUTOMATION="create-automation",c.UPDATE_AUTOMATION="update-automation",c.DELETE_AUTOMATION="delete-automation",c.GET_AUTOMATIONS="get-automations",c.START_WEBINAR="start-webinar",c.RAISE_HAND="raise-hand",c.LOWER_HAND="lower-hand",c.PROMOTE_ATTENDEE_AUDIO="promote-attendee-audio",c.WEBINAR_QA_SUBMIT="webinar-qa-submit",c.WEBINAR_QA_ANSWER="webinar-qa-answer",c.WEBINAR_STARTED="webinar-started",c.WEBINAR_HAND_RAISED="webinar-hand-raised",c.WEBINAR_HAND_LOWERED="webinar-hand-lowered",c.WEBINAR_ATTENDEE_PROMOTED="webinar-attendee-promoted",c.WEBINAR_QA_UPDATED="webinar-qa-updated",c.GET_CONVERSATION_STATS="get-conversation-stats",c.UPDATE_CHAT_USER_SETTINGS="update-chat-user-settings",c.MESSAGE_DELIVERED="message-delivered",c.MESSAGE_INFO="message-info",c.MUTE_CONVERSATION="mute-conversation",c.CONVERSATION_MUTED="conversation-muted",c.UPDATE_QUIET_HOURS="update-quiet-hours",c.QUIET_HOURS_UPDATED="quiet-hours-updated",c.SET_MESSAGE_REMINDER="set-message-reminder",c.CANCEL_MESSAGE_REMINDER="cancel-message-reminder",c.MESSAGE_REMINDERS_CHANGED="message-reminders-changed",c.MESSAGE_REMINDER_DUE="message-reminder-due",c.UPDATE_CONVERSATION_PERMISSIONS="update-conversation-permissions",c.CONVERSATION_PERMISSIONS_UPDATED="conversation-permissions-updated",c.HUDDLE_START="huddle-start",c.HUDDLE_STATUS="huddle-status",c.HUDDLE_END="huddle-end",c.HUDDLE_UPDATED="huddle-updated",c.TRANSCRIBE_MESSAGE="transcribe-message",c.MESSAGE_TRANSCRIPT_UPDATED="message-transcript-updated",c.INBOX_UPDATED="inbox-updated",c.INTERNAL_NOTE="internal-note",c.INTERNAL_NOTE_DELETED="internal-note-deleted",c.CONVERSATION_NOTES_UPDATED="conversation-notes-updated",c.CSAT_UPDATED="csat-updated",c.CONVERSATION_READ="conversation-read",c.CONVERSATION_UNREAD="conversation-unread",c.UNREAD_TOTALS="unread-totals",c.DELETE_MESSAGE="delete-message",c.MESSAGE_DELETED="message-deleted",c.SEARCH_ALL="search-all",c.SUBMIT_PRE_CHAT="submit-pre-chat",c.PRE_CHAT_SUBMITTED="pre-chat-submitted",c.LINK_SETTINGS_UPDATED="link-settings-updated",c.CALL_LOGGED="call-logged",c.STICKERS_MINE="stickers-mine",c.STICKERS_SEARCH="stickers-search",c.STICKER_UPLOAD="sticker-upload",c.STICKER_ADD="sticker-add",c.STICKER_REMOVE="sticker-remove",c.CHATTA_MONEY_CARD="chatta-money-card",c.CHATTA_MONEY_CONFIRM="chatta-money-confirm",c.MONEY_CARD_GET="money-card-get",c.MONEY_CARD_ACTION="money-card-action",c.MONEY_CARD_UPDATE="money-card-update",c.WEBINAR_QA_ANSWER_LIVE="webinar-qa-answer-live",c.WEBINAR_QA_VOTE="webinar-qa-vote",c.WEBINAR_VIEWER_COUNT="webinar-viewer-count",exports.SDKEvent=void 0,(l=exports.SDKEvent||(exports.SDKEvent={})).CONNECTING="sdk:connecting",l.CONNECTED="sdk:connected",l.DISCONNECTED="sdk:disconnected",l.RECONNECTING="sdk:reconnecting",l.RECONNECTED="sdk:reconnected",l.ERROR="sdk:error",l.QUEUE_FLUSH="sdk:queue-flush",exports.ChatConversationType=void 0,(u=exports.ChatConversationType||(exports.ChatConversationType={})).SINGLE="SINGLE",u.GROUP="GROUP",u.CHANNEL="CHANNEL",u.SELF="SELF",exports.ChatMessageStatus=void 0,(p=exports.ChatMessageStatus||(exports.ChatMessageStatus={})).SENT="SENT",p.DELIVERED="DELIVERED",p.READ="READ",p.DELETED="DELETED",p.SCHEDULED="SCHEDULED",exports.ChatMessageType=void 0,(d=exports.ChatMessageType||(exports.ChatMessageType={})).SYSTEM="SYSTEM",d.USER="USER",d.ADMIN="ADMIN",exports.ChatMessageKind=void 0,(E=exports.ChatMessageKind||(exports.ChatMessageKind={})).PARENT="PARENT",E.THREAD="THREAD",E.POLL="POLL",E.STICKER="STICKER",E.GIF="GIF",E.HOP_SYSTEM="HOP_SYSTEM",E.HOP_RECORDING="HOP_RECORDING",E.HOP_VOTE="HOP_VOTE",E.HOP_MEETING="HOP_MEETING",E.CSAT="CSAT",exports.UserStatus=void 0,(m=exports.UserStatus||(exports.UserStatus={})).ACTIVE="ACTIVE",m.DISABLE="DISABLE",m.DEACTIVATE="DEACTIVATE",m.BLOCKED="BLOCKED",m.LEAVE="LEAVE",m.FULLY_CLOSED="FULLY_CLOSED",exports.UserConversationRole=void 0,(y=exports.UserConversationRole||(exports.UserConversationRole={})).SUPER_ADMIN="SUPER_ADMIN",y.ADMIN="ADMIN",y.MODERATOR="MODERATOR",y.MEMBER="MEMBER",exports.MessageChangeStatus=void 0,(T=exports.MessageChangeStatus||(exports.MessageChangeStatus={})).DELETE="DELETE",T.PIN="PIN",T.UNPIN="UNPIN",T.STARRED="STARRED",T.UNSTARRED="UNSTARRED",exports.ConnectionState=void 0,(g=exports.ConnectionState||(exports.ConnectionState={})).DISCONNECTED="DISCONNECTED",g.CONNECTING="CONNECTING",g.CONNECTED="CONNECTED",g.RECONNECTING="RECONNECTING",exports.AttachmentType=void 0,(C=exports.AttachmentType||(exports.AttachmentType={})).PHOTO="PHOTO",C.VIDEO="VIDEO",C.AUDIO="AUDIO",C.WORD="WORD",C.PDF="PDF",C.EXCEL="EXCEL",C.ZIP="ZIP",C.OTHER="OTHER",exports.PostType=void 0,(S=exports.PostType||(exports.PostType={})).STORY="STORY",S.POST="POST",S.PROMOTION="PROMOTION",exports.HopMode=void 0,(v=exports.HopMode||(exports.HopMode={})).NOW="NOW",v.CIRCLE="CIRCLE",v.MEETING="MEETING",exports.HopStatus=void 0,(O=exports.HopStatus||(exports.HopStatus={})).IDLE="IDLE",O.SCHEDULED="SCHEDULED",O.LIVE="LIVE",O.ENDED="ENDED",O.CANCELLED="CANCELLED",exports.WebhookStatus=void 0,(A=exports.WebhookStatus||(exports.WebhookStatus={})).ACTIVE="ACTIVE",A.DISABLED="DISABLED",exports.WebhookEvent=void 0,(b=exports.WebhookEvent||(exports.WebhookEvent={})).MESSAGE_SENT="message.sent",b.CONVERSATION_CREATED="conversation.created",b.USER_JOINED="user.joined",b.USER_LEFT="user.left",b.CONVERSATION_LOCKED="conversation.locked",b.CONVERSATION_UNLOCKED="conversation.unlocked",b.CSAT_SUBMITTED="csat.submitted";class f extends Error{constructor(t,e,n,r,s){super(t),this.statusCode=e,this.code=n,this.details=r,this.transport=s,this.name="LiveChattaError"}}class R{constructor(t,e,n){this.config=t,this.tokenManager=e,this.eventBus=n,this.maxRetries=2,this.timeout=3e4,this.ownerToken=t.ownerToken||null,this.memberToken=t.memberToken||null}setMemberToken(t){this.memberToken=t||null}hasMemberToken(){return!!this.memberToken}bearerFor(t){return"owner"===t?this.ownerToken:"member"===t?this.memberToken:"user"===t?this.memberToken||this.ownerToken:null}setOwnerToken(t){this.ownerToken=t||null}hasOwnerToken(){return!!this.ownerToken}buildHeaders(t="apiKey"){return"owner"===t||"member"===t||"user"===t?{"Content-Type":"application/json",Authorization:`Bearer ${this.bearerFor(t)}`}:"none"===t?{"Content-Type":"application/json"}:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"x-embed":"true"}}baseFor(t="external"){return"api"===t?this.config.apiUrl:"root"===t?this.config.rootUrl:this.config.externalUrl}buildQueryString(t){if(!t)return"";const e=Object.entries(t).filter(([,t])=>null!=t&&""!==t);return e.length?"?"+new URLSearchParams(e.map(([t,e])=>[t,String(e)])).toString():""}async request(t,e,n){return this._doRequest(t,e,n,!1)}async _doRequest(t,e,n,r){var s,o;const a=(null==n?void 0:n.auth)||"apiKey";if("owner"===a&&!this.ownerToken)throw new f("Owner token required — pass ownerToken to init() or call api().setOwnerToken()",401,"OWNER_TOKEN_REQUIRED");if(("member"===a||"user"===a)&&!this.bearerFor(a))throw new f("member"===a?"Member token required — pass memberToken to init() or call api().setMemberToken()":"Member or owner token required — call api().setMemberToken() or api().setOwnerToken()",401,"member"===a?"MEMBER_TOKEN_REQUIRED":"USER_TOKEN_REQUIRED");const i=`${this.baseFor(null==n?void 0:n.base)}${e}${this.buildQueryString(null==n?void 0:n.query)}`,h={...(null==n?void 0:n.headers)||{},...this.buildHeaders(a)},c=(null==n?void 0:n.noRetry)?0:this.maxRetries;let l=null;for(let u=0;u<=c;u++){const p=new AbortController,d=setTimeout(()=>p.abort(),this.timeout);try{const c={method:t,headers:h,signal:p.signal};(null==n?void 0:n.body)&&(c.body=JSON.stringify(n.body)),this.log(`${t} ${e}`);const u=await fetch(i,c);if(u.ok)return u.json();if(401===u.status&&"apiKey"===a&&!r&&this.tokenManager){clearTimeout(d);try{return await this.tokenManager.refresh(),this._doRequest(t,e,n,!0)}catch(t){throw null===(s=this.eventBus)||void 0===s||s.emit(exports.ChatEvent.AUTH_ERROR,{message:"Authentication failed after token refresh"}),new f("Unauthorized — token refresh failed",401,"AUTH_ERROR")}}if(u.status<500){const t=await u.json().catch(()=>({message:u.statusText}));401===u.status&&(null===(o=this.eventBus)||void 0===o||o.emit(exports.ChatEvent.AUTH_ERROR,{message:"Unauthorized"}));const e=401!==u.status&&403!==u.status||"apiKey"===a||"none"===a?void 0:"owner"===a?"OWNER_AUTH":"USER_AUTH";throw new f(t.message||`Request failed: ${u.status}`,u.status,_(t)||e,t)}const E=await u.json().catch(()=>({message:u.statusText}));l=new f(E.message||`Server error: ${u.status}`,u.status)}catch(t){if(t instanceof f&&t.statusCode<500)throw t;l="AbortError"===t.name?new f("Request timeout",408,"TIMEOUT"):t}finally{clearTimeout(d)}u<c&&await new Promise(t=>setTimeout(t,1e3*Math.pow(2,u)))}throw l||new Error("LiveChatta: Request failed")}get(t,e){return this.request("GET",t,{query:e})}post(t,e,n){return this.request("POST",t,{body:e,query:n})}put(t,e,n){return this.request("PUT",t,{body:e,query:n})}patch(t,e,n){return this.request("PATCH",t,{body:e,query:n})}delete(t,e){return this.request("DELETE",t,{query:e})}owner(t,e,n){return this.request(t,e,{...n,base:"api",auth:"owner"})}user(t,e,n){return this.request(t,e,{...n,base:"api",auth:(null==n?void 0:n.auth)||"user"})}urlFor(t,e,n){return`${this.baseFor(t)}${e}${this.buildQueryString(n)}`}log(t){this.config.debug&&console.log(`[LiveChatta HTTP] ${t}`)}}class x{constructor(t,e,n){this.config=t,this.tokenManager=e,this.eventBus=n,this.socket=null,this.state=exports.ConnectionState.DISCONNECTED,this.queue=[],this.reconnectAttempt=0,this.selfUserId=null}async connect(){var e;if(null===(e=this.socket)||void 0===e?void 0:e.connected)return;this.setState(exports.ConnectionState.CONNECTING);const n=await this.tokenManager.getToken(),r={linkCode:this.config.linkCode};return this.tokenManager.hasPublicKey?r.token=n:r.apiKey=n,this.config.chatUsername&&(r.chatUsername=this.config.chatUsername),this.config.linkCode&&(r.chatLinkCode=this.config.linkCode),this.socket=t.io(this.config.baseUrl,{query:r,auth:{token:`Bearer ${n}`},extraHeaders:{"x-api-key":this.config.apiKey,"x-embed":"true"},transports:["websocket"],reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,reconnectionAttempts:1/0}),this.setupLifecycleListeners(),new Promise((t,e)=>{let n=!1;const r=()=>{var t,e,n;null===(t=this.socket)||void 0===t||t.off("connect",o),null===(e=this.socket)||void 0===e||e.off(exports.ChatEvent.CHAT_ERROR,a),null===(n=this.socket)||void 0===n||n.off("connect_error",i)},s=setTimeout(()=>{n||(n=!0,r(),e(new Error("LiveChatta: Socket connection timeout")))},15e3),o=()=>{n||(n=!0,clearTimeout(s),r(),this.setState(exports.ConnectionState.CONNECTED),this.reconnectAttempt=0,this.log("Socket connected"),this.flushQueue(),t())},a=t=>{n||(n=!0,clearTimeout(s),r(),e(new Error((null==t?void 0:t.message)||"LiveChatta: Connection failed")))},i=t=>{n||(n=!0,clearTimeout(s),r(),e(t))};this.socket.on("connect",o),this.socket.on(exports.ChatEvent.CHAT_ERROR,a),this.socket.on("connect_error",i)})}getSelfUserId(){return this.selfUserId}disconnect(){this.selfUserId=null,this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,this.setState(exports.ConnectionState.DISCONNECTED),this.rejectQueue("LiveChatta: Socket disconnected before flush"),this.log("Socket disconnected"))}rejectQueue(t){if(!this.queue.length)return void(this.queue=[]);const e=this.queue;this.queue=[];for(const n of e)n.reject(new Error(t))}isConnected(){var t;return this.state===exports.ConnectionState.CONNECTED&&!!(null===(t=this.socket)||void 0===t?void 0:t.connected)}getState(){return this.state}emit(t,e){var n;return(null===(n=this.socket)||void 0===n?void 0:n.connected)?this.doEmit(t,e):this.queue.length>=x.MAX_QUEUE_SIZE?Promise.reject(new Error("LiveChatta: Emit queue full — socket disconnected, too many pending emits")):(this.log(`Queuing emit: ${t}`),new Promise((n,r)=>{this.queue.push({event:t,data:e,resolve:n,reject:r})}))}on(t,e){var n;null===(n=this.socket)||void 0===n||n.on(t,e)}off(t,e){var n,r;e?null===(n=this.socket)||void 0===n||n.off(t,e):null===(r=this.socket)||void 0===r||r.removeAllListeners(t)}getSocket(){return this.socket}doEmit(t,e){return new Promise((n,r)=>{var s;if(!(null===(s=this.socket)||void 0===s?void 0:s.connected))return r(new Error("LiveChatta: Socket not connected"));this.socket.emit(t,e,t=>{const e=function(t){const e=t&&"object"==typeof t?t.error:void 0;if(!e)return null;const n="object"==typeof e?e:null;let r=n?n.message:e;Array.isArray(r)&&(r=r.join(", "));const s=n&&"number"==typeof n.statusCode?n.statusCode:400;return new f("string"==typeof r&&r?r:"Request failed",s,_(n)||"SOCKET_ERROR",e,"socket")}(t);e?r(e):n(t)})})}setupLifecycleListeners(){this.socket&&(this.socket.on(exports.ChatEvent.ONLINE,t=>{var e;const n=(null==t?void 0:t.isSelfConnection)?null===(e=t.user)||void 0===e?void 0:e._id:void 0;"string"==typeof n&&n&&(this.selfUserId=n)}),this.socket.on("disconnect",t=>{this.log(`Socket disconnected: ${t}`),this.setState(exports.ConnectionState.DISCONNECTED),this.eventBus.emit(exports.SDKEvent.DISCONNECTED,{reason:t})}),this.socket.io.on("reconnect_attempt",t=>{this.reconnectAttempt=t,this.setState(exports.ConnectionState.RECONNECTING),this.log(`Reconnecting... attempt ${t}`),this.eventBus.emit(exports.SDKEvent.RECONNECTING,{attempt:t})}),this.socket.io.on("reconnect",t=>{this.setState(exports.ConnectionState.CONNECTED),this.reconnectAttempt=0,this.log(`Reconnected after ${t} attempts`),this.eventBus.emit(exports.SDKEvent.RECONNECTED,{attempt:t}),this.flushQueue()}),this.socket.io.on("reconnect_error",t=>{this.log(`Reconnect error: ${t.message}`),this.eventBus.emit(exports.SDKEvent.ERROR,{error:t,type:"reconnect"})}))}flushQueue(){if(!this.queue.length)return;this.log(`Flushing ${this.queue.length} queued emits`);const t=[...this.queue];this.queue=[],this.eventBus.emit(exports.SDKEvent.QUEUE_FLUSH,{count:t.length});for(const e of t)this.doEmit(e.event,e.data).then(e.resolve).catch(e.reject)}setState(t){this.state=t}log(t){this.config.debug&&console.log(`[LiveChatta] ${t}`)}}async function P(t,e,n,r){const s=await t.emit(e,n);return null==r||r(s),s}x.MAX_QUEUE_SIZE=100;class I{constructor(t,e){this.transport=t,this.eventBus=e}async getConversations(t,e){const n=await this.transport.emit(exports.ChatEvent.ALL_CONVERSATIONS,t||{});return null==e||e(n),n}async startConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.NEW_CONVERSATION,t);return null==e||e(n),n}async enterConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.ENTER_CONVERSATION,{conversationId:t});return null==e||e(n),n}async joinConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.JOIN_CONVERSATION,t);return null==e||e(n),n}async editConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.EDIT_CONVERSATION,t);return null==e||e(n),n}async pinConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.PIN_CONVERSATION,t);return null==e||e(n),n}async makeAdmin(t,e){const n=await this.transport.emit(exports.ChatEvent.MAKE_ADMIN_CONVERSATION,t);return null==e||e(n),n}async toggleLock(t,e){const n=await this.transport.emit(exports.ChatEvent.TOGGLE_CONVERSATION,t);return null==e||e(n),n}async changeConversationStatus(t,e){const n=await this.transport.emit(exports.ChatEvent.STATUS_CHANGE_CONVERSATION,t);return null==e||e(n),n}async changeMemberStatus(t,e){const n=await this.transport.emit(exports.ChatEvent.MEMBER_STATUS_CHANGE_CONVERSATION,t);return null==e||e(n),n}async getMessages(t,e){const n=await this.transport.emit(exports.ChatEvent.ALL_MESSAGES,t);return null==e||e(n),n}async sendMessage(t,e){const n=await this.transport.emit(exports.ChatEvent.NEW_MESSAGE,t);return null==e||e(n),n}async typing(t,e){const n=await this.transport.emit(exports.ChatEvent.NEW_TYPING,t);return null==e||e(n),n}async saveDraft(t,e){const n=await this.transport.emit(exports.ChatEvent.SAVE_DRAFT,t);return null==e||e(n),n}async setChatStatus(t,e){const n=await this.transport.emit(exports.ChatEvent.SET_STATUS,t);return null==e||e(n),n}async updateLiveLocation(t,e){const n=await this.transport.emit(exports.ChatEvent.UPDATE_LIVE_LOCATION,t);return null==e||e(n),n}async stopLiveLocation(t,e){const n=await this.transport.emit(exports.ChatEvent.STOP_LIVE_LOCATION,t);return null==e||e(n),n}async changeMessageStatus(t,e){const n=await this.transport.emit(exports.ChatEvent.MESSAGE_STATUS_CHANGE,t);return null==e||e(n),n}async reactToMessage(t,e){const n=await this.transport.emit(exports.ChatEvent.MESSAGE_REACTION,t);return null==e||e(n),n}async editMessage(t,e){var n,r,s;const o=null!==(n=t.senderId)&&void 0!==n?n:null===(s=(r=this.transport).getSelfUserId)||void 0===s?void 0:s.call(r),a=await this.transport.emit(exports.ChatEvent.EDIT_MESSAGE,o?{...t,senderId:o}:t);return null==e||e(a),a}async forwardMessage(t,e){const n=t,{conversationId:r,targetConversationId:s,...o}=n,a={...o,fromConversationId:n.fromConversationId||r,toConversationId:n.toConversationId||s},i=await this.transport.emit(exports.ChatEvent.FORWARD_MESSAGE,a);return null==e||e(i),i}async forwardPost(t,e){const n=await this.transport.emit(exports.ChatEvent.FORWARD_POST,t);return null==e||e(n),n}async markMessagesRead(t,e){const n=await this.transport.emit(exports.ChatEvent.MESSAGE_READ,t);return null==e||e(n),n}async searchMessages(t,e){const n=await this.transport.emit(exports.ChatEvent.SEARCH_MESSAGES,t);return null==e||e(n),n}async searchChatUsers(t,e){const n=await this.transport.emit(exports.ChatEvent.SEARCH_CHAT_USERS,t);return null==e||e(n),n}async getThreadMessages(t,e){const n=await this.transport.emit(exports.ChatEvent.THREAD_MESSAGES,t);return null==e||e(n),n}async toggleBookmark(t,e){const n=await this.transport.emit(exports.ChatEvent.TOGGLE_BOOKMARK,t);return null==e||e(n),n}async getBookmarks(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_BOOKMARKS,t);return null==e||e(n),n}async getAllBookmarks(t={},e){const n=await this.transport.emit(exports.ChatEvent.GET_ALL_BOOKMARKS,t);return null==e||e(n),n}async votePoll(t,e){const n=await this.transport.emit(exports.ChatEvent.VOTE_POLL,t);return null==e||e(n),n}async validatePassword(t,e){const n=await this.transport.emit(exports.ChatEvent.VALIDATE_PASSWORD,t);return null==e||e(n),n}async forgotPassword(t,e){const n=await this.transport.emit(exports.ChatEvent.FORGOT_PASSWORD,t);return null==e||e(n),n}async resetPassword(t,e){const n=await this.transport.emit(exports.ChatEvent.RESET_PASSWORD,t);return null==e||e(n),n}async changePassword(t,e){const n=await this.transport.emit(exports.ChatEvent.CHANGE_PASSWORD,t);return null==e||e(n),n}async refreshToken(t,e){const n=await this.transport.emit(exports.ChatEvent.REFRESH_TOKEN,t);return null==e||e(n),n}async revokeToken(t,e){const n=await this.transport.emit(exports.ChatEvent.REVOKE_TOKEN,t);return null==e||e(n),n}async createPost(t,e){const n=!t.cta&&t.ctaLabel&&t.ctaUrl?{...t,cta:{label:t.ctaLabel,url:t.ctaUrl}}:t,r=await this.transport.emit(exports.ChatEvent.CREATE_POST,n);return null==e||e(r),r}async getPosts(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_POSTS,t||{});return null==e||e(n),n}async getStories(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_STORIES,t||{});return null==e||e(n),n}async viewPost(t,e){const n=await this.transport.emit(exports.ChatEvent.VIEW_POST,t);return null==e||e(n),n}async reactToPost(t,e){const n=await this.transport.emit(exports.ChatEvent.REACT_TO_POST,t);return null==e||e(n),n}async replyToPost(t,e){const n=await this.transport.emit(exports.ChatEvent.REPLY_TO_POST,t);return null==e||e(n),n}async updatePost(t,e){const n=await this.transport.emit(exports.ChatEvent.UPDATE_POST,t);return null==e||e(n),n}async deletePost(t,e){const n=await this.transport.emit(exports.ChatEvent.DELETE_POST,t);return null==e||e(n),n}async getPostMessages(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_POST_MESSAGES,t);return null==e||e(n),n}async getAllThreads(t,e){const n=await this.transport.emit(exports.ChatEvent.ALL_THREADS,t||{});return null==e||e(n),n}async getConversationMembers(t,e){const n=await this.transport.emit(exports.ChatEvent.CONVERSATION_MEMBERS,t);return null==e||e(n),n}async getLinkHandles(t){const e=await this.transport.emit(exports.ChatEvent.LINK_HANDLES,{});return null==t||t(e),e}async startHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_START,t);return null==e||e(n),n}async startHopAdHoc(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_AD_HOC_START,t);return null==e||e(n),n}async joinHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_JOIN,t);return null==e||e(n),n}async connectHopTransport(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_CONNECT_TRANSPORT,t);return null==e||e(n),n}async hopProduce(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_PRODUCE,t);return null==e||e(n),n}async hopConsume(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_CONSUME,t);return null==e||e(n),n}async resumeHopConsumer(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_RESUME_CONSUMER,t);return null==e||e(n),n}async leaveHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_LEAVE,t);return null==e||e(n),n}async endHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_END,t);return null==e||e(n),n}async inviteToHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_INVITE_REQUEST,t);return null==e||e(n),n}async getHopSession(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_GET_SESSION,t);return null==e||e(n),n}async startHopRecording(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_RECORDING_START,t);return null==e||e(n),n}async stopHopRecording(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_RECORDING_STOP,t);return null==e||e(n),n}async scheduleHopMeeting(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_MEETING_CREATE,t);return null==e||e(n),n}async cancelHopMeeting(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_MEETING_CANCEL,t);return null==e||e(n),n}async listHopMeetings(t={},e){const n=await this.transport.emit(exports.ChatEvent.HOP_MEETING_LIST,t);return null==e||e(n),n}async listHopProducers(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_LIST_PRODUCERS,t);return null==e||e(n),n}async listHopParticipants(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_LIST_PARTICIPANTS,t);return null==e||e(n),n}async muteHopParticipant(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_MUTE_PARTICIPANT,t);return null==e||e(n),n}async dropHopParticipant(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_DROP_PARTICIPANT,t);return null==e||e(n),n}async hopPinForAll(t,e){return P(this.transport,exports.ChatEvent.HOP_PIN_FOR_ALL,t,e)}async listActiveHops(t){const e=await this.transport.emit(exports.ChatEvent.HOP_LIST_ACTIVE,{});return null==t||t(e),e}async sendHopReaction(t){return this.transport.emit(exports.ChatEvent.HOP_REACTION,t)}async keepHopWaiting(t){return this.transport.emit(exports.ChatEvent.HOP_KEEP_WAITING,t)}async sendHopVote(t){return this.transport.emit(exports.ChatEvent.HOP_VOTE,t)}async raiseHand(t){return this.transport.emit(exports.ChatEvent.HOP_RAISE_HAND,t)}async startNewVoteRound(t){return this.transport.emit(exports.ChatEvent.HOP_NEW_VOTE_ROUND,t)}async makeHost(t){return this.transport.emit(exports.ChatEvent.HOP_MAKE_HOST,t)}async stopHopScreenShare(t){return this.transport.emit(exports.ChatEvent.HOP_SCREENSHARE_STOP,t)}async startHopScreenShare(t){return this.transport.emit(exports.ChatEvent.HOP_SCREENSHARE_START,t)}async hopMediaChange(t){return this.transport.emit(exports.ChatEvent.HOP_MEDIA_CHANGE,t)}async hopInviteDecline(t){return this.transport.emit(exports.ChatEvent.HOP_INVITE_DECLINE,t)}async rejoinHop(t){return this.transport.emit(exports.ChatEvent.HOP_REJOIN_ROOM,t)}async restartHopIce(t){return this.transport.emit(exports.ChatEvent.HOP_ICE_RESTART,t)}async hopAdmit(t){return this.transport.emit(exports.ChatEvent.HOP_ADMIT,t)}async translateMessage(t,e){const n=await this.transport.emit(exports.ChatEvent.TRANSLATE_MESSAGE,t);return null==e||e(n),n}async setLanguage(t,e){const n=await this.transport.emit(exports.ChatEvent.SET_LANGUAGE,t);return null==e||e(n),n}async getOnlineUsers(t,e){const n=await this.transport.emit(exports.ChatEvent.ONLINE_USERS,t);return null==e||e(n),n}async heartbeat(t){await this.transport.emit(exports.ChatEvent.HEARTBEAT,"boolean"==typeof(null==t?void 0:t.visible)?{visible:t.visible}:{})}async messageDelivered(t,e){return P(this.transport,exports.ChatEvent.MESSAGE_DELIVERED,t,e)}async messageInfo(t,e){return P(this.transport,exports.ChatEvent.MESSAGE_INFO,t,e)}async muteConversation(t,e){return P(this.transport,exports.ChatEvent.MUTE_CONVERSATION,t,e)}async updateQuietHours(t,e){return P(this.transport,exports.ChatEvent.UPDATE_QUIET_HOURS,t,e)}async setMessageReminder(t,e){return P(this.transport,exports.ChatEvent.SET_MESSAGE_REMINDER,t,e)}async cancelMessageReminder(t,e){return P(this.transport,exports.ChatEvent.CANCEL_MESSAGE_REMINDER,{reminderId:t},e)}async updateConversationPermissions(t,e){return P(this.transport,exports.ChatEvent.UPDATE_CONVERSATION_PERMISSIONS,t,e)}async huddleStart(t,e){return P(this.transport,exports.ChatEvent.HUDDLE_START,t,e)}async huddleStatus(t,e){return P(this.transport,exports.ChatEvent.HUDDLE_STATUS,{conversationId:t},e)}async huddleEnd(t,e){return P(this.transport,exports.ChatEvent.HUDDLE_END,{conversationId:t},e)}async transcribeMessage(t,e){return P(this.transport,exports.ChatEvent.TRANSCRIBE_MESSAGE,t,e)}async conversationRead(t,e){return P(this.transport,exports.ChatEvent.CONVERSATION_READ,{conversationId:t},e)}async conversationUnread(t,e,n){return P(this.transport,exports.ChatEvent.CONVERSATION_UNREAD,{conversationId:t,messageId:e},n)}async getUnreadTotals(t={},e){return P(this.transport,exports.ChatEvent.UNREAD_TOTALS,t,e)}async deleteMessage(t,e){return P(this.transport,exports.ChatEvent.DELETE_MESSAGE,t,e)}async searchAll(t,e){return P(this.transport,exports.ChatEvent.SEARCH_ALL,t,e)}async submitPreChat(t,e){return P(this.transport,exports.ChatEvent.SUBMIT_PRE_CHAT,t,e)}async hopPollClose(t,e){return P(this.transport,exports.ChatEvent.HOP_POLL_CLOSE,t,e)}async hopCollabState(t,e){return P(this.transport,exports.ChatEvent.HOP_COLLAB_STATE,{sessionId:t},e)}async hopCaptionsToggle(t,e){return P(this.transport,exports.ChatEvent.HOP_CAPTIONS_TOGGLE,t,e)}async hopCaption(t,e){return P(this.transport,exports.ChatEvent.HOP_CAPTION,t,e)}async hopRecordingList(t,e){return P(this.transport,exports.ChatEvent.HOP_RECORDING_LIST,t,e)}async stickersMine(t){return P(this.transport,exports.ChatEvent.STICKERS_MINE,{},t)}async stickersSearch(t={},e){return P(this.transport,exports.ChatEvent.STICKERS_SEARCH,t,e)}async stickerUpload(t,e){return P(this.transport,exports.ChatEvent.STICKER_UPLOAD,t,e)}async stickerAdd(t,e){return P(this.transport,exports.ChatEvent.STICKER_ADD,t,e)}async stickerRemove(t,e){return P(this.transport,exports.ChatEvent.STICKER_REMOVE,t,e)}async chattaMoneyConfirm(t,e){return P(this.transport,exports.ChatEvent.CHATTA_MONEY_CONFIRM,t,e)}async getMoneyCard(t,e){return P(this.transport,exports.ChatEvent.MONEY_CARD_GET,t,e)}async moneyCardAction(t,e){return P(this.transport,exports.ChatEvent.MONEY_CARD_ACTION,t,e)}async webinarQaAnswerLive(t,e){return P(this.transport,exports.ChatEvent.WEBINAR_QA_ANSWER_LIVE,t,e)}async webinarQaVote(t,e){return P(this.transport,exports.ChatEvent.WEBINAR_QA_VOTE,t,e)}onMessage(t){return this.transport.on(exports.ChatEvent.NEW_MESSAGE,t),this}onConversation(t){return this.transport.on(exports.ChatEvent.NEW_CONVERSATION,t),this}onEditConversation(t){return this.transport.on(exports.ChatEvent.EDIT_CONVERSATION,t),this}onMakeAdmin(t){return this.transport.on(exports.ChatEvent.MAKE_ADMIN_CONVERSATION,t),this}onMemberStatusChange(t){return this.transport.on(exports.ChatEvent.MEMBER_STATUS_CHANGE_CONVERSATION,t),this}onToggleConversation(t){return this.transport.on(exports.ChatEvent.TOGGLE_CONVERSATION,t),this}onStatusChangeConversation(t){return this.transport.on(exports.ChatEvent.STATUS_CHANGE_CONVERSATION,t),this}onPinConversation(t){return this.transport.on(exports.ChatEvent.PIN_CONVERSATION,t),this}onLinkUserJoined(t){return this.transport.on(exports.ChatEvent.LINK_USER_JOINED,t),this}onLinkUserUpdated(t){return this.transport.on(exports.ChatEvent.LINK_USER_UPDATED,t),this}onMessageStatusChange(t){return this.transport.on(exports.ChatEvent.MESSAGE_STATUS_CHANGE,t),this}onMessageReaction(t){return this.transport.on(exports.ChatEvent.MESSAGE_REACTION,t),this}onTyping(t){return this.transport.on(exports.ChatEvent.NEW_TYPING,t),this}onDraftUpdated(t){return this.transport.on(exports.ChatEvent.DRAFT_UPDATED,t),this}onStatusUpdated(t){return this.transport.on(exports.ChatEvent.STATUS_UPDATED,t),this}onLiveLocationUpdated(t){return this.transport.on(exports.ChatEvent.LIVE_LOCATION_UPDATED,t),this}onLiveLocationEnded(t){return this.transport.on(exports.ChatEvent.LIVE_LOCATION_ENDED,t),this}onOnline(t){return this.transport.on(exports.ChatEvent.ONLINE,t),this}onOffline(t){return this.transport.on(exports.ChatEvent.OFFLINE,t),this}onJoinConversation(t){return this.transport.on(exports.ChatEvent.JOIN_CONVERSATION,t),this}onUnreadCountUpdate(t){return this.transport.on(exports.ChatEvent.UNREAD_COUNT_UPDATE,t),this}onMembershipRevoked(t){return this.transport.on(exports.ChatEvent.MEMBERSHIP_REVOKED,t),this}onSharedChannelInvite(t){return this.transport.on(exports.ChatEvent.SHARED_CHANNEL_INVITE,t),this}onSharedChannelUpdated(t){return this.transport.on(exports.ChatEvent.SHARED_CHANNEL_UPDATED,t),this}onNotification(t){return this.transport.on(exports.ChatEvent.NOTIFICATION,t),this}onEditMessage(t){return this.transport.on(exports.ChatEvent.EDIT_MESSAGE,t),this}onForwardMessage(t){return this.transport.on(exports.ChatEvent.FORWARD_MESSAGE,t),this}onMessageRead(t){return this.transport.on(exports.ChatEvent.MESSAGE_READ,t),this}onScheduledMessage(t){return this.transport.on(exports.ChatEvent.SCHEDULED_MESSAGE,t),this}onMessageFailed(t){return this.transport.on(exports.ChatEvent.MESSAGE_FAILED,t),this}onVotePoll(t){return this.transport.on(exports.ChatEvent.VOTE_POLL,t),this}onError(t){return this.transport.on(exports.ChatEvent.CHAT_ERROR,t),this}onAuthError(t){return this.transport.on(exports.ChatEvent.AUTH_ERROR,t),this}onCreatePost(t){return this.transport.on(exports.ChatEvent.CREATE_POST,t),this}onNewStory(t){return this.transport.on(exports.ChatEvent.NEW_STORY,t),this}onUpdatePost(t){return this.transport.on(exports.ChatEvent.UPDATE_POST,t),this}onDeletePost(t){return this.transport.on(exports.ChatEvent.DELETE_POST,t),this}onReactToPost(t){return this.transport.on(exports.ChatEvent.REACT_TO_POST,t),this}onReplyToPost(t){return this.transport.on(exports.ChatEvent.REPLY_TO_POST,t),this}onTranslateMessage(t){return this.transport.on(exports.ChatEvent.TRANSLATE_MESSAGE,t),this}onAiCreditsUpdated(t){return this.transport.on(exports.ChatEvent.AI_CREDITS_UPDATED,t),this}onAiCreditsExhausted(t){return this.transport.on(exports.ChatEvent.AI_CREDITS_EXHAUSTED,t),this}onHopAdmitted(t){return this.transport.on(exports.ChatEvent.HOP_ADMITTED,t),this}onHopReaction(t){return this.transport.on(exports.ChatEvent.HOP_REACTION,t),this}onHopVoteUpdated(t){return this.transport.on(exports.ChatEvent.HOP_VOTE_UPDATED,t),this}onHopVoteComplete(t){return this.transport.on(exports.ChatEvent.HOP_VOTE_COMPLETE,t),this}onHopNewVoteRound(t){return this.transport.on(exports.ChatEvent.HOP_NEW_VOTE_ROUND,t),this}onHopRaiseHand(t){return this.transport.on(exports.ChatEvent.HOP_RAISE_HAND,t),this}onHopHostChanged(t){return this.transport.on(exports.ChatEvent.HOP_HOST_CHANGED,t),this}onHopStarted(t){return this.transport.on(exports.ChatEvent.HOP_STARTED,t),this}onHopEnded(t){return this.transport.on(exports.ChatEvent.HOP_ENDED,t),this}onHopParticipantJoined(t){return this.transport.on(exports.ChatEvent.HOP_PARTICIPANT_JOINED,t),this}onHopParticipantLeft(t){return this.transport.on(exports.ChatEvent.HOP_PARTICIPANT_LEFT,t),this}onHopInvite(t){return this.transport.on(exports.ChatEvent.HOP_INVITE,t),this}onHopLobbyWaiting(t){return this.transport.on(exports.ChatEvent.HOP_LOBBY_WAITING,t),this}onHopDenied(t){return this.transport.on(exports.ChatEvent.HOP_DENIED,t),this}onHopRedirect(t){return this.transport.on(exports.ChatEvent.HOP_REDIRECT,t),this}onHopRecordingStarted(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_STARTED,t),this}onHopRecordingStopped(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_STOPPED,t),this}onHopRecordingReady(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_READY,t),this}onHopRecordingAlreadyActive(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_ALREADY_ACTIVE,t),this}onHopParticipantMuted(t){return this.transport.on(exports.ChatEvent.HOP_PARTICIPANT_MUTED,t),this}onHopPinnedForAll(t){return this.transport.on(exports.ChatEvent.HOP_PINNED_FOR_ALL,t),this}onHopParticipantDropped(t){return this.transport.on(exports.ChatEvent.HOP_PARTICIPANT_DROPPED,t),this}onHopYouWereDropped(t){return this.transport.on(exports.ChatEvent.HOP_YOU_WERE_DROPPED,t),this}onHopInviteAnswered(t){return this.transport.on(exports.ChatEvent.HOP_INVITE_ANSWERED,t),this}onHopUnmuteRequested(t){return this.transport.on(exports.ChatEvent.HOP_UNMUTE_REQUESTED,t),this}onHopMeetingReminder(t){return this.transport.on(exports.ChatEvent.HOP_MEETING_REMINDER,t),this}onHopVote(t){return this.transport.on(exports.ChatEvent.HOP_VOTE,t),this}onHopNewProducer(t){return this.transport.on(exports.ChatEvent.HOP_NEW_PRODUCER,t),this}onHopProducerClosed(t){return this.transport.on(exports.ChatEvent.HOP_PRODUCER_CLOSED,t),this}hopDeny(t,e,n){return this.transport.emit(exports.ChatEvent.HOP_DENY,{sessionId:t,userId:e,...n?{block:!0}:{}}),this}onHopInviteDeclined(t){return this.transport.on(exports.ChatEvent.HOP_INVITE_DECLINED,t),this}onHopScreenshareStarted(t){return this.transport.on(exports.ChatEvent.HOP_SCREENSHARE_STARTED,t),this}onHopMediaChanged(t){return this.transport.on(exports.ChatEvent.HOP_MEDIA_CHANGED,t),this}onHopTransportParams(t){return this.transport.on(exports.ChatEvent.HOP_TRANSPORT_PARAMS,t),this}onHopRecordingForbidden(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_FORBIDDEN,t),this}hopScreenshareStart(t){return this.transport.emit(exports.ChatEvent.HOP_SCREENSHARE_START,t),this}hopCoHostAssign(t){return this.transport.emit(exports.ChatEvent.HOP_CO_HOST_ASSIGN,t),this}onHopCoHostAssigned(t){return this.transport.on(exports.ChatEvent.HOP_CO_HOST_ASSIGNED,t),this}hopPollLaunch(t){return this.transport.emit(exports.ChatEvent.HOP_POLL_LAUNCH,t),this}onHopPollLaunched(t){return this.transport.on(exports.ChatEvent.HOP_POLL_LAUNCHED,t),this}hopPollVote(t){return this.transport.emit(exports.ChatEvent.HOP_POLL_VOTE,t),this}onHopPollVoteUpdated(t){return this.transport.on(exports.ChatEvent.HOP_POLL_VOTE_UPDATED,t),this}hopWhiteboardSync(t){return this.transport.emit(exports.ChatEvent.HOP_WHITEBOARD_SYNC,t),this}onHopWhiteboardDelta(t){return this.transport.on(exports.ChatEvent.HOP_WHITEBOARD_DELTA,t),this}openWhiteboard(t,e){return this.transport.emit(exports.ChatEvent.WHITEBOARD_OPEN,{conversationId:t,...e?{chatLinkId:e}:{}}),this}sendWhiteboardStroke(t){return this.transport.emit(exports.ChatEvent.WHITEBOARD_STROKE,t),this}clearWhiteboard(t,e){return this.transport.emit(exports.ChatEvent.WHITEBOARD_CLEAR,{conversationId:t,...e?{whiteboardId:e}:{}}),this}closeWhiteboard(t,e){return this.transport.emit(exports.ChatEvent.WHITEBOARD_CLOSE,{conversationId:t,...e?{whiteboardId:e}:{}}),this}snapshotWhiteboard(t){return this.transport.emit(exports.ChatEvent.WHITEBOARD_SNAPSHOT,t),this}onWhiteboardStroke(t){return this.transport.on(exports.ChatEvent.WHITEBOARD_STROKE,t),this}onWhiteboardCleared(t){return this.transport.on(exports.ChatEvent.WHITEBOARD_CLEAR,t),this}onWhiteboardClosed(t){return this.transport.on(exports.ChatEvent.WHITEBOARD_CLOSE,t),this}onWhiteboardSnapshot(t){return this.transport.on(exports.ChatEvent.WHITEBOARD_SNAPSHOT,t),this}async createAutomation(t,e){const n=await this.transport.emit(exports.ChatEvent.CREATE_AUTOMATION,t);return null==e||e(n),n}async updateAutomation(t,e){const n=await this.transport.emit(exports.ChatEvent.UPDATE_AUTOMATION,t);return null==e||e(n),n}async deleteAutomation(t,e){const n=await this.transport.emit(exports.ChatEvent.DELETE_AUTOMATION,t);return null==e||e(n),n}async getAutomations(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_AUTOMATIONS,t);return null==e||e(n),n}async startWebinar(t,e){const n=await this.transport.emit(exports.ChatEvent.START_WEBINAR,t);return null==e||e(n),n}raiseHandWebinar(t){return this.transport.emit(exports.ChatEvent.RAISE_HAND,t),this}lowerHand(t){return this.transport.emit(exports.ChatEvent.LOWER_HAND,t),this}async promoteAttendeeAudio(t,e){const n=await this.transport.emit(exports.ChatEvent.PROMOTE_ATTENDEE_AUDIO,t);return null==e||e(n),n}async submitWebinarQa(t,e){const n=await this.transport.emit(exports.ChatEvent.WEBINAR_QA_SUBMIT,t);return null==e||e(n),n}async answerWebinarQa(t,e){const n=await this.transport.emit(exports.ChatEvent.WEBINAR_QA_ANSWER,t);return null==e||e(n),n}onCallLogged(t){return this.transport.on(exports.ChatEvent.CALL_LOGGED,t),this}onChattaMoneyCard(t){return this.transport.on(exports.ChatEvent.CHATTA_MONEY_CARD,t),this}onMoneyCardUpdate(t){return this.transport.on(exports.ChatEvent.MONEY_CARD_UPDATE,t),this}onLinkSettingsUpdated(t){return this.transport.on(exports.ChatEvent.LINK_SETTINGS_UPDATED,t),this}onWebinarViewerCount(t){return this.transport.on(exports.ChatEvent.WEBINAR_VIEWER_COUNT,t),this}onWebinarStarted(t){return this.transport.on(exports.ChatEvent.WEBINAR_STARTED,t),this}onWebinarRaisedHand(t){return this.transport.on(exports.ChatEvent.WEBINAR_HAND_RAISED,t),this}onWebinarHandLowered(t){return this.transport.on(exports.ChatEvent.WEBINAR_HAND_LOWERED,t),this}onWebinarAttendeePromoted(t){return this.transport.on(exports.ChatEvent.WEBINAR_ATTENDEE_PROMOTED,t),this}onWebinarQaSubmitted(t){return this.transport.on(exports.ChatEvent.WEBINAR_QA_UPDATED,t),this}async getConversationStats(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_CONVERSATION_STATS,{conversationId:t});return null==e||e(n),n}onConversationStats(t){return this.transport.on(exports.ChatEvent.GET_CONVERSATION_STATS,t),this}async updateChatUserSettings(t,e){const n=await this.transport.emit(exports.ChatEvent.UPDATE_CHAT_USER_SETTINGS,t);return null==e||e(n),n}onConnect(t){return this.eventBus.on(exports.SDKEvent.CONNECTED,t),this}onDisconnect(t){return this.eventBus.on(exports.SDKEvent.DISCONNECTED,t),this}onReconnect(t){return this.eventBus.on(exports.SDKEvent.RECONNECTED,t),this}onReconnecting(t){return this.eventBus.on(exports.SDKEvent.RECONNECTING,t),this}off(t,e){return this.transport.off(t,e),this}onMessageDelivered(t){return this.transport.on(exports.ChatEvent.MESSAGE_DELIVERED,t),this}onConversationMuted(t){return this.transport.on(exports.ChatEvent.CONVERSATION_MUTED,t),this}onQuietHoursUpdated(t){return this.transport.on(exports.ChatEvent.QUIET_HOURS_UPDATED,t),this}onMessageRemindersChanged(t){return this.transport.on(exports.ChatEvent.MESSAGE_REMINDERS_CHANGED,t),this}onMessageReminderDue(t){return this.transport.on(exports.ChatEvent.MESSAGE_REMINDER_DUE,t),this}onConversationPermissionsUpdated(t){return this.transport.on(exports.ChatEvent.CONVERSATION_PERMISSIONS_UPDATED,t),this}onHopMeetingUpdated(t){return this.transport.on(exports.ChatEvent.HOP_MEETING_UPDATED,t),this}onHuddleUpdated(t){return this.transport.on(exports.ChatEvent.HUDDLE_UPDATED,t),this}onMessageTranscriptUpdated(t){return this.transport.on(exports.ChatEvent.MESSAGE_TRANSCRIPT_UPDATED,t),this}onInboxUpdated(t){return this.transport.on(exports.ChatEvent.INBOX_UPDATED,t),this}onInternalNote(t){return this.transport.on(exports.ChatEvent.INTERNAL_NOTE,t),this}onInternalNoteDeleted(t){return this.transport.on(exports.ChatEvent.INTERNAL_NOTE_DELETED,t),this}onConversationNotesUpdated(t){return this.transport.on(exports.ChatEvent.CONVERSATION_NOTES_UPDATED,t),this}onCsatUpdated(t){return this.transport.on(exports.ChatEvent.CSAT_UPDATED,t),this}onThreadUpdate(t){return this.transport.on(exports.ChatEvent.THREAD_MESSAGES,t),this}onConversationUnread(t){return this.transport.on(exports.ChatEvent.CONVERSATION_UNREAD,t),this}onConversationRead(t){return this.transport.on(exports.ChatEvent.CONVERSATION_READ,t),this}onMessageDeleted(t){return this.transport.on(exports.ChatEvent.MESSAGE_DELETED,t),this}onPreChatSubmitted(t){return this.transport.on(exports.ChatEvent.PRE_CHAT_SUBMITTED,t),this}onHopCaptionsState(t){return this.transport.on(exports.ChatEvent.HOP_CAPTIONS_STATE,t),this}onHopCaptionText(t){return this.transport.on(exports.ChatEvent.HOP_CAPTION_TEXT,t),this}}const w=encodeURIComponent,N=({limit:t,...e})=>({...e,...void 0!==t?{limit:String(t)}:{}});function L(t){if(!t)return;const{limit:e,...n}=t;return{...n,...void 0!==e?{limit:String(e)}:{}}}function D(t){if(t)return{...t,limit:void 0!==t.limit?String(t.limit):void 0}}function k(t){if(!t)return;const e={};return t.q&&(e.q=t.q),t.nextCursor&&(e.nextCursor=t.nextCursor),t.source&&(e.source=t.source),e}function M(t){const e={};for(const[n,r]of Object.entries(t))r&&(e[n]=r);return e}function H(t){const{handles:e,...n}=t||{};return{...n,handles:Array.isArray(e)?e.join(","):e}}const U=(t,e)=>`/chat-users/links/${w(t)}/members/${w(e)}/follow`,G=/^[A-Za-z0-9_-]{8,64}$/,$=(t,e)=>`/chats/conversations/${w(t)}/messages/${w(e)}`,F=t=>`/chats/agent-inbox/${w(t)}`;class W{constructor(t){this.transport=t}setOwnerToken(t){this.transport.setOwnerToken(t)}setMemberToken(t){this.transport.setMemberToken(t)}async registerMembers(t){return this.transport.post("/members",t)}async registerMember(t){const e=await this.transport.post("/members/single",t);return Array.isArray(e)?e[0]:e}async listMembers(t){return this.transport.get("/members",t)}async getMember(t){return this.transport.get(`/members/${t}`)}async createChatLink(t){return this.transport.post("/chat-links",t)}async listChatLinks(t){return this.transport.get("/chat-links",t)}async getChatLink(t){return this.transport.get(`/chat-links/${t}`)}async updateChatLink(t,e){return this.transport.patch(`/chat-links/${t}`,e)}async createConversation(t,e){return this.transport.post(`/chat-links/${t}/conversations`,e)}async listPublicConversations(t,e){return this.transport.get(`/public/${t}/conversations`,e)}async getMemberConversations(t,e){return this.transport.get(`/members/${t}/conversations`,e)}async getConversationUsers(t,e){return this.transport.get(`/conversations/${t}/users`,e)}async getMessages(t,e,n){return this.transport.get(`/members/${t}/conversations/${e}/messages`,n)}async sendMessage(t){return this.transport.post("/chats/messages/send",t)}async listSentMessages(t){const{conversationId:e,...n}=t||{};return this.transport.get("/chats/messages",{...n,...e?{chatMessageByConversationIds:e}:{}})}async cancelScheduledMessage(t,e){return this.transport.request("DELETE",`/chats/messages/${t}`,{body:{conversationId:e}})}async rescheduleMessage(t,e,n){return this.transport.patch(`/chats/messages/${t}`,{scheduledAt:n,conversationId:e})}async sendPushNotification(t){return this.transport.post("/chats/push-notification",t)}async exportChat(t){return this.transport.post("/chats/exports",t)}async getExports(t){return this.transport.get("/chats/exports",t)}async getCannedResponses(){return this.transport.get("/chats/canned-responses")}async createCannedResponse(t){return this.transport.post("/chats/canned-responses",t)}async updateCannedResponse(t,e){return this.transport.patch(`/chats/canned-responses/${t}`,e)}async deleteCannedResponse(t){return this.transport.delete(`/chats/canned-responses/${t}`)}async markCannedResponseUsed(t){return this.transport.post(`/chats/canned-responses/${encodeURIComponent(t)}/used`,{})}async getWebhooks(t){return this.transport.get("/chats/webhooks",t)}async getWebhook(t){return this.transport.get(`/chats/webhooks/${t}`)}async createWebhook(t){return this.transport.post("/chats/webhooks",t)}async updateWebhook(t,e){return this.transport.patch(`/chats/webhooks/${t}`,e)}async deleteWebhook(t){return this.transport.delete(`/chats/webhooks/${t}`)}async testWebhook(t){return this.transport.post(`/chats/webhooks/${w(t)}/test`)}async testAutomationKeywords(t,e){return this.transport.owner("POST","/chats/automations/test",{body:{chatLinkId:t,keywords:e}})}async testWebhookAsOwner(t){return this.transport.owner("POST",`/chats/webhooks/${w(t)}/test`)}async getWebhookDeliveries(t,e){return this.transport.owner("GET",`/chats/webhooks/${w(t)}/deliveries`,{query:void 0!==(null==e?void 0:e.limit)?{limit:String(e.limit)}:void 0})}async retryWebhookDelivery(t,e){return this.transport.owner("POST",`/chats/webhooks/${w(t)}/deliveries/${w(e)}/retry`,{noRetry:!0})}async rotateWebhookSecret(t){return this.transport.owner("POST",`/chats/webhooks/${w(t)}/rotate-secret`,{noRetry:!0})}async startWebhookCapture(t){return this.transport.owner("POST",`/chats/webhooks/${w(t)}/capture`,{noRetry:!0})}async readWebhookCapture(t,e=0){return this.transport.owner("GET",`/chats/webhooks/${w(t)}/capture`,{query:{after:String(e)}})}async stopWebhookCapture(t){return this.transport.owner("DELETE",`/chats/webhooks/${w(t)}/capture`,{noRetry:!0})}async listIncomingWebhooks(t,e){const n=e?{...e.status?{status:e.status}:{},...e.nextCursor?{nextCursor:e.nextCursor}:{},...void 0!==e.limit?{limit:String(e.limit)}:{}}:void 0;return this.transport.get(`/chats/conversations/${w(t)}/incoming-webhooks`,n)}async createIncomingWebhook(t,e){return this.transport.request("POST",`/chats/conversations/${w(t)}/incoming-webhooks`,{body:e,noRetry:!0})}async updateIncomingWebhook(t,e,n){return this.transport.request("PATCH",`/chats/conversations/${w(t)}/incoming-webhooks/${w(e)}`,{body:n,noRetry:!0})}async regenerateIncomingWebhook(t,e){return this.transport.request("POST",`/chats/conversations/${w(t)}/incoming-webhooks/${w(e)}/regenerate`,{body:{},noRetry:!0})}async revokeIncomingWebhook(t,e){return this.transport.request("DELETE",`/chats/conversations/${w(t)}/incoming-webhooks/${w(e)}`,{noRetry:!0})}async listMeetings(t){return this.transport.owner("GET","/hops/owner/meetings",{query:N(t)})}async scheduleMeeting(t,e){const n=null==e?void 0:e.idempotencyKey;return this.transport.owner("POST","/hops/owner/meetings",{body:t,noRetry:!n,...n?{headers:{"Idempotency-Key":n}}:{}})}async cancelMeeting(t,e){return this.transport.owner("DELETE",`/hops/owner/meetings/${w(t)}`,{query:e?{reason:e}:void 0,noRetry:!0})}async listMeetingsWithKey(t){return this.transport.get("/meetings",N(t))}async scheduleMeetingWithKey(t,e){const n=null==e?void 0:e.idempotencyKey;return this.transport.request("POST","/meetings",{body:t,noRetry:!n,...n?{headers:{"Idempotency-Key":n}}:{}})}async cancelMeetingWithKey(t,e){return this.transport.request("DELETE",`/meetings/${w(t)}`,{query:e?{reason:e}:void 0,noRetry:!0})}async translateMessage(t,e){return this.transport.post("/chats/translate",{messageId:t,targetLanguage:e})}async getChatUserProfile(){return this.transport.get("/chat-users/me")}async updateChatUserProfile(t){return this.transport.patch("/chat-users/me",t)}async getHandleEditInfo(){return this.transport.get("/chat-users/me/handle-edits")}async sendAdminReply(t){return this.transport.post("/chats/messages/admin-reply",t)}async getFeaturePricing(){return this.transport.get("/subscriptions/features")}async giftFeature(t){return this.transport.post("/subscriptions/features/gift",t)}async verifyGiftFeature(t){return this.transport.post("/subscriptions/features/gift/verify",t)}async getCannedResponseSuggested(t){return this.transport.get("/chats/canned-responses/suggested",t?{category:t}:void 0)}async useSuggestedCannedResponse(t){return this.transport.post("/chats/canned-responses/use-suggested",{suggestedId:t})}async getAdminMentions(t){return this.transport.get("/chats/messages/admin-mentions",H(t))}async getAdminMentionsAsOwner(t){return this.transport.owner("GET","/chats/messages/admin-mentions",{query:H(t)})}async globalSearch(t){return this.transport.get("/chats/global-search",{q:t})}async bulkExportChat(t){return this.transport.post("/chats/conversations/bulk-export",t)}async getLinkWorkspaceInfo(t){return this.transport.get(`/chat-links/${t}/info`)}async getWebinarRegistrations(t){return this.transport.get(`/chats/conversations/${t}/webinar/registrations`)}async getAppVersion(){return this.transport.get("/version")}async createLinkEmoji(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/emojis`,{body:e})}async listLinkEmojis(t,e){return this.transport.owner("GET",`/chats/links/${w(t)}/emojis`,{query:e})}async updateLinkEmoji(t,e,n){return this.transport.owner("PATCH",`/chats/links/${w(t)}/emojis/${w(e)}`,{body:n})}async enableLinkEmoji(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/emojis/${w(e)}/enable`)}async disableLinkEmoji(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/emojis/${w(e)}/disable`)}async deleteLinkEmoji(t,e){return this.transport.owner("DELETE",`/chats/links/${w(t)}/emojis/${w(e)}`)}async getLinkEmojiPack(t){return this.transport.request("GET",`/in/${w(t)}/emoji-pack`,{base:"root",auth:"none"})}async createPost(t){return this.transport.owner("POST","/posts",{body:t})}async listPosts(t){return this.transport.owner("GET","/posts",{query:t})}async schedulePost(t,e){return this.transport.owner("POST",`/posts/${w(t)}/schedule`,{body:e})}async publishPost(t){return this.transport.owner("POST",`/posts/${w(t)}/publish`)}async cancelPostSchedule(t){return this.transport.owner("POST",`/posts/${w(t)}/cancel-schedule`)}async getPromoAnalytics(t){return this.transport.owner("GET",`/posts/${w(t)}/analytics`)}async trackPromoClick(t,e){const n=e&&G.test(e)?{visitorId:e}:{};return this.transport.request("POST",`/promos/${w(t)}/click`,{body:n,base:"api",auth:"none",noRetry:!0})}async getMessageInfo(t,e,n){return this.transport.user("GET",`/chats/conversations/${w(t)}/messages/${w(e)}/info`,{query:n})}async getMessageEditHistory(t,e){return this.transport.user("GET",`/chats/conversations/${w(t)}/messages/${w(e)}/history`)}async exportConversationAsAdmin(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/member-export`,{body:e?{format:e}:{},auth:"member"})}async exportConversationAsMember(t,e={}){return this.transport.user("POST",`/chats/conversations/${w(t)}/member-export`,{body:e,auth:"member"})}async getMemberExportStatus(t,e){return this.transport.user("GET",`/chats/conversations/${w(t)}/member-export/${w(e)}`,{auth:"member"})}async exportConversationAsOwner(t,e){return this.transport.owner("POST",`/chats/conversations/${w(t)}/export`,{body:e})}async muteConversation(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/mute`,{body:{duration:e},auth:"member"})}async getQuietHours(){return this.transport.user("GET","/chats/settings/quiet-hours",{auth:"member"})}async setQuietHours(t){return this.transport.user("POST","/chats/settings/quiet-hours",{body:t,auth:"member"})}async createReminder(t){return this.transport.user("POST","/chats/reminders",{body:t,auth:"member"})}async listReminders(t){return this.transport.user("GET","/chats/reminders",{query:t,auth:"member"})}async cancelReminder(t){return this.transport.user("DELETE",`/chats/reminders/${w(t)}`,{auth:"member"})}async completeReminder(t){return this.transport.user("POST",`/chats/reminders/${w(t)}/done`,{auth:"member"})}async getConversationPermissions(t){return this.transport.user("GET",`/chats/conversations/${w(t)}/permissions`)}async updateConversationPermissions(t,e){return this.transport.user("PATCH",`/chats/conversations/${w(t)}/permissions`,{body:e})}async getTranscribeAvailability(){return this.transport.user("GET","/chats/transcription/availability")}async transcribeMessage(t,e){return this.transport.user("POST",`${$(t,e)}/transcribe`)}async getTranscript(t,e){return this.transport.user("GET",`${$(t,e)}/transcript`)}async summarizeTranscript(t,e){return this.transport.user("POST",`${$(t,e)}/transcript/summary`)}async translateTranscript(t,e,n){return this.transport.user("POST",`${$(t,e)}/transcript/translate`,{body:{targetLanguage:n}})}async startHuddle(t,e){return this.transport.user("POST",`/hops/huddles/${w(t)}/start`,{body:e?{initialMediaKind:e}:{},auth:"member"})}async getHuddle(t){return this.transport.user("GET",`/hops/huddles/${w(t)}`,{auth:"member"})}async endHuddle(t){return this.transport.user("POST",`/hops/huddles/${w(t)}/end`,{auth:"member"})}async declineHopInvite(t){return this.transport.user("POST",`/hops/${w(t)}/decline`,{auth:"member"})}async pushDeclineCall(t){return this.transport.request("POST","/hops/push-decline",{base:"api",auth:"none",body:{token:t},noRetry:!0})}async registerDevice(t){return this.transport.user("POST","/notifications/register-device",{body:t})}async inviteToHop(t,e){return this.transport.user("POST",`/hops/${w(t)}/invite`,{body:{chatUserIds:e},auth:"member",noRetry:!0})}async setLinkAutoTranscribe(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/auto-transcribe`,{body:{enabled:e}})}async setLinkAgentInbox(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/agent-inbox`,{body:{enabled:e}})}async listInbox(t){return this.transport.owner("GET","/chats/inbox",{query:t})}async assignInbox(t,e){return this.transport.owner("POST",`/chats/inbox/${w(t)}/assign`,{body:{assigneeId:e}})}async setInboxStatus(t,e){return this.transport.owner("POST",`/chats/inbox/${w(t)}/status`,{body:{status:e}})}async setLinkInboxSettings(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/inbox-settings`,{body:e})}async setLinkDiscoverable(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/discoverable`,{body:{enabled:e}})}async submitCsat(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/csat`,{body:e,auth:"member",noRetry:!0})}async listCsatRatings(t){return this.transport.get("/chats/csat",L(t))}async getCsatSummary(t){return this.transport.get("/chats/csat/summary",L(t))}async listCsatRatingsAsOwner(t){return this.transport.owner("GET","/chats/csat",{query:L(t)})}async getCsatSummaryAsOwner(t){return this.transport.owner("GET","/chats/csat/summary",{query:L(t)})}async getLinkMemberList(t,e){const n=e?{...e,limit:void 0!==e.limit?String(e.limit):void 0}:void 0;return this.transport.owner("GET",`/chats/links/${w(t)}/member-list`,{query:n})}async revokeLinkInvite(t,e){return this.transport.owner("DELETE",`/chats/links/${w(t)}/members/${w(e)}/invite`,{noRetry:!0})}async setWidgetConfig(t,e){return this.transport.owner("PUT",`/chats/links/${w(t)}/widget`,{body:e})}async getInboxAgentProfile(){return this.transport.user("GET","/chats/agent-inbox/me",{auth:"member"})}async listInternalNotes(t,e){return this.transport.user("GET",`${F(t)}/internal-notes`,{query:e,auth:"member"})}async createInternalNote(t,e){return this.transport.user("POST",`${F(t)}/internal-notes`,{body:e,auth:"member"})}async deleteInternalNote(t,e){return this.transport.user("DELETE",`${F(t)}/internal-notes/${w(e)}`,{auth:"member"})}async getAgentInboxState(t){return this.transport.user("GET",`${F(t)}/state`,{auth:"member"})}async agentAssignConversation(t,e){return this.transport.user("POST",`${F(t)}/assign`,{body:{assigneeId:e},auth:"member"})}async agentSetInboxStatus(t,e){return this.transport.user("POST",`${F(t)}/status`,{body:{status:e},auth:"member"})}async listConversationNotes(t,e){return this.transport.user("GET",`${F(t)}/notes`,{query:e,auth:"member"})}async createConversationNote(t,e){return this.transport.user("POST",`${F(t)}/notes`,{body:{text:e},auth:"member"})}async updateConversationNote(t,e,n){return this.transport.user("PATCH",`${F(t)}/notes/${w(e)}`,{body:{text:n},auth:"member"})}async deleteConversationNote(t,e){return this.transport.user("DELETE",`${F(t)}/notes/${w(e)}`,{auth:"member"})}async getConversationSummary(t){return this.transport.user("GET",`${F(t)}/summary`,{auth:"member"})}async draftConversationReply(t,e){return this.transport.user("POST",`/chats/conversations/${encodeURIComponent(t)}/draft-reply`,{body:e?{note:e}:{},auth:"member",noRetry:!0})}async getDraftReply(t){return this.transport.user("POST",`${F(t)}/draft-reply`,{auth:"member"})}async getConversationCatchUp(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/catch-up`,{body:{unreadCount:e},auth:"member"})}async getDrafts(){return this.transport.user("GET","/chats/drafts",{auth:"member"})}async setConversationTopic(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/topic`,{body:{topicId:e},auth:"member"})}async getPresenceStats(t){return this.transport.request("GET",`/in/${w(t)}/presence-stats`,{base:"root",auth:"none"})}async listMyChatLinks(t){return this.transport.user("GET","/chat-users/me/links",{query:t,auth:"member"})}async leaveMyLink(t){return this.transport.user("POST",`/chat-users/me/links/${w(t)}/leave`,{auth:"member"})}async claimGuest(t){return this.transport.user("POST","/chat-users/me/claim-guest",{body:t,auth:"member",noRetry:!0})}async setMyLinkNotify(t,e){return this.transport.user("PUT",`/chat-users/me/links/${w(t)}/notify`,{body:{level:e},auth:"member"})}async listLinkMembers(t,e){const n=void 0===e?{chatLinkId:t}:{chatLinkId:t,limit:String(e)};return this.transport.user("GET","/chat-users/me/link-members",{query:n,auth:"member"})}async getLinkAvailability(t){return this.transport.request("GET",`/in/${w(t)}/availability`,{base:"root",auth:"none"})}async announceGift(t,e,n){return this.transport.user("POST",`/chats/conversations/${w(t)}/gift-announce`,{body:n?{reference:e,note:n}:{reference:e},auth:"member"})}async listAccountSessions(){return this.transport.owner("GET","/users/sessions")}async revokeAccountSession(t){return this.transport.owner("DELETE",`/users/sessions/${w(t)}`)}async revokeOtherAccountSessions(){return this.transport.owner("POST","/users/sessions/revoke-others")}async listMySessions(){return this.transport.user("GET","/chat-users/me/sessions",{auth:"member"})}async revokeMySession(t){return this.transport.user("DELETE",`/chat-users/me/sessions/${w(t)}`,{auth:"member"})}async revokeMyOtherSessions(){return this.transport.user("POST","/chat-users/me/sessions/revoke-others",{auth:"member"})}async getAccountQuietHours(){return this.transport.owner("GET","/users/me/quiet-hours")}async setAccountQuietHours(t){return this.transport.owner("PUT","/users/me/quiet-hours",{body:t})}async sendScheduledMessageNow(t){return this.transport.user("POST",`/chats/messages/${w(t)}/send-now`,{auth:"member"})}async getLinkOnlineCount(t){return this.transport.request("GET",`/in/${w(t)}/online-count`,{base:"root",auth:"none"})}async joinLinkAsGuest(t,e){return this.transport.request("POST",`/in/${w(t)}/join-guest`,{base:"root",auth:"none",body:e,noRetry:!0})}async verifyMeetingGuest(t,e){return this.transport.request("POST",`/in/${w(t)}/join-guest/verify`,{base:"root",auth:"none",body:e,noRetry:!0})}async notifyWhenLinkReopens(t,e){return this.transport.request("POST",`/in/${w(t)}/notify-reopen`,{base:"root",auth:"none",body:{email:e}})}async subscribeToStatusUpdates(t){return this.transport.request("POST","/health/subscribe",{base:"api",auth:"none",body:{email:t}})}async unsubscribeFromStatusUpdates(t,e){return this.transport.request("GET","/health/unsubscribe",{base:"api",auth:"none",query:{email:t,token:e}})}async getWebinarInfo(t){return this.transport.request("GET",`/chats/conversations/${w(t)}/webinar/info`,{base:"api",auth:"none"})}async registerForWebinar(t,e){return this.transport.request("POST",`/chats/conversations/${w(t)}/webinar/register`,{base:"api",auth:"none",body:e,noRetry:!0})}async requestBusinessSignInCode(t){return this.transport.request("POST","/users/sign-in-code",{base:"api",auth:"none",body:{email:t},noRetry:!0})}async verifyBusinessSignInCode(t,e){const n=await this.transport.request("POST","/users/sign-in-code/verify",{base:"api",auth:"none",body:{email:t,code:e},noRetry:!0});return"accessToken"in n&&n.accessToken&&this.transport.setOwnerToken(n.accessToken),n}async verifyBusinessTotp(t,e){const n=await this.transport.request("POST","/users/2fa/verify",{base:"api",auth:"none",body:{pendingToken:t,token:e},noRetry:!0});return(null==n?void 0:n.accessToken)&&this.transport.setOwnerToken(n.accessToken),n}async listAccountChatLinks(t){return this.transport.owner("GET","/chats/links",{query:t})}async updateAccountProfile(t){return this.transport.owner("PATCH","/users/me",{body:t})}async listWorkspaceTeams(){return this.transport.owner("GET","/users/teams")}async createWorkspaceTeam(t){return this.transport.owner("POST","/users/teams",{body:t})}async updateWorkspaceTeam(t,e){return this.transport.owner("PATCH",`/users/teams/${w(t)}`,{body:e})}async deleteWorkspaceTeam(t){return this.transport.owner("DELETE",`/users/teams/${w(t)}`)}async inviteTeamMember(t){return this.transport.owner("POST","/users/team/invite",{body:t,noRetry:!0})}async inviteChatUser(t){return this.transport.owner("POST","/chats/chat-users/invite",{body:t,noRetry:!0})}async getMemberFollowStatus(t,e){return this.transport.user("GET",U(t,e),{auth:"member"})}async followMember(t,e){return this.transport.user("POST",U(t,e),{auth:"member"})}async unfollowMember(t,e){return this.transport.user("DELETE",U(t,e),{auth:"member"})}async getCalendarSyncStatus(){return this.transport.user("GET","/calendar-sync/status",{auth:"member"})}async connectCalendar(t,e){return this.transport.user("POST",`/calendar-sync/${w(t)}/connect`,{body:e||{},auth:"member",noRetry:!0})}async completeNativeCalendarConnect(t){return this.transport.user("POST","/calendar-sync/native/complete",{body:{code:t},auth:"member",noRetry:!0})}async disconnectCalendar(t){return this.transport.user("DELETE",`/calendar-sync/${w(t)}`,{auth:"member"})}async setCalendarShareBusy(t,e){return this.transport.user("PATCH",`/calendar-sync/${w(t)}/settings`,{body:{shareBusy:e},auth:"member"})}async syncCalendarNow(){return this.transport.user("POST","/calendar-sync/sync",{auth:"member",noRetry:!0})}async getCalendarBusy(t){return this.transport.user("GET","/calendar-sync/busy",{query:{userIds:t.userIds.join(","),from:t.from,to:t.to},auth:"member"})}async listActivity(t){return this.transport.user("GET","/notifications/activity",{query:D(t)})}async getActivityUnreadCount(){return this.transport.user("GET","/notifications/activity/unread-count")}async markAllActivityRead(){return this.transport.user("PATCH","/notifications/activity/read-all")}async getSidebarCategories(t){return this.transport.user("GET","/chats/categories",{query:t?{chatLinkId:t}:void 0})}async setConversationCategory(t,e){return this.transport.user("PUT",`/chats/conversations/${w(t)}/category`,{body:{category:e}})}async renameSidebarCategory(t){return this.transport.user("PATCH","/chats/categories",{body:t})}async deleteSidebarCategory(t,e){return this.transport.user("DELETE","/chats/categories",{query:{name:t,...e?{chatLinkId:e}:{}}})}async sendPushReply(t,e,n){return this.transport.request("POST","/chats/push-reply",{base:"api",auth:"none",body:{token:t,message:e,...n?{deviceHint:n}:{}},noRetry:!0})}async redeemMeetingGuestPass(t,e){return this.transport.user("POST","/hops/meetings/guest-pass",{body:{code:t,token:e},auth:"member"})}async joinMeetingByLink(t){return this.transport.user("POST","/hops/meetings/join-by-link",{body:{code:t},auth:"member"})}async joinMeetingFromChannel(t){return this.transport.user("POST",`/hops/meetings/${w(t)}/join-from-channel`,{auth:"member"})}async requestWebinarRecordingLink(t,e){return this.transport.request("POST",`/chats/conversations/${w(t)}/webinar/recording-link`,{base:"api",auth:"none",body:{email:e},noRetry:!0})}async getWebinarRecording(t,e){return this.transport.request("GET",`/chats/conversations/${w(t)}/webinar/recording`,{base:"api",auth:"none",headers:{"X-Recording-Token":e}})}async getWebinarRecordingsAsOwner(t){return this.transport.owner("GET",`/chats/conversations/${w(t)}/webinar/recordings`)}async getGiftCatalog(){return this.transport.user("GET","/gifts/catalog")}async sendPeerGift(t){return this.transport.user("POST","/gifts/peer",{body:t,auth:"member",noRetry:!0})}async verifyPeerGift(t){return this.transport.request("POST","/gifts/peer/verify",{base:"api",auth:"none",body:{reference:t}})}async listReceivedGifts(t){return this.transport.user("GET","/gifts/received",{query:t,auth:"member"})}async getOwnerGifts(t){return this.transport.owner("GET","/gifts/owner",{query:D(t)})}async getGiftBalance(){return this.transport.user("GET","/gifts/balance",{auth:"member"})}async requestGiftPayout(){return this.transport.user("POST","/gifts/payouts",{auth:"member",noRetry:!0})}async requestBusinessPasswordReset(t){return this.transport.request("POST","/users/forgot-password",{base:"api",auth:"none",body:{identifier:t},noRetry:!0})}async resetBusinessPassword(t){return this.transport.request("POST","/users/reset-password",{base:"api",auth:"none",body:t,noRetry:!0})}async getPasswordResetStatus(t){return this.transport.request("GET","/users/reset-password/status",{base:"api",auth:"none",query:{token:t}})}async requestChatPasswordReset(t){return this.transport.request("POST","/chat-users/forgot-password",{base:"api",auth:"none",body:t,noRetry:!0})}async resetChatPassword(t){return this.transport.request("POST","/chat-users/reset-password",{base:"api",auth:"none",body:t,noRetry:!0})}async requestLinkPasswordReset(t,e){return this.transport.request("POST",`/in/${w(t)}/forgot-password`,{base:"root",auth:"none",body:{identifier:e},noRetry:!0})}async resetLinkPassword(t,e){return this.transport.request("POST",`/in/${w(t)}/reset-password`,{base:"root",auth:"none",body:e,noRetry:!0})}async setLinkMode(t,e){return this.transport.owner("PATCH",`/chats/links/${w(t)}/mode`,{body:e})}async setConversationMode(t,e){return this.transport.user("PATCH",`/chats/conversations/${w(t)}/mode`,{body:e})}async getPublicLinkInfo(t){return this.transport.request("GET",`/in/${w(t)}`,{base:"root",auth:"none"})}async createAccountChatLink(t){return this.transport.owner("POST","/chats/links",{body:t,noRetry:!0})}async getLinkChannels(t){return this.transport.request("GET",`/in/${w(t)}/channels`,{base:"root",auth:"none"})}async getGiftStoreData(t){return this.transport.request("GET",`/in/${w(t)}/gift-store-data`,{base:"root",auth:"none"})}async setLinkJoinPolicy(t,e){return this.transport.owner("PATCH",`/chats/links/${w(t)}/join-policy`,{body:e})}async requestToJoinLink(t,e){return this.transport.request("POST",`/in/${w(t)}/join-request`,{base:"root",auth:"none",body:e,noRetry:!0})}async listJoinRequests(t,e){const n=e?{...e,limit:void 0!==e.limit?String(e.limit):void 0}:void 0;return this.transport.owner("GET",`/chats/links/${w(t)}/join-requests`,{query:n})}async approveJoinRequest(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/join-requests/${w(e)}/approve`,{noRetry:!0})}async denyJoinRequest(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/join-requests/${w(e)}/deny`,{noRetry:!0})}async getSupportGroupTeam(t){return this.transport.user("GET",`/chats/conversations/${w(t)}/support-team`,{auth:"member"})}async setSupportGroupTeam(t,e){return this.transport.user("PATCH",`/chats/conversations/${w(t)}/support-team`,{body:{teamId:e},auth:"member"})}async setLinkAppOrigins(t,e){return this.transport.owner("PUT",`/chats/links/${w(t)}/app-origins`,{body:{origins:e}})}async setLinkEmbedDomains(t,e){return this.transport.owner("PUT",`/chats/links/${w(t)}/embed-domains`,{body:{domains:e}})}async listPlans(){const t=this.transport.hasOwnerToken()?"owner":"none";return this.transport.request("GET","/subscriptions/plans",{base:"api",auth:t})}async getPlan(t){const e=this.transport.hasOwnerToken()?"owner":"none";return this.transport.request("GET",`/subscriptions/plans/${w(t)}`,{base:"api",auth:e})}async subscribeToPlan(t){return this.transport.owner("POST","/subscriptions/subscribe",{body:t,noRetry:!0})}async verifySubscription(t){return this.transport.request("POST","/subscriptions/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async listMySubscriptions(){return this.transport.owner("GET","/subscriptions/my-subscriptions")}async changePlan(t,e){return this.transport.owner("POST",`/subscriptions/${w(t)}/change-plan`,{body:e,noRetry:!0})}async cancelSubscription(t){return this.transport.owner("DELETE",`/subscriptions/${w(t)}`)}async cancelScheduledPlanChange(t){return this.transport.owner("DELETE",`/subscriptions/${w(t)}/scheduled-change`)}async giftPlan(t){return this.transport.user("POST","/subscriptions/plan/gift",{body:t,noRetry:!0})}async verifyPlanGift(t){return this.transport.request("POST","/subscriptions/plan/gift/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async getTrialStatus(){return this.transport.owner("GET","/subscriptions/trial")}async startTrial(t){return this.transport.owner("POST","/subscriptions/trial",{body:t,noRetry:!0})}async getRenewalStatus(){return this.transport.owner("GET","/subscriptions/renewal")}async renewSubscription(t,e){return this.transport.owner("POST",`/subscriptions/${w(t)}/renew`,{body:e||{},noRetry:!0})}async useBankTransferRenewals(){return this.transport.owner("POST","/subscriptions/payment-method/bank-transfer",{noRetry:!0})}async getStorageUsage(){return this.transport.user("GET","/subscriptions/storage")}async listStaffAccess(t){return this.transport.owner("GET","/staff-access",{query:D(t)})}async requestCustomPlan(t){return this.transport.request("POST","/plan-requests",{base:"api",auth:"none",body:t,noRetry:!0})}async requestCustomPlanAsOwner(t){return this.transport.owner("POST","/plan-requests/me",{body:t,noRetry:!0})}async getMyLatestPlanRequest(){return this.transport.owner("GET","/plan-requests/me/latest")}async listStoreFeatures(){return this.transport.request("GET","/subscriptions/features",{base:"api",auth:"none"})}async purchaseFeature(t){return this.transport.owner("POST","/subscriptions/features/purchase",{body:t,noRetry:!0})}async verifyFeaturePurchase(t){return this.transport.request("POST","/subscriptions/features/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async listMyFeaturePurchases(){return this.transport.user("GET","/subscriptions/features/my-purchases")}async giftWorkspaceFeature(t){return this.transport.user("POST","/subscriptions/features/gift",{body:t,noRetry:!0})}async verifyWorkspaceFeatureGift(t){return this.transport.request("POST","/subscriptions/features/gift/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async checkLinkCode(t){return this.transport.owner("GET","/chats/links/code-available",{query:{code:t}})}async getLinkModeCatalog(){return this.transport.owner("GET","/chats/links/modes")}async updateLinkTheme(t,e){return this.transport.owner("PATCH",`/chats/links/${w(t)}/theme`,{body:e})}async setLinkWhoCanJoin(t,e){return this.transport.owner("PATCH",`/chats/links/${w(t)}/who-can-join`,{body:{who:e}})}async getLinkCustomDomain(t){return this.transport.owner("GET",`/chats/links/${w(t)}/custom-domain`)}async setLinkCustomDomain(t,e){return this.transport.owner("PUT",`/chats/links/${w(t)}/custom-domain`,{body:{domain:e}})}async verifyLinkCustomDomain(t){return this.transport.owner("POST",`/chats/links/${w(t)}/custom-domain/verify`)}async wipeLinkMessages(t){return this.transport.owner("POST",`/chats/links/${w(t)}/wipe-messages`,{noRetry:!0})}async getLinkOverview(t){return this.transport.owner("GET",`/chats/links/${w(t)}/overview`)}async getChatLinkModeCatalog(){return this.transport.get("/chat-links/modes")}async setChatLinkMode(t,e){return this.transport.patch(`/chat-links/${w(t)}/mode`,e)}async getMyNote(t){return this.transport.user("GET",`/chats/conversations/${w(t)}/my-note`,{auth:"member"})}async setMyNote(t,e){return this.transport.user("PUT",`/chats/conversations/${w(t)}/my-note`,{body:{text:e},auth:"member"})}async setConversationPinned(t,e){return this.transport.user("PUT",`/chats/conversations/${w(t)}/pin`,{body:{pinned:e},auth:"member"})}async listStarredPeople(t){return this.transport.user("GET","/chat-users/me/starred",{query:t,auth:"member"})}async listStarredIds(){return this.transport.user("GET","/chat-users/me/starred/ids",{auth:"member"})}async starPerson(t){return this.transport.user("PUT",`/chat-users/me/starred/${w(t)}`,{auth:"member"})}async unstarPerson(t){return this.transport.user("DELETE",`/chat-users/me/starred/${w(t)}`,{auth:"member"})}async getAccountProfile(){return this.transport.owner("GET","/users/me")}async getKnownFeatureFlags(){return this.transport.owner("GET","/admins/feature-flags/known")}async listPendingTransfers(){return this.transport.owner("GET","/subscriptions/pending-transfers")}async purchaseExtraSeats(t){return this.transport.user("POST","/subscriptions/extra-seats",{body:t,noRetry:!0})}async verifyExtraSeats(t){return this.transport.request("POST","/subscriptions/extra-seats/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async setStorageAddonAutoRenew(t,e){return this.transport.owner("POST",`/subscriptions/storage/addons/${w(t)}/auto-renew`,{body:{autoRenew:e}})}async createApiKey(t){return this.transport.owner("POST","/api-keys",{body:t,noRetry:!0})}async listApiKeys(t){return this.transport.owner("GET","/api-keys",{query:t})}async updateApiKey(t,e){return this.transport.owner("PATCH",`/api-keys/${w(t)}`,{body:e})}async rotateApiKey(t){return this.transport.owner("POST",`/api-keys/${w(t)}/rotate`,{noRetry:!0})}async revokeApiKey(t){return this.transport.owner("DELETE",`/api-keys/${w(t)}`)}async getApiKeyUsage(t,e="7d"){return this.transport.owner("GET",`/api-keys/${w(t)}/usage`,{query:{period:e}})}async getLiveFlex(){return this.transport.user("GET","/wallet")}async listLiveFlexTransactions(t){return this.transport.user("GET","/wallet/transactions",{query:t})}async fundLiveFlex(t){return this.transport.user("POST","/wallet/fund",{body:t,noRetry:!0})}async verifyLiveFlexFunding(t){return this.transport.user("POST","/wallet/fund/verify",{body:{reference:t}})}async listLiveFlexRecipients(t){return this.transport.user("GET","/wallet/recipients",{query:t?{q:t}:void 0})}async listLiveFlexBanks(){return this.transport.user("GET","/wallet/banks")}async setLiveFlexPayoutBank(t){return this.transport.user("PUT","/wallet/payout/bank",{body:t,noRetry:!0})}async setLiveFlexPayoutCrypto(t){return this.transport.user("PUT","/wallet/payout/crypto",{body:t,noRetry:!0})}async confirmLiveFlexPayout(t){return this.transport.user("POST","/wallet/payout/confirm",{body:{code:t},noRetry:!0})}async clearLiveFlexPayout(t){return this.transport.user("DELETE",`/wallet/payout/${w(t)}`)}async withdrawLiveFlex(t){return this.transport.user("POST","/wallet/withdraw",{body:t,noRetry:!0})}async sendLiveFlex(t){return this.transport.user("POST","/wallet/send",{body:t,noRetry:!0})}async startLiveFlexPinSetup(){return this.transport.user("POST","/wallet/pin/start",{noRetry:!0})}async setLiveFlexPin(t){return this.transport.user("POST","/wallet/pin",{body:t,noRetry:!0})}async startLiveFlexLink(){return this.transport.user("POST","/wallet/link/start",{noRetry:!0})}async linkLiveFlex(t){return this.transport.user("POST","/wallet/link",{body:t,noRetry:!0})}async setLiveFlexTag(t){return this.transport.user("PUT","/wallet/tag",{body:{tag:t},noRetry:!0})}async findLiveFlexTag(t){return this.transport.user("GET",`/wallet/tags/${w(t.replace(/^\$/,""))}`)}async listLiveFlexApprovals(){return this.transport.owner("GET","/wallet/approvals")}async decideLiveFlexApproval(t,e){return this.transport.owner("PATCH",`/wallet/approvals/${w(t)}/${w(e)}`,{noRetry:!0})}async getLiveFlexTeamLimits(){return this.transport.owner("GET","/wallet/team-limits")}async setLiveFlexTeamLimits(t){return this.transport.owner("PUT","/wallet/team-limits",{body:t})}async createLiveFlexRequest(t){return this.transport.user("POST","/wallet/requests",{body:t,auth:"member",noRetry:!0})}async listLiveFlexRequests(t="incoming"){return this.transport.user("GET","/wallet/requests",{query:{box:t},auth:"member"})}async getLiveFlexRequest(t){return this.transport.user("GET",`/wallet/requests/${w(t)}`,{auth:"member"})}async payLiveFlexRequest(t,e={}){return this.transport.user("POST",`/wallet/requests/${w(t)}/pay`,{body:e,auth:"member",noRetry:!0})}async declineLiveFlexRequest(t){return this.transport.user("POST",`/wallet/requests/${w(t)}/decline`,{auth:"member",noRetry:!0})}async blockLiveFlexRequester(t){return this.transport.user("POST",`/wallet/requests/${w(t)}/block`,{auth:"member",noRetry:!0})}async cancelLiveFlexRequest(t){return this.transport.user("POST",`/wallet/requests/${w(t)}/cancel`,{auth:"member",noRetry:!0})}async createLiveFlexSplit(t){return this.transport.user("POST","/wallet/splits",{body:t,auth:"member",noRetry:!0})}async getLiveFlexSplit(t){return this.transport.user("GET",`/wallet/splits/${w(t)}`,{auth:"member"})}async cancelLiveFlexSplit(t){return this.transport.user("POST",`/wallet/splits/${w(t)}/cancel`,{auth:"member",noRetry:!0})}async listLiveFlexStanding(){return this.transport.user("GET","/wallet/standing")}async createLiveFlexStanding(t){return this.transport.user("POST","/wallet/standing",{body:t,auth:"member",noRetry:!0})}async pauseLiveFlexStanding(t){return this.transport.user("POST",`/wallet/standing/${w(t)}/pause`,{noRetry:!0})}async resumeLiveFlexStanding(t){return this.transport.user("POST",`/wallet/standing/${w(t)}/resume`,{noRetry:!0})}async cancelLiveFlexStanding(t){return this.transport.user("POST",`/wallet/standing/${w(t)}/cancel`,{noRetry:!0})}async createLiveFlexPot(t){return this.transport.user("POST","/wallet/pots",{body:t,auth:"member",noRetry:!0})}async getLiveFlexPot(t){return this.transport.user("GET",`/wallet/pots/${w(t)}`,{auth:"member"})}async contributeLiveFlexPot(t,e={}){return this.transport.user("POST",`/wallet/pots/${w(t)}/contribute`,{body:e,auth:"member",noRetry:!0})}async closeLiveFlexPot(t){return this.transport.user("POST",`/wallet/pots/${w(t)}/close`,{auth:"member",noRetry:!0})}async cancelLiveFlexPot(t){return this.transport.user("POST",`/wallet/pots/${w(t)}/cancel`,{auth:"member",noRetry:!0})}async refundLiveFlexTransaction(t,e={}){return this.transport.user("POST",`/wallet/transactions/${w(t)}/refund`,{body:e,noRetry:!0})}async createLiveFlexPayLink(t){return this.transport.user("POST","/wallet/pay-links",{body:t,auth:"member",noRetry:!0})}async getLiveFlexPayLink(t){return this.transport.user("GET",`/wallet/pay-links/${w(t)}`,{auth:"member"})}async cancelLiveFlexPayLink(t){return this.transport.user("POST",`/wallet/pay-links/${w(t)}/cancel`,{auth:"member",noRetry:!0})}async payLiveFlexPayLink(t,e){return this.transport.user("POST",`/wallet/pay-links/${w(t)}/pay`,{body:e,auth:"member",noRetry:!0})}async verifyLiveFlexPayLink(t){return this.transport.user("POST","/wallet/pay-links/verify",{body:{reference:t}})}async getLiveFlexPayLinkReceiptLink(t){return this.transport.user("GET",`/wallet/pay-links/${w(t)}/receipt/link`,{auth:"member"})}async listLiveFlexReceipts(){return this.transport.user("GET","/wallet/receipts")}async getLiveFlexReceiptLink(t){return this.transport.user("GET",`/wallet/receipts/${w(t)}/link`)}async getLiveFlexStatementLinks(t){return this.transport.user("GET",`/wallet/statements/${w(t)}/links`)}async getStaffAccessGrant(){return this.transport.owner("GET","/staff-access/grant")}async setStaffAccessGrant(t){return this.transport.owner("PUT","/staff-access/grant",{body:t})}async revokeStaffAccessGrant(){return this.transport.owner("DELETE","/staff-access/grant")}async listWorkspaceStickers(t){return this.transport.owner("GET","/chats/stickers",{query:t})}async setWorkspaceStickerState(t,e){return this.transport.owner("PATCH",`/chats/stickers/${encodeURIComponent(t)}/workspace/${e}`)}async takeDownSticker(t){return this.transport.owner("POST",`/chats/stickers/${encodeURIComponent(t)}/take-down`)}async listCallHistory(t){return this.transport.user("GET","/hops/calls",{query:t,auth:"member"})}async getRecordingDownloadLink(t){return this.transport.user("POST",`/hops/recordings/${w(t)}/download`,{auth:"member",noRetry:!0})}async sendContactMessage(t){return this.transport.request("POST","/public/contact",{base:"root",auth:"none",body:t,noRetry:!0})}googleSignInUrl(t){return this.transport.urlFor("api","/users/google/start",t?{returnUrl:t}:void 0)}async redeemGoogleSignIn(t){const e=await this.transport.request("POST","/users/google/redeem",{base:"api",auth:"none",body:{handoff:t},noRetry:!0});return"accessToken"in e&&e.accessToken&&this.transport.setOwnerToken(e.accessToken),e}async getGifConfig(){return this.transport.user("GET","/chats/gifs/config")}async searchGifs(t){return this.transport.user("GET","/chats/gifs/search",{query:k(t)})}async trendingGifs(t){return this.transport.user("GET","/chats/gifs/trending",{query:k(t)})}async registerGifShare(t){return this.transport.user("POST","/chats/gifs/share",{body:t})}async reportGif(t){return this.transport.user("POST","/chats/gifs/report",{body:t})}async inviteSharedChannel(t){return this.transport.user("POST","/shared-channels",{body:t,auth:"member",noRetry:!0})}async listSharedChannels(t){return this.transport.user("GET","/shared-channels",{query:M({chatLinkId:t.chatLinkId,nextCursor:t.nextCursor}),auth:"member"})}async previewSharedChannelInvite(t){return this.transport.user("POST","/shared-channels/preview",{body:{token:t},auth:"member",noRetry:!0})}async listSharedChannelMembers(t){return this.transport.user("GET","/shared-channels/members",{query:M({chatLinkId:t.chatLinkId,q:t.q,sharedChannelId:t.sharedChannelId,nextCursor:t.nextCursor}),auth:"member"})}async getConversationSharedChannels(t,e){return this.transport.user("GET",`/shared-channels/conversations/${w(t)}`,{query:M({chatLinkId:e.chatLinkId}),auth:"member"})}async getSharedChannelPermissions(t,e){return this.transport.user("GET",`/shared-channels/conversations/${w(t)}/permissions`,{query:M({chatLinkId:e.chatLinkId}),auth:"member"})}async acceptSharedChannel(t,e){return this.transport.user("POST",`/shared-channels/${w(t)}/accept`,{body:e,auth:"member",noRetry:!0})}async acceptSharedChannelByToken(t){return this.transport.user("POST","/shared-channels/accept-token",{body:t,auth:"member",noRetry:!0})}async endSharedChannel(t,e){return this.transport.user("POST",`/shared-channels/${w(t)}/end`,{body:{chatLinkId:e.chatLinkId},auth:"member",noRetry:!0})}async updateSharedChannelMembers(t,e){return this.transport.user("PUT",`/shared-channels/${w(t)}/members`,{body:e,auth:"member",noRetry:!0})}async getSharedChannelAudit(t,e){return this.transport.user("GET",`/shared-channels/${w(t)}/audit`,{query:M({chatLinkId:e.chatLinkId,nextCursor:e.nextCursor}),auth:"member"})}async openSharedDirect(t){return this.transport.user("POST","/shared-channels/direct",{body:t,auth:"member",noRetry:!0})}async removeSharedChannelMember(t){return this.transport.user("POST","/shared-channels/remove-member",{body:t,auth:"member",noRetry:!0})}async removeSharedChannelMessage(t){return this.transport.user("POST","/shared-channels/remove-message",{body:t,auth:"member",noRetry:!0})}async linkChatUserToAccount(t){return this.transport.owner("POST","/chats/chat-users/link-account",{body:t,noRetry:!0})}}const q=["ringing","cancel","end","mute","unmute","hold","unhold"],B={brand:"livechatta:brand",unread:"livechatta:unread",themeLoaded:"CHATTA_APP:onThemeLoaded",unreadChange:"CHATTA_APP:onUnreadChange",preChat:"livechatta:prechat",hello:"livechatta:hello"};function V(t){try{const e=new URL(String(t||""));return"https:"===e.protocol||"http:"===e.protocol?e.origin:null}catch(t){return null}}function K(t){const e=V(t.getAttribute("src")||t.src),n=t.contentWindow;return!(!e||!n||(n.postMessage({type:B.hello},e),0))}function j(t){t.addEventListener("load",()=>{K(t)})}function Y(t,e){if(!e||"object"!=typeof e)return!1;const n=e,r=void 0!==n.payload?n.payload:n;switch(n.type){case B.brand:case B.themeLoaded:return t.setLinkBrand(null==r?void 0:r.primaryColor),(null==r?void 0:r.secondaryColor)&&t.setLinkSecondary(r.secondaryColor),(null==r?void 0:r.mode)&&t.setFrameMode(r.mode),!0;case B.unread:case B.unreadChange:return t.setUnread("number"==typeof r?r:{count:Number(null==r?void 0:r.count)}),!0;default:return!1}}class z{constructor(t){this.iframe=null,this.warned=!1,this.listeners=new Map,this.boundMessageHandler=null,this.nextCallId=1,this.pendingCalls=new Map,this.allowedOrigin=V(t.allowedOrigin)||"",this.runtime=i()}attach(t){this.iframe=t,this.boundMessageHandler||(this.boundMessageHandler=t=>this.handleIncoming(t),window.addEventListener("message",this.boundMessageHandler))}detach(){this.boundMessageHandler&&(window.removeEventListener("message",this.boundMessageHandler),this.boundMessageHandler=null),this.listeners.clear(),this.pendingCalls.clear(),this.iframe=null}on(t,e){let n=this.listeners.get(t);return n||(n=new Set,this.listeners.set(t,n)),n.add(e),()=>n.delete(e)}warnOnce(t){this.warned||(this.warned=!0,"undefined"!=typeof console&&console.warn(`[LiveChatta] Bridge: ${t} Nothing is sent to the chat frame.`))}targetOrigin(){const t=this.iframe;if(!t||!t.contentWindow)return null;if(!this.allowedOrigin)return this.warnOnce("no allowedOrigin is configured (set baseUrl), so there is no safe target origin."),null;const e=V("function"==typeof t.getAttribute&&t.getAttribute("src")||t.src);return e?e!==this.allowedOrigin?(this.warnOnce(`the iframe is on ${e} but the allowed origin is ${this.allowedOrigin}.`),null):e:null}send(t,e){const n=this.targetOrigin();return!!n&&(this.iframe.contentWindow.postMessage({type:`CHATTA_APP:${t}`,payload:e},n),!0)}onOpenWorkspaceDrawer(t){return this.on("openWorkspaceDrawer",t)}onUnreadChange(t){return this.on("onUnreadChange",t)}onLoginSuccess(t){return this.on("onLoginSuccess",t)}onLogout(t){return this.on("onLogout",t)}onThemeLoaded(t){return this.on("onThemeLoaded",t)}onScreenshotProtection(t){return this.on("enableScreenshotProtection",t)}onNotify(t){return this.on("notify",t)}onHopStartCall(t){return this.on("hopStartCall",t)}onHopEndCall(t){return this.on("hopEndCall",t)}onHopMuteChanged(t){return this.on("hopMuteChanged",t)}onLinkUnavailable(t){return this.on("onLinkUnavailable",t)}restoreSession(t){this.send("restoreSession",t)}sendHopInvite(t){this.send("hopInvite",t)}notifyUpdateReady(t){this.send("updateReady",t)}sendInit(t){this.send("init",t)}sendNativeCall(t,e){return!(!q.includes(t)||!/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))||(this.send("nativeCall",{action:t,sessionId:e}),0))}shareFiles(t,e){if(!this.targetOrigin())return!1;const n=(t||[]).filter(t=>"undefined"!=typeof File&&t instanceof File).slice(0,10),r="string"==typeof e?e.trim().slice(0,4e3):"";return!(!n.length&&!r)&&this.send("shareFiles",r?{files:n,text:r}:{files:n})}request(t,e,n=5e3){if(!this.iframe||!this.iframe.contentWindow)return Promise.reject(new Error("Bridge: iframe not attached"));const r=this.targetOrigin();if(!r)return Promise.reject(new Error("Bridge: no safe target origin (allowedOrigin and the iframe src must match)"));const s="sdk-"+this.nextCallId++;return new Promise((o,a)=>{const i=setTimeout(()=>{this.pendingCalls.delete(s),a(new Error(`Bridge: ${t} timed out after ${n}ms`))},n);this.pendingCalls.set(s,t=>{clearTimeout(i),o(t)}),this.iframe.contentWindow.postMessage({type:`CHATTA_APP:${t}`,payload:e,callId:s},r)})}handleIncoming(t){var e;if(!t.data||"object"!=typeof t.data)return;const n=t.data;if("string"!=typeof n.type||!n.type.startsWith("CHATTA_APP:"))return;const r=null===(e=this.iframe)||void 0===e?void 0:e.contentWindow;if(!this.allowedOrigin||!r||t.source!==r)return;if(t.origin!==this.allowedOrigin&&"null"!==t.origin)return;if("CHATTA_APP:response"===n.type&&n.callId){const t=this.pendingCalls.get(n.callId);return void(t&&(this.pendingCalls.delete(n.callId),t(n.result)))}const s=n.type.slice(11),o=this.listeners.get(s);o&&o.forEach(t=>{try{t(n.payload)}catch(t){}})}}const Q=["primaryColor","secondaryColor","primaryLight","primaryDark","primaryBg","bg","bgDark","textColor","textLight","textMuted","borderColor","borderLight"],X=[...Q,"fontFamily","logoUrl","theme"];function J(t,e,n){for(const r of n){const n=t[r];null!=n&&(e[r]=n)}}const Z="#D2400B",tt="#0B6E66",et="#6C5CE7",nt="#191715";function rt(t){if("string"!=typeof t)return null;let e=t.trim().replace(/^#/,"");return/^[0-9a-f]{3}$/i.test(e)&&(e=e.split("").map(t=>t+t).join("")),/^[0-9a-f]{6}$/i.test(e)?`#${e.toUpperCase()}`:null}function st(t){const e=rt(t);return!!e&&e!==et}function ot(t){const e=(rt(t)||Z).slice(1),[n,r,s]=[0,2,4].map(t=>function(t){const e=t/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}(parseInt(e.substr(t,2),16)));return.2126*n+.7152*r+.0722*s}function at(t,e){const n=ot(t),r=ot(e);return(Math.max(n,r)+.05)/(Math.min(n,r)+.05)}function it(t){return at(t,"#FFFFFF")>=at(t,nt)?"#FFFFFF":nt}function ht(t,e){const n=(rt(t)||Z).slice(1),r=ot(e)>.18?0:255,s=[0,2,4].map(t=>parseInt(n.substr(t,2),16));for(let t=0;t<=1.0001;t+=.05){const n="#"+s.map(e=>Math.round(e+(r-e)*t).toString(16).padStart(2,"0")).join("").toUpperCase();if(at(n,e)>=4.5)return n}return 0===r?nt:"#FFFFFF"}function ct(t,e){return"light"===t||"dark"===t||"system"===t?t:e}class lt{constructor(t){var e,n,r,s,o,a,i,h,c,l;if(this.floating=!0===t.floating,!t.container&&!this.floating)throw new Error("LiveChatta UI: container is required");this.container=t.container,this.width=t.width||(this.floating?"380px":"100%"),this.height=t.height||(this.floating?"640px":"600px"),this.hasExplicitPrimary=st(t.primaryColor),this.hasExplicitSecondary=!!t.secondaryColor,this.primaryColor=(this.hasExplicitPrimary?t.primaryColor:Z).replace("#",""),this.secondaryColor=(t.secondaryColor||tt).replace("#",""),this.primaryLight=null===(e=t.primaryLight)||void 0===e?void 0:e.replace("#",""),this.primaryDark=null===(n=t.primaryDark)||void 0===n?void 0:n.replace("#",""),this.primaryBg=null===(r=t.primaryBg)||void 0===r?void 0:r.replace("#",""),this.bg=null===(s=t.bg)||void 0===s?void 0:s.replace("#",""),this.bgDark=null===(o=t.bgDark)||void 0===o?void 0:o.replace("#",""),this.textColor=null===(a=t.textColor)||void 0===a?void 0:a.replace("#",""),this.textLight=null===(i=t.textLight)||void 0===i?void 0:i.replace("#",""),this.textMuted=null===(h=t.textMuted)||void 0===h?void 0:h.replace("#",""),this.borderColor=null===(c=t.borderColor)||void 0===c?void 0:c.replace("#",""),this.borderLight=null===(l=t.borderLight)||void 0===l?void 0:l.replace("#",""),this.fontFamily=t.fontFamily,this.logoUrl=t.logoUrl,this.theme=ct(t.theme,this.floating?"system":"light"),this.layout="bubbles"===t.layout||"lines"===t.layout?t.layout:void 0,this.position="bottom-left"===t.position?"bottom-left":"bottom-right",this.preload=!1!==t.preload,this.embedMode=t.embedMode||"auto",this.appVersion=t.appVersion||"1.0.0"}themeRecord(){const t={};return J(this,t,X),this.hasExplicitPrimary||delete t.primaryColor,this.hasExplicitSecondary||delete t.secondaryColor,t}toQueryParams(){const t=this.themeRecord();return this.layout&&(t.layout=this.layout),new URLSearchParams(t).toString()}toPostMessagePayload(){return{type:"livechatta:theme",...this.themeRecord()}}}const ut=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function pt(t){const e="string"==typeof t?/^(\d{1,2}):(\d{2})$/.exec(t.trim()):null;if(!e)return null;const n=+e[1],r=+e[2];return n<=24&&r<60&&60*n+r<=1440?60*n+r:null}function dt(t,e){try{const n=new Intl.DateTimeFormat("en-US",{timeZone:e,weekday:"short",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(t),r=t=>{var e;return(null===(e=n.find(e=>e.type===t))||void 0===e?void 0:e.value)||""},s=ut.indexOf(r("weekday")),o=+r("hour")%24*60+ +r("minute");return s<0||!Number.isFinite(o)?null:{day:s,minutes:o}}catch(t){return null}}function Et(t){if(!t||!1===t.enabled||!Array.isArray(t.windows))return[];const e=[];for(const n of t.windows){const t=pt(null==n?void 0:n.open),r=pt(null==n?void 0:n.close);null!==t&&null!==r&&n.day>=0&&n.day<=6&&t!==r&&e.push({day:Math.floor(n.day),open:t,close:r})}return e}function mt(t,e=new Date){const n=Et(t);if(!n.length)return!0;const r=dt(e,t.timezone);if(!r)return!0;const s=(r.day+6)%7;return n.some(t=>t.open<t.close?t.day===r.day&&r.minutes>=t.open&&r.minutes<t.close:t.day===r.day&&r.minutes>=t.open||t.day===s&&r.minutes<t.close)}function yt(t){return`${Math.floor(t/60)%24}:${String(t%60).padStart(2,"0")}`}function Tt(t,e=new Date){const n=Et(t),r=n.length?dt(e,t.timezone):null;if(!r)return null;for(let e=0;e<=7;e++){const s=(r.day+e)%7,o=n.filter(t=>t.day===s&&(e>0||t.open>r.minutes)).map(t=>t.open);if(!o.length)continue;const a=0===e?"today":1===e?"tomorrow":ut[s],i=t.timezoneLabel?` ${t.timezoneLabel}`:"";return`${a} ${yt(Math.min(...o))}${i}`}return null}function gt(t,e=new Date){return mt(t,e)?null:{backAt:Tt(t,e),message:null==t?void 0:t.awayMessage}}const Ct=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,St=/^[A-Za-z][\w-]{0,39}$/;function vt(t){var e;if(!t)return null;const n=!0===t?{}:t;if(!1===n.enabled)return null;let r=Array.isArray(n.fields)?n.fields.filter(t=>t&&St.test(t.name)&&t.label):[];if(!r.length){r=[{name:"name",label:"Your name",type:"text",required:!0},{name:"email",label:"Email",type:"email",required:!0}];const t=(n.topics||[]).filter(t=>"string"==typeof t&&t.trim());t.length&&r.push({name:"topic",label:"What do you need?",type:"select",required:!0,options:t})}return{...n,fields:r,submitLabel:n.submitLabel||"Start chat",note:null!==(e=n.note)&&void 0!==e?e:"We only use your email to reply."}}function Ot(t,e){var n;const r={};for(const s of t){const t=(e[s.name]||"").trim();t?"email"!==s.type||Ct.test(t)?"select"===s.type&&(null===(n=s.options)||void 0===n?void 0:n.length)&&!s.options.includes(t)?r[s.name]="Choose an option":t.length>500&&(r[s.name]="Keep this under 500 characters"):r[s.name]="Enter an email like name@example.com":s.required&&(r[s.name]="select"===s.type?"Choose an option":`Enter ${s.label.toLowerCase()}`)}return r}const At={surface:"#FFFFFF",text:"#191715",text2:"#5A544F",line:"#DEDAD0",bubble:"#FFFFFF",lineStrong:"#8F887C",danger:"#B4123A",info:"#1E56C2",infoSoft:"#E3ECFB",focus:"#1E56C2",shadow2:"0 8px 24px rgba(25,23,21,0.10), 0 2px 6px rgba(25,23,21,0.06)",shadow3:"0 24px 64px rgba(25,23,21,0.18), 0 4px 12px rgba(25,23,21,0.08)"},bt={surface:"#1B1A17",text:"#F3F0EA",text2:"#BFB8AC",line:"#34312C",bubble:"#24221F",lineStrong:"#8A8378",danger:"#F26B8A",info:"#7AA7FF",infoSoft:"#142039",focus:"#7AA7FF",shadow2:"0 8px 24px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.06)",shadow3:"0 24px 64px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08)"};function _t(t){return`--lc-surface:${t.surface};--lc-text:${t.text};--lc-text-2:${t.text2};--lc-line:${t.line};--lc-bubble-in:${t.bubble};--lc-focus:${t.focus};--lc-shadow-2:${t.shadow2};--lc-shadow-3:${t.shadow3};--lc-line-strong:${t.lineStrong};--lc-danger:${t.danger};--lc-info:${t.info};--lc-info-soft:${t.infoSoft};`}const ft=`\n:host{all:initial}\n.lc{${_t(At)}color-scheme:light;position:fixed;bottom:calc(20px + env(safe-area-inset-bottom,0px));right:calc(20px + env(safe-area-inset-right,0px));display:flex;flex-direction:column;align-items:flex-end;gap:12px;font:400 15px/22px "Atkinson Hyperlegible Next","Atkinson Hyperlegible",system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--lc-text);-webkit-font-smoothing:antialiased}\n.lc[data-theme="dark"]{${_t(bt)}color-scheme:dark}\n.lc[data-pos="bottom-left"]{right:auto;left:calc(20px + env(safe-area-inset-left,0px));align-items:flex-start}\n.lc *,.lc *::before,.lc *::after{box-sizing:border-box}\n:where(.lc) button{font:inherit;color:inherit;cursor:pointer}\n.lc :focus-visible{outline:3px solid var(--lc-focus);outline-offset:2px}\n.lc-btn{position:relative;width:60px;height:60px;border:0;padding:0;border-radius:20px 20px 5px 20px;background:var(--lc-brand);color:var(--lc-on-brand);display:grid;place-items:center;box-shadow:var(--lc-shadow-3);transition:transform .15s ease}\n.lc[data-pos="bottom-left"] .lc-btn{border-radius:20px 20px 20px 5px}\n.lc-btn:hover{transform:translateY(-2px)}\n.lc-btn:active{transform:translateY(0) scale(.97)}\n.lc-btn svg{width:26px;height:26px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}\n.lc-btn .lc-ic-close{display:none}\n.lc[data-open="true"] .lc-btn .lc-ic-chat{display:none}\n.lc[data-open="true"] .lc-btn .lc-ic-close{display:block}\n.lc-count{position:absolute;top:-6px;right:-6px;min-width:22px;height:22px;padding:0 6px;border-radius:9999px;background:var(--lc-accent);color:var(--lc-on-accent);box-shadow:0 0 0 2px var(--lc-surface);font:700 11px/22px "JetBrains Mono",ui-monospace,"SF Mono",Menlo,monospace;text-align:center;font-variant-numeric:tabular-nums}\n.lc[data-pos="bottom-left"] .lc-count{right:auto;left:-6px}\n.lc-count[hidden],.lc[data-open="true"] .lc-count{display:none}\n.lc-greet{display:flex;align-items:flex-start;gap:4px;max-width:260px;padding:8px 6px 8px 12px;border-radius:20px 20px 4px 20px;background:var(--lc-bubble-in);color:var(--lc-text);box-shadow:var(--lc-shadow-2);animation:lc-in .2s ease}\n.lc[data-pos="bottom-left"] .lc-greet{border-radius:20px 20px 20px 4px}\n.lc-greet[hidden],.lc[data-open="true"] .lc-greet{display:none}\n.lc-greet__text{flex:1;border:0;background:none;padding:0;text-align:start;font-size:15px;line-height:22px}\n.lc-x{flex:none;width:28px;height:28px;border:0;border-radius:9999px;background:none;display:grid;place-items:center;color:var(--lc-text-2)}\n.lc-x:hover{background:var(--lc-line)}\n.lc-x svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round}\n.lc-panel{width:var(--lc-w);height:var(--lc-h);max-width:calc(100vw - 40px);max-height:calc(100vh - 120px);display:flex;flex-direction:column;border-radius:20px;overflow:hidden;background:var(--lc-surface);box-shadow:var(--lc-shadow-3);transform-origin:bottom right;transition:opacity .16s ease,transform .16s ease,visibility 0s linear .16s}\n.lc[data-pos="bottom-left"] .lc-panel{transform-origin:bottom left}\n.lc[data-open="false"] .lc-panel{visibility:hidden;opacity:0;transform:translateY(8px) scale(.98);pointer-events:none;position:absolute;bottom:72px}\n.lc[data-pos="bottom-right"][data-open="false"] .lc-panel{right:0}\n.lc[data-pos="bottom-left"][data-open="false"] .lc-panel{left:0}\n.lc[data-open="true"] .lc-panel{visibility:visible;opacity:1;transform:none;transition-delay:0s}\n.lc-head{flex:none;display:flex;align-items:center;gap:10px;padding:12px 10px 12px 14px;background:var(--lc-brand);color:var(--lc-on-brand)}\n.lc-logo{flex:none;width:32px;height:32px;border-radius:14px 14px 14px 4px;background:var(--lc-surface);color:var(--lc-brand-text);display:grid;place-items:center;overflow:hidden;font:800 11px/1 "Schibsted Grotesk","Helvetica Neue",Arial,sans-serif}\n.lc-logo img{width:100%;height:100%;object-fit:cover}\n.lc-head__t{flex:1;min-width:0;display:grid}\n.lc-head__t b{font:700 15px/20px "Schibsted Grotesk","Helvetica Neue",Arial,sans-serif;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n.lc-head__t span{font-size:12px;line-height:16px;opacity:.9}\n.lc-head .lc-x{width:40px;height:40px;color:inherit}\n.lc-head .lc-x:hover{background:rgba(127,127,127,.22)}\n.lc-head .lc-x:focus-visible{outline-color:currentColor;outline-offset:-3px}\n.lc-head__t span[hidden]{display:none}\n.lc-body{position:relative;flex:1;min-height:0;background:var(--lc-surface)}\n.lc-body iframe{display:block;width:100%;height:100%;border:0}\n.lc-gate{position:absolute;inset:0;overflow:auto;padding:16px;display:grid;align-content:start;gap:12px;background:var(--lc-surface)}\n.lc-gate[hidden]{display:none}\n.lc-gate p{margin:0}\n.lc-form{display:grid;gap:12px}\n.lc-f{display:grid;gap:4px}\n.lc-f label{font-size:13px;line-height:18px;font-weight:600;color:var(--lc-text-2)}\n.lc-in{width:100%;min-height:44px;padding:10px 12px;border:1px solid var(--lc-line-strong);border-radius:10px;background:var(--lc-surface);color:var(--lc-text);font:inherit}\ntextarea.lc-in{min-height:96px;resize:vertical}\n.lc-in[aria-invalid="true"]{border-color:var(--lc-danger);box-shadow:0 0 0 1px var(--lc-danger)}\n.lc-err{font-size:13px;line-height:18px;color:var(--lc-danger)}\n.lc-err:empty{display:none}\n.lc-go{min-height:48px;border:0;border-radius:10px;padding:0 16px;background:var(--lc-brand);color:var(--lc-on-brand);font-weight:700}\n.lc-go[disabled]{opacity:.6;cursor:progress}\n.lc-link{border:0;background:none;padding:10px 0;min-height:44px;color:var(--lc-brand-text);font-weight:600;text-decoration:underline;text-align:start}\n.lc-note{font-size:12px;line-height:16px;color:var(--lc-text-2)}\n.lc-ban{display:flex;gap:10px;align-items:flex-start;padding:12px;border-radius:10px;background:var(--lc-info-soft);color:var(--lc-text)}\n.lc-ban svg{flex:none;width:20px;height:20px;fill:none;stroke:var(--lc-info);stroke-width:2;stroke-linecap:round}\n@media (max-width:640px){\n.lc{bottom:calc(16px + env(safe-area-inset-bottom,0px));right:calc(16px + env(safe-area-inset-right,0px))}\n.lc[data-pos="bottom-left"]{left:calc(16px + env(safe-area-inset-left,0px))}\n.lc[data-open="true"]{inset:0;gap:0}\n.lc[data-open="true"] .lc-btn{display:none}\n.lc-panel{max-width:none;max-height:none}\n.lc[data-open="true"] .lc-panel{position:fixed;inset:0;width:100vw;height:100vh;height:100dvh;border-radius:0;padding-top:env(safe-area-inset-top,0px)}\n.lc[data-open="false"] .lc-panel{position:fixed;inset:0;width:100vw;height:100vh;bottom:auto;border-radius:0}\n.lc-head{min-height:56px}\n}\n@media (prefers-reduced-motion:reduce){.lc *{transition:none!important;animation:none!important}}\n@keyframes lc-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}\n`,Rt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>';function xt(t,e,n){const r=document.createElement(t);return e&&(r.className=e),n&&(r.textContent=n),r}let Pt=0;function It(){try{return"undefined"!=typeof window?window.localStorage:null}catch(t){return null}}class wt{constructor(t){var e;this.cfg=t,this.preChat=null,this.preChatValues=null,this.hours=null,this.awayDismissed=!1,this.awaySent=!1,this.gateKind="",this.linkAccent=null,this.iframe=null,this.pendingSrc=null,this.opened=!1,this.unread=0,this.frameMode=null,this.linkBrand=null,this.greetTimer=null,this.mql=null,this.prevOverflow=null,this.onMql=()=>this.applyTheme(),this.onResize=()=>this.syncModal();const n="lc-panel-"+ ++Pt;this.pid=n,this.mode=t.theme||"system",this.explicitBrand=st(t.brandColor)?rt(t.brandColor):null,this.explicitAccent=rt(t.secondaryColor),this.preChat=vt(t.preChat),this.hours=t.businessHours||null,this.host=document.createElement("div"),this.host.setAttribute("data-livechatta-launcher",""),this.root=this.host.attachShadow({mode:"open"});const r=document.createElement("style");r.textContent=ft,this.root.appendChild(r);const s=t.title||"Chat";this.wrap=document.createElement("div"),this.wrap.className="lc",this.wrap.setAttribute("data-pos","bottom-left"===t.position?"bottom-left":"bottom-right"),this.wrap.setAttribute("data-open","false"),this.wrap.style.zIndex=String(null!==(e=t.zIndex)&&void 0!==e?e:2147483e3),this.wrap.style.setProperty("--lc-w",t.width||"380px"),this.wrap.style.setProperty("--lc-h",t.height||"640px"),this.panel=document.createElement("div"),this.panel.className="lc-panel",this.panel.id=n,this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label",s),this.panel.setAttribute("aria-modal","false"),this.panel.setAttribute("inert","");const o=document.createElement("div");o.className="lc-head";const a=document.createElement("span");if(a.className="lc-logo",a.setAttribute("aria-hidden","true"),t.logoUrl&&/^https:\/\//.test(t.logoUrl)){const e=document.createElement("img");e.src=t.logoUrl,e.alt="",a.appendChild(e)}else a.textContent=function(t){var e,n;const r=t.trim().split(/\s+/).filter(Boolean);return(((null===(e=r[0])||void 0===e?void 0:e[0])||"L")+((null===(n=r[1])||void 0===n?void 0:n[0])||"")).toUpperCase()}(s);const i=document.createElement("div");i.className="lc-head__t";const h=document.createElement("b");h.textContent=s,this.sub=xt("span"),i.append(h,this.sub),this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="lc-x",this.closeBtn.setAttribute("aria-label","Close chat"),this.closeBtn.innerHTML=Rt,this.closeBtn.addEventListener("click",()=>this.close()),o.append(a,i,this.closeBtn),this.body=document.createElement("div"),this.body.className="lc-body",this.gate=xt("div","lc-gate"),this.gate.hidden=!0,this.body.appendChild(this.gate),this.panel.append(o,this.body),this.greet=document.createElement("div"),this.greet.className="lc-greet",this.greet.hidden=!0;const c=document.createElement("button");c.type="button",c.className="lc-greet__text",c.textContent=t.greeting||"",c.addEventListener("click",()=>this.open());const l=document.createElement("button");l.type="button",l.className="lc-x",l.setAttribute("aria-label","Dismiss greeting"),l.innerHTML=Rt,l.addEventListener("click",()=>this.dismissGreeting(!0)),this.greet.append(c,l),this.greet.setAttribute("role","status"),this.btn=document.createElement("button"),this.btn.type="button",this.btn.className="lc-btn",this.btn.setAttribute("aria-controls",n),this.btn.setAttribute("aria-expanded","false"),this.btn.innerHTML='<svg class="lc-ic-chat" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 5h14v10H9l-4 4z"/></svg><svg class="lc-ic-close" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>',this.count=document.createElement("span"),this.count.className="lc-count",this.count.hidden=!0,this.count.setAttribute("aria-hidden","true"),this.btn.appendChild(this.count),this.btn.addEventListener("click",()=>this.toggle()),this.wrap.append(this.panel,this.greet,this.btn),this.wrap.addEventListener("keydown",t=>{"Escape"===t.key&&(this.opened?(t.stopPropagation(),this.close()):this.greet.hidden||this.dismissGreeting(!0))}),this.root.appendChild(this.wrap),this.updateLabel(),this.applyBrand(),this.applyTheme(),this.renderGate()}mount(t,e){var n,r;this.iframe=t,this.pendingSrc=e||null,this.body.insertBefore(t,this.gate),this.syncFrameInert(),document.body.appendChild(this.host),"function"==typeof window.matchMedia&&(this.mql=window.matchMedia("(prefers-color-scheme: dark)"),this.mql.addEventListener?this.mql.addEventListener("change",this.onMql):null===(r=(n=this.mql).addListener)||void 0===r||r.call(n,this.onMql)),window.addEventListener("resize",this.onResize),this.applyTheme(),this.cfg.autoOpen?this.open(!1):this.scheduleGreeting()}open(t=!0){var e,n;this.opened||(this.pendingSrc&&this.iframe&&(this.iframe.src=this.pendingSrc,this.pendingSrc=null),this.opened=!0,this.wrap.setAttribute("data-open","true"),this.panel.removeAttribute("inert"),this.btn.setAttribute("aria-expanded","true"),this.dismissGreeting(!0),this.updateLabel(),this.syncModal(),this.renderGate(),t&&(this.firstGateControl()||this.closeBtn).focus(),null===(n=(e=this.cfg).onOpenChange)||void 0===n||n.call(e,!0))}close(){var t,e;this.opened&&(this.opened=!1,this.wrap.setAttribute("data-open","false"),this.panel.setAttribute("inert",""),this.btn.setAttribute("aria-expanded","false"),this.updateLabel(),this.syncModal(),this.btn.focus(),null===(e=(t=this.cfg).onOpenChange)||void 0===e||e.call(t,!1))}toggle(){this.opened?this.close():this.open()}isOpen(){return this.opened}setUnread(t){const e="number"==typeof t?t:Number(null==t?void 0:t.count);this.unread=Number.isFinite(e)&&e>0?Math.floor(e):0,this.count.hidden=0===this.unread,this.count.textContent=this.unread>99?"99+":String(this.unread),this.updateLabel()}setLinkBrand(t){this.linkBrand=st(t)?rt(t):null,this.applyBrand()}setLinkSecondary(t){this.linkAccent=rt(t),this.applyBrand()}setWidgetConfig(t){void 0===this.cfg.preChat&&t.preChat&&(this.preChat=vt(t.preChat)),!this.cfg.businessHours&&t.businessHours&&(this.hours=t.businessHours),this.renderGate()}getGate(){return this.gateKind}setBrand(t){this.explicitBrand=st(t)?rt(t):null,this.applyBrand()}setTheme(t){this.mode=t,this.frameMode=null,this.applyTheme()}setFrameMode(t){this.frameMode="dark"===t||"light"===t?t:null,this.applyTheme()}getEffectiveMode(){var t;return this.frameMode?this.frameMode:"system"!==this.mode?this.mode:(null===(t=this.mql)||void 0===t?void 0:t.matches)?"dark":"light"}destroy(){var t,e,n,r;this.greetTimer&&clearTimeout(this.greetTimer),(null===(t=this.mql)||void 0===t?void 0:t.removeEventListener)?this.mql.removeEventListener("change",this.onMql):null===(n=null===(e=this.mql)||void 0===e?void 0:e.removeListener)||void 0===n||n.call(e,this.onMql),window.removeEventListener("resize",this.onResize),this.opened&&(this.opened=!1,this.syncModal()),null===(r=this.host.parentNode)||void 0===r||r.removeChild(this.host),this.iframe=null}brand(){return this.explicitBrand||this.linkBrand||Z}applyBrand(){const t=this.brand();this.wrap.style.setProperty("--lc-brand",t),this.wrap.style.setProperty("--lc-on-brand",it(t));const e=this.explicitAccent||this.linkAccent||t;this.wrap.style.setProperty("--lc-accent",e),this.wrap.style.setProperty("--lc-on-accent",it(e)),this.applyBrandText()}applyBrandText(){const t="dark"===this.getEffectiveMode()?bt.surface:At.surface;this.wrap.style.setProperty("--lc-brand-text",ht(this.brand(),t))}applyTheme(){this.wrap.setAttribute("data-theme",this.getEffectiveMode()),this.applyBrandText()}updateLabel(){const t=this.cfg.launcherLabel||"Open chat",e=this.opened?"Close chat":this.unread?`${t}, ${this.unread} unread`:t;this.btn.setAttribute("aria-label",e)}greetingKey(){return`livechatta:greeting-dismissed:${this.cfg.storageKey}`}scheduleGreeting(){var t,e;const n=this.cfg.greeting;if(!n)return;try{if((null===(t=It())||void 0===t?void 0:t.getItem(this.greetingKey()))===n)return}catch(t){}const r=Math.max(0,null!==(e=this.cfg.greetingDelay)&&void 0!==e?e:1e4);this.greetTimer=setTimeout(()=>{this.opened||(this.greet.hidden=!1)},r)}dismissGreeting(t){var e;this.greetTimer&&(clearTimeout(this.greetTimer),this.greetTimer=null);const n=!this.greet.hidden;if(this.greet.hidden=!0,t&&this.cfg.greeting)try{null===(e=It())||void 0===e||e.setItem(this.greetingKey(),this.cfg.greeting)}catch(t){}n&&!this.opened&&this.root.activeElement&&this.btn.focus()}preChatKey(){return`livechatta:prechat-done:${this.cfg.storageKey}`}preChatDone(){var t;if(this.preChatValues)return!0;try{return"1"===(null===(t=It())||void 0===t?void 0:t.getItem(this.preChatKey()))}catch(t){return!1}}renderGate(){var t,e;const n=this.hours&&!this.awayDismissed?gt(this.hours,null===(e=(t=this.cfg).now)||void 0===e?void 0:e.call(t)):null,r=this.preChat&&!this.preChatDone()?"prechat":n?"away":"";this.sub.textContent=n?"Away"+(n.backAt?` · back ${n.backAt}`:""):this.cfg.subtitle||"",this.sub.hidden=!this.sub.textContent,r===this.gateKind&&"away"!==r||"away"===r&&"away"===this.gateKind&&this.gate.contains(this.root.activeElement)||(this.gateKind=r,this.gate.textContent="",this.gate.hidden=!r,"prechat"===r?this.buildPreChat():"away"===r&&this.buildAway(n),this.syncFrameInert())}syncFrameInert(){this.iframe&&(this.gateKind?this.iframe.setAttribute("inert",""):this.iframe.removeAttribute("inert"))}firstGateControl(){return this.gateKind?this.gate.querySelector("input,select,textarea,button"):null}uncover(){this.renderGate(),this.opened&&(this.firstGateControl()||this.closeBtn).focus()}field(t,e,n,r=!0){const s=xt("div","lc-f"),o=xt("label","",e);o.htmlFor=t,n.id=t,n.classList.add("lc-in");const a=xt("p","lc-err");return a.id=`${t}-err`,n.setAttribute("aria-describedby",a.id),s.append(o,n,a),r&&this.gate.appendChild(s),a}buildPreChat(){const t=this.preChat,e=xt("form","lc-form");e.noValidate=!0,e.setAttribute("aria-label","Before we start"),t.intro&&e.appendChild(xt("p","",t.intro));const n={},r={};for(const s of t.fields){let t;if("select"===s.type){const e=xt("select");e.appendChild(new Option("Choose…","")),(s.options||[]).forEach(t=>e.appendChild(new Option(t,t))),t=e}else if("textarea"===s.type)t=xt("textarea");else{const e=xt("input");e.type=s.type||"text","name"===s.name&&(e.autocomplete="name"),"email"===s.type&&(e.autocomplete="email"),t=e}t.name=s.name,s.required&&(t.required=!0),!s.placeholder||t instanceof HTMLSelectElement||(t.placeholder=s.placeholder),r[s.name]=t,n[s.name]=this.field(`${this.pid}-${s.name}`,s.label,t,!1),e.appendChild(n[s.name].parentElement)}const s=xt("p","lc-err");s.setAttribute("role","alert");const o=xt("button","lc-go",t.submitLabel);o.type="submit",e.append(s,o),t.note&&e.appendChild(xt("p","lc-note",t.note)),e.addEventListener("submit",async e=>{var a,i,h,c,l;e.preventDefault();const u={};for(const t of Object.keys(r))u[t]=r[t].value.trim();const p=Ot(t.fields,u);s.textContent="";for(const t of Object.keys(r))n[t].textContent=p[t]||"",r[t].setAttribute("aria-invalid",p[t]?"true":"false");const d=Object.keys(r).find(t=>p[t]);if(d)return r[d].focus();o.disabled=!0,o.setAttribute("aria-busy","true");try{await(null===(i=(a=this.cfg).onPreChatSubmit)||void 0===i?void 0:i.call(a,u))}catch(t){return o.disabled=!1,o.removeAttribute("aria-busy"),void(s.textContent="Couldn't start the chat. Check your connection and try again.")}this.preChatValues=u;try{null===(h=It())||void 0===h||h.setItem(this.preChatKey(),"1")}catch(t){}null===(l=(c=this.cfg).onPreChatComplete)||void 0===l||l.call(c,u),this.uncover()}),this.gate.appendChild(e)}buildAway(t){const e=xt("div","lc-ban");e.setAttribute("role","status"),e.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>';const n=xt("p");n.append(xt("b","","We're away"),document.createTextNode(t.backAt?` · back ${t.backAt}.`:".")),t.message&&n.append(document.createTextNode(` ${t.message}`)),e.appendChild(n),this.gate.appendChild(e);const r=xt("button","lc-link","Continue to chat");r.type="button",r.addEventListener("click",()=>{this.awayDismissed=!0,this.uncover()});const s=this.cfg.onAwayMessage;if(!s||this.awaySent)return this.awaySent&&this.gate.appendChild(xt("p","","Thanks, your message is with the team. We'll reply by email.")),void this.gate.appendChild(r);const o=xt("textarea"),a=this.field(`${this.pid}-away`,"Your message",o),i=xt("button","lc-go","Send");i.type="button",i.addEventListener("click",async()=>{var t;const e=o.value.trim();if(a.textContent=e?"":"Write a message first",o.setAttribute("aria-invalid",e?"false":"true"),!e)return o.focus();i.disabled=!0,i.setAttribute("aria-busy","true");try{await s(e,this.preChatValues)}catch(t){return i.disabled=!1,i.removeAttribute("aria-busy"),void(a.textContent="Couldn't send. Try again.")}this.awaySent=!0,this.gateKind="",this.renderGate(),null===(t=this.gate.querySelector(".lc-link"))||void 0===t||t.focus()}),this.gate.append(i,r)}syncModal(){const t=this.opened&&"undefined"!=typeof window&&window.innerWidth<=640;this.panel.setAttribute("aria-modal",t?"true":"false");const e=document.documentElement;t&&null===this.prevOverflow?(this.prevOverflow=e.style.overflow,e.style.overflow="hidden"):t||null===this.prevOverflow||(e.style.overflow=this.prevOverflow,this.prevOverflow=null)}}const Nt="0123456789abcdef";async function Lt(t,e){return"undefined"!=typeof crypto&&void 0!==crypto.subtle?async function(t,e){const n=await crypto.subtle.importKey("raw",(new TextEncoder).encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return function(t){const e=new Uint8Array(t);let n="";for(let t=0;t<e.length;t++){const r=e[t];n+=Nt[r>>>4]+Nt[15&r]}return n}(await crypto.subtle.sign("HMAC",n,(new TextEncoder).encode(t)))}(t,e):"undefined"!=typeof window||"undefined"==typeof globalThis||void 0===globalThis.process?function(t,e){const n=new TextEncoder,r=n.encode(e),s=n.encode(t),o=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function a(t,e){return e>>>t|e<<32-t}function i(t){let e=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,h=2600822924,c=528734635,l=1541459225;const u=t.length,p=8*u,d=u+9+63&-64,E=new Uint8Array(d);E.set(t),E[u]=128;const m=new DataView(E.buffer);m.setUint32(d-4,p,!1);const y=new Uint32Array(64);for(let t=0;t<d;t+=64){for(let e=0;e<16;e++)y[e]=m.getUint32(t+4*e,!1);for(let t=16;t<64;t++){const e=a(7,y[t-15])^a(18,y[t-15])^y[t-15]>>>3,n=a(17,y[t-2])^a(19,y[t-2])^y[t-2]>>>10;y[t]=y[t-16]+e+y[t-7]+n|0}let u=e,p=n,d=r,E=s,T=i,g=h,C=c,S=l;for(let t=0;t<64;t++){const e=S+(a(6,T)^a(11,T)^a(25,T))+(T&g^~T&C)+o[t]+y[t]|0,n=u&p^u&d^p&d;S=C,C=g,g=T,T=E+e|0,E=d,d=p,p=u,u=e+((a(2,u)^a(13,u)^a(22,u))+n|0)|0}e=e+u|0,n=n+p|0,r=r+d|0,s=s+E|0,i=i+T|0,h=h+g|0,c=c+C|0,l=l+S|0}const T=new Uint8Array(32),g=new DataView(T.buffer);return g.setUint32(0,e,!1),g.setUint32(4,n,!1),g.setUint32(8,r,!1),g.setUint32(12,s,!1),g.setUint32(16,i,!1),g.setUint32(20,h,!1),g.setUint32(24,c,!1),g.setUint32(28,l,!1),T}const h=64;let c=r;c.length>h&&(c=i(c));const l=new Uint8Array(h);l.set(c);const u=new Uint8Array(h),p=new Uint8Array(h);for(let t=0;t<h;t++)u[t]=54^l[t],p[t]=92^l[t];const d=new Uint8Array(h+s.length);d.set(u),d.set(s,h);const E=i(d),m=new Uint8Array(96);m.set(p),m.set(E,h);const y=i(m);return Array.from(y).map(t=>t.toString(16).padStart(2,"0")).join("")}(t,e):async function(t,e){const{createHmac:n}=await(import("crypto"));return n("sha256",e).update(t).digest("hex")}(t,e)}async function Dt(t){if(!t.linkCode)throw new Error("LiveChatta.signAppRequest: linkCode is required");if(!t.platform)throw new Error("LiveChatta.signAppRequest: platform is required");if(!t.version)throw new Error("LiveChatta.signAppRequest: version is required");if(!t.apiKey)throw new Error("LiveChatta.signAppRequest: apiKey is required");const e=`${t.linkCode}:${t.platform}:${t.version}`,n=await Lt(e,t.apiKey),r=`CHATTA-APP:${t.platform}:${t.version}:${n}`;return{header:r,querySig:encodeURIComponent(r),signature:n,platform:t.platform,version:t.version}}const kt="microphone *; camera *; display-capture *; clipboard-write *; autoplay *; fullscreen *; picture-in-picture *; clipboard-read *; encrypted-media *; screen-wake-lock *; web-share *; geolocation *; gyroscope *; accelerometer *; magnetometer *; speaker-selection *",Mt="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-presentation allow-downloads allow-orientation-lock";function Ht(t){const e={};for(const n of Object.keys(t))void 0!==t[n]&&null!==t[n]&&(e[n]=t[n]);return e}class Ut{constructor(t,e,n){this.config=t,this.tokenManager=e,this.loadWidgetConfig=n,this.iframe=null,this.embedConfig=null,this.options=null,this.launcher=null,this.unsubs=[],this.bridge=new z({allowedOrigin:this.config.baseUrl})}async mount(t){this.options={...t},this.embedConfig=new lt(t);const e=this.embedConfig;let n=null;if(!e.floating)if("string"==typeof e.container){const t=document.querySelector(e.container);if(!t)throw new Error(`LiveChatta UI: container "${e.container}" not found`);n=t}else n=e.container;const r=await this.buildEmbedUrl();return this.iframe=document.createElement("iframe"),this.iframe.setAttribute("allow",kt),this.iframe.setAttribute("sandbox",Mt),this.iframe.setAttribute("allowfullscreen",""),this.iframe.style.border="none",j(this.iframe),e.floating?this.mountFloating(this.iframe,r,t):(this.iframe.src=r,this.iframe.style.width=e.width,this.iframe.style.height=e.height,this.iframe.style.borderRadius="12px",this.iframe.setAttribute("loading","lazy"),this.iframe.title="LiveChatta workspace",n.innerHTML="",n.appendChild(this.iframe)),this.bridge.attach(this.iframe),this.iframe}mountFloating(t,e,n){const r=this.embedConfig;t.title=`${n.title||"LiveChatta"} chat`,this.launcher=new wt({storageKey:this.config.linkCode,position:r.position,theme:r.theme,brandColor:r.hasExplicitPrimary?`#${r.primaryColor}`:void 0,title:n.title,subtitle:n.subtitle,logoUrl:n.logoUrl,launcherLabel:n.launcherLabel,greeting:n.greeting,greetingDelay:n.greetingDelay,zIndex:n.zIndex,autoOpen:n.autoOpen,width:r.width,height:r.height,onOpenChange:n.onOpenChange,secondaryColor:r.hasExplicitSecondary?`#${r.secondaryColor}`:void 0,preChat:n.preChat,onPreChatSubmit:n.onPreChatSubmit,onPreChatComplete:e=>{var n;null===(n=t.contentWindow)||void 0===n||n.postMessage({type:B.preChat,payload:e},this.config.baseUrl)},businessHours:n.businessHours,onAwayMessage:n.onAwayMessage}),r.preload?(t.src=e,this.launcher.mount(t)):this.launcher.mount(t,e);const s=this.launcher,o=this.config.baseUrl,a=e=>{e.source!==t.contentWindow||e.origin!==o&&"null"!==e.origin||Y(s,e.data)};window.addEventListener("message",a),this.unsubs.push(()=>window.removeEventListener("message",a)),!1!==n.linkConfig&&this.loadWidgetConfig&&this.applyLinkWidget(s)}applyLinkWidget(t){this.loadWidgetConfig().then(e=>{e&&this.launcher===t&&t.setWidgetConfig({preChat:e.preChat,businessHours:e.businessHours})}).catch(()=>{})}unmount(){var t,e;this.unsubs.forEach(t=>t()),this.unsubs=[],this.bridge.detach(),null===(t=this.launcher)||void 0===t||t.destroy(),this.launcher=null,(null===(e=this.iframe)||void 0===e?void 0:e.parentNode)&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null,this.embedConfig=null,this.options=null}getIframe(){return this.iframe}getLauncher(){return this.launcher}open(){var t;null===(t=this.launcher)||void 0===t||t.open()}close(){var t;null===(t=this.launcher)||void 0===t||t.close()}toggle(){var t;null===(t=this.launcher)||void 0===t||t.toggle()}isOpen(){var t,e;return null!==(e=null===(t=this.launcher)||void 0===t?void 0:t.isOpen())&&void 0!==e&&e}setUnread(t){var e;null===(e=this.launcher)||void 0===e||e.setUnread(t)}async updateTheme(t){if(!this.iframe||!this.embedConfig||!this.options)return;this.options={...this.options,...Ht(t)};const e=new lt(this.options);this.embedConfig=e,this.launcher&&(t.primaryColor&&this.launcher.setBrand(t.primaryColor),t.theme&&this.launcher.setTheme(e.theme));const n=this.iframe.contentWindow;n?(n.postMessage(e.toPostMessagePayload(),this.config.baseUrl),t.theme&&n.postMessage({type:"CHATTA_APP:theme",mode:ct(t.theme,"system")},this.config.baseUrl)):this.iframe.src=await this.buildEmbedUrl()}async buildEmbedUrl(){var t,e,n;const r=await this.tokenManager.getToken(),s=(null===(t=this.embedConfig)||void 0===t?void 0:t.toQueryParams())||"",o=i(),a=(null===(e=this.embedConfig)||void 0===e?void 0:e.embedMode)||"auto";if(!("app"===a||"auto"===a&&o.isAppShell))return`${this.config.embedUrl}?token=${encodeURIComponent(r)}${s?`&${s}`:""}`;const h=await Dt({linkCode:this.config.linkCode,platform:"web"===o.platform?"web":o.platform,version:(null===(n=this.embedConfig)||void 0===n?void 0:n.appVersion)||"1.0.0",apiKey:this.config.apiKey});return`${this.config.appEmbedUrl}?token=${encodeURIComponent(r)}&_app_sig=${h.querySig}`+(s?`&${s}`:"")}}class Gt{constructor(){this.config=null,this.tokenManager=null,this.eventBus=null,this.socketTransport=null,this.socketAPI=null,this.httpTransport=null,this.httpAPI=null,this.embedUI=null,this.permissionsApi=new h,this.initialized=!1}init(t){this.config=new e(t),this.eventBus=new s,this.tokenManager=new r(this.config.apiKey,this.config.linkCode,this.config.chatUsername,this.config.publicKey),this.config.enableSocket&&(this.socketTransport=new x(this.config,this.tokenManager,this.eventBus),this.socketAPI=new I(this.socketTransport,this.eventBus)),this.config.enableHttp&&(this.httpTransport=new R(this.config,this.tokenManager,this.eventBus),this.httpAPI=new W(this.httpTransport));const n=this.config.linkCode;return this.embedUI=new Ut(this.config,this.tokenManager,this.httpAPI?()=>this.httpAPI.getLinkWorkspaceInfo(n).then(t=>null==t?void 0:t.widget):void 0),this.initialized=!0,this.config.debug&&console.log("[LiveChatta] SDK initialized",{linkCode:this.config.linkCode,socket:this.config.enableSocket,http:this.config.enableHttp}),this}async connect(){if(this.assertInitialized(),!this.socketTransport)throw new Error("LiveChatta: Socket transport is not enabled");await this.socketTransport.connect()}disconnect(){var t;null===(t=this.socketTransport)||void 0===t||t.disconnect()}sock(){if(this.assertInitialized(),!this.socketAPI)throw new Error("LiveChatta: Socket transport is not enabled. Set enableSocket: true in init().");return this.socketAPI}api(){if(this.assertInitialized(),!this.httpAPI)throw new Error("LiveChatta: HTTP transport is not enabled. Set enableHttp: true in init().");return this.httpAPI}async ui(t){if(this.assertInitialized(),!this.embedUI)throw new Error("LiveChatta: Embed UI not available");if(!this.config.chatUsername)throw new Error("LiveChatta: chatUsername is required for embed mode — each embed must identify the individual user. Pass chatUsername in init().");return this.embedUI.mount(t)}unmountUI(){var t;null===(t=this.embedUI)||void 0===t||t.unmount()}async updateTheme(t){var e;await(null===(e=this.embedUI)||void 0===e?void 0:e.updateTheme(t))}open(){var t;null===(t=this.embedUI)||void 0===t||t.open()}close(){var t;null===(t=this.embedUI)||void 0===t||t.close()}toggle(){var t;null===(t=this.embedUI)||void 0===t||t.toggle()}isOpen(){var t,e;return null!==(e=null===(t=this.embedUI)||void 0===t?void 0:t.isOpen())&&void 0!==e&&e}setUnread(t){var e;null===(e=this.embedUI)||void 0===e||e.setUnread(t)}on(t,e){var n;return null===(n=this.eventBus)||void 0===n||n.on(t,e),this}off(t,e){var n;return null===(n=this.eventBus)||void 0===n||n.off(t,e),this}isInitialized(){return this.initialized}isConnected(){var t,e;return null!==(e=null===(t=this.socketTransport)||void 0===t?void 0:t.isConnected())&&void 0!==e&&e}getConnectionState(){var t,e;return null!==(e=null===(t=this.socketTransport)||void 0===t?void 0:t.getState())&&void 0!==e?e:exports.ConnectionState.DISCONNECTED}getConfig(){return this.config}signAppRequest(t){return this.assertInitialized(),Dt({linkCode:this.config.linkCode,apiKey:this.config.apiKey,platform:t.platform,version:t.version})}buildUserToken(t){this.assertInitialized();const e=(null==t?void 0:t.chatUsername)||this.config.chatUsername;if(!e)throw new Error("LiveChatta.buildUserToken: chatUsername is required");return n(this.config.publicKey,{apiKey:this.config.apiKey,linkCode:this.config.linkCode,chatUsername:e,...(null==t?void 0:t.conversationId)?{conversationId:t.conversationId}:{}})}get bridge(){var t,e;return null!==(e=null===(t=this.embedUI)||void 0===t?void 0:t.bridge)&&void 0!==e?e:null}get permissions(){return this.permissionsApi}get runtime(){return i()}destroy(){var t;this.disconnect(),this.unmountUI(),null===(t=this.eventBus)||void 0===t||t.removeAllListeners(),this.config=null,this.tokenManager=null,this.eventBus=null,this.socketTransport=null,this.socketAPI=null,this.httpTransport=null,this.httpAPI=null,this.embedUI=null,this.initialized=!1}assertInitialized(){if(!this.initialized||!this.config)throw new Error("LiveChatta: SDK not initialized. Call LiveChatta.init() first.")}}const $t=new Gt,Ft=/^(?:https:\/\/[^/\s]+|http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?)\/hooks\/in\/lhk_[A-Za-z0-9_-]{43}\/?$/,Wt={name:{name:"name",label:"Your name",type:"text"},email:{name:"email",label:"Email",type:"email"},phone:{name:"phone",label:"Phone",type:"tel"},topic:{name:"topic",label:"What do you need?",type:"text"}},qt="chatta-bridge-grants";class Bt{async load(){if("undefined"==typeof localStorage)return{};try{const t=localStorage.getItem(qt);return t?JSON.parse(t):{}}catch(t){return{}}}async save(t){if("undefined"!=typeof localStorage)try{localStorage.setItem(qt,JSON.stringify(t))}catch(t){}}}class Vt{async load(){try{const{Preferences:t}=await(import("@capacitor/preferences")),{value:e}=await t.get({key:qt});return e?JSON.parse(e):{}}catch(t){return{}}}async save(t){try{const{Preferences:e}=await(import("@capacitor/preferences"));await e.set({key:qt,value:JSON.stringify(t)})}catch(t){}}}class Kt{constructor(){this.grants={}}async load(){return{...this.grants}}async save(t){this.grants={...t}}}class jt{constructor(t){this.cache=null,this.backend=t||new Bt}static withCapacitor(){return new jt(new Vt)}static inMemory(){return new jt(new Kt)}async getAll(){return this.cache||(this.cache=await this.backend.load()),{...this.cache}}async get(t){return!0===(await this.getAll())[t]}async set(t,e){this.cache||(this.cache=await this.backend.load()),this.cache[t]=e,await this.backend.save(this.cache)}async clear(){this.cache={},await this.backend.save({})}}const Yt=new Set(["livechatta.com","staging.livechatta.com","app.livechatta.com"]);function zt(t){if(!t||"string"!=typeof t)return{kind:"unknown",raw:t};if(0===t.indexOf("chatta://")){const e=t.slice(9).split("?")[0].split("/").filter(Boolean);return"open"===e[0]&&e[1]?{kind:"open",linkCode:e[1],raw:t}:"chat"===e[0]&&e[1]?{kind:"chat",linkCode:e[1],conversationId:e[2],raw:t}:"reset"===e[0]&&e[1]?{kind:"reset",resetToken:e[1],raw:t}:{kind:"unknown",raw:t}}try{const e=new URL(t);if(!Yt.has(e.hostname))return{kind:"unknown",raw:t};const n=e.pathname.split("/").filter(Boolean);if("in"===n[0]&&n[1]){const r=n[1],s=e.searchParams.get("conv");return s?{kind:"chat",linkCode:r,conversationId:s,raw:t}:{kind:"open",linkCode:r,raw:t}}return{kind:"unknown",raw:t}}catch(e){return{kind:"unknown",raw:t}}}const Qt=Object.freeze({membersCanSend:!0,membersCanAddPeople:!1,membersCanStartCalls:!0,membersCanShareMedia:!0,membersCanPin:!0,membersCanManageWebhooks:!1,slowModeSeconds:0}),Xt={"ios-app":"iPhone app","android-app":"Android app","desktop-app":"Desktop app","mobile-web":"Mobile web",web:"Web",api:"API",bot:"Bot",automation:"Automation"},Jt="RATE_LIMITED",Zt="EDIT_WINDOW_CLOSED",te="HOP_INVITE_CANCEL",ee=["answered","declined","ended"],ne="Plan not found.",re="This plan is not available.",se="This plan is activated by the LiveChatta team. Contact support to switch to it.",oe="PLAN_NOT_FOUND",ae="PLAN_NOT_AVAILABLE",ie="PLAN_TEAM_ACTIVATED",he={[oe]:"not-found",[ae]:"not-available",[ie]:"team-activated"},ce=["TOO_SHORT","TOO_LONG","INVALID","RESERVED","TAKEN"],le=ce.map(t=>`LINK_CODE_${t}`),ue="isn't allowed from",pe=/\S@\S|@\s*[\w-]+(?:\s*(?:\.|\[dot\]|\(dot\))\s*[a-z]{2,})|\[at\]|\(at\)|\bat\s+[\w-]+\s+dot\s+[a-z]{2,}/i,de=/\b\d{4}-\d{2}-\d{2}\b/g,Ee=t=>"string"==typeof t&&t.trim()&&!function(t){const e=t.normalize("NFKC");return!!pe.test(e)||(e.replace(de," ").match(/\+?\d[\d\s().-]{5,}\d/g)||[]).some(t=>{const e=t.replace(/\D/g,"").length;return e>=7&&e<=15})}(t)?t.trim():"",me="livechatta:visitor-id",ye=/^[A-Za-z0-9_-]{8,64}$/;let Te=null;function ge(){const t=new Uint8Array(16),e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(null==e?void 0:e.getRandomValues)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(256*Math.random());return"v_"+Array.from(t,t=>t.toString(16).padStart(2,"0")).join("")}const Ce=[["send","Only admins can send messages in this conversation."],["shareMedia","Only admins can share media in this conversation."],["addPeople","Only admins can add people to this conversation."],["startCall","Only admins can start calls in this conversation."],["pin","Only admins can pin messages in this conversation."]],Se=/^Slow mode is on\. You can send one message every (\d+)s\.$/,ve="This conversation is locked. Only admins can send messages.";exports.ACCOUNT_EXISTS="ACCOUNT_EXISTS",exports.ADMIN_NO_ACCESS="ADMIN_NO_ACCESS",exports.API_KEY_MAX_ORIGINS=20,exports.API_KEY_ORIGIN_ERROR_MARKER=ue,exports.APPROVAL_OFF="APPROVAL_OFF",exports.AutoRefresh=class{constructor(t){this.cfg=t,this.timer=null,this.inflight=null}start(){var t;if(this.timer)return;const e=null!==(t=this.cfg.intervalMs)&&void 0!==t?t:6e4;this.timer=setInterval(()=>this.tick(),e),this.tick()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}shouldRefresh(){var t;const{tokenIssuedAt:e,tokenExpiresAt:n,refreshToken:r}=this.cfg.getTokens();if(!r||!n)return!1;const s=Date.now();if(s>=n)return!0;const o=e||n-36e5,a=n-o;return!(a<=0)&&s>=o+a*(1-(null!==(t=this.cfg.threshold)&&void 0!==t?t:.2))}async refreshNow(){if(this.inflight)return this.inflight;const{refreshToken:t}=this.cfg.getTokens();return t?(this.inflight=(async()=>{try{const e=await this.cfg.refresh(t);(null==e?void 0:e.accessToken)&&this.cfg.onRefreshed(e)}catch(t){}this.inflight=null})(),this.inflight):void 0}async tick(){this.shouldRefresh()&&await this.refreshNow()}static pushToBridge(t,e){t.send("restoreSession",e)}},exports.Bridge=z,exports.CALENDAR_ACCOUNT_MISMATCH="CALENDAR_ACCOUNT_MISMATCH",exports.CALENDAR_PROVIDERS=["google","microsoft"],exports.CALENDAR_SIGNIN_EXPIRED="CALENDAR_SIGNIN_EXPIRED",exports.CALL_CANCEL_PUSH_TYPE=te,exports.CALL_CANCEL_REASONS=ee,exports.CALL_DECLINE_TTL_SECONDS=120,exports.CALL_WAITING_TUNES=["drift","pebble","lantern","tide","meadow","off"],exports.CATCH_UP_MIN_UNREAD=8,exports.CHAT_LINK_SETTINGS_KEYS=["maxMembers","allowAttachments","allowVoiceMessages","allowVideoMessages","allowMemberInvite","welcomeMessage","defaultLayout","hideRunsOn","allowMemberStart","allowHopCalls","allowScreenshots","retentionDays","allowLiveFlex","editHistoryAdminsOnly","allowSharedDms","isolated","allowRecordingDownload"],exports.CONVERSATION_CATEGORY_MAX=40,exports.CONVERSATION_LOCKED_MESSAGE=ve,exports.CONVERSATION_MODES=["standard","broadcast","announcement","qa","voice","support"],exports.CONVERSATION_NOTE_MAX_LENGTH=2e3,exports.CSAT_COMMENT_MAX=500,exports.CSAT_DEFAULT_QUESTION="How would you rate the help you got today?",exports.CSAT_QUESTION_MAX=140,exports.CSAT_SATISFIED_MIN=4,exports.CSAT_SCALE=5,exports.CUSTOM_PLAN_REQUEST_FEATURES=["SSO","WHITE_LABEL","API_ACCESS","WEBINARS","AUTOMATION","ADVANCED_ANALYTICS","HOP_RECORDING","LONG_RETENTION","DEDICATED_SUPPORT"],exports.CUSTOM_PLAN_REQUEST_STATUSES=["NEW","CONTACTED","QUOTED","ASSIGNED","CLOSED"],exports.ChattaEvent={OnLoginSuccess:"onLoginSuccess",OnLogout:"onLogout",OnUnreadChange:"onUnreadChange",OnThemeLoaded:"onThemeLoaded",OpenExternal:"openExternal",OpenWorkspaceDrawer:"openWorkspaceDrawer",EnableScreenshotProtection:"enableScreenshotProtection",HopStartCall:"hopStartCall",HopEndCall:"hopEndCall",HopRecordingStarted:"hopRecordingStarted",HopRecordingStopped:"hopRecordingStopped",Notify:"notify",GrantUpdate:"grantUpdate",SetClipboard:"setClipboard",Share:"share",Haptic:"haptic",WindowControl:"windowControl",OnLinkUnavailable:"onLinkUnavailable",HopMuteChanged:"hopMuteChanged",RestoreSession:"restoreSession",RestoreGrants:"restoreGrants",HopInvite:"hopInvite",OnLinkNotFound:"onLinkNotFound",UpdateReady:"updateReady",ConnectionLost:"connectionLost",ShareFiles:"shareFiles",Init:"init",NativeCall:"nativeCall"},exports.Config=e,exports.DEFAULT_CONVERSATION_PERMISSIONS=Qt,exports.DELETE_FOR_EVERYONE_WINDOW_MS=1728e5,exports.DeepLinks=class{constructor(){this.listeners=new Set}on(t){return this.listeners.add(t),()=>this.listeners.delete(t)}dispatch(t){const e=zt(t);return this.listeners.forEach(t=>{try{t(e)}catch(t){}}),e}},exports.EDIT_WINDOW_CLOSED=Zt,exports.EDIT_WINDOW_CLOSED_MESSAGE="Messages can only be edited within 24 hours of sending.",exports.EMAIL_REQUIRED="EMAIL_REQUIRED",exports.EMBED_IFRAME_ALLOW="microphone; camera; display-capture; clipboard-write",exports.EMBED_MESSAGE_TYPES=B,exports.EMBED_OPTION_KEYS=["floating","position","autoOpen","greeting","greetingDelay","title","subtitle","launcherLabel","zIndex","preload","layout","onOpenChange","preChat","onPreChatSubmit","businessHours","onAwayMessage","linkConfig"],exports.EmbedConfig=lt,exports.EmbedUI=Ut,exports.EventBus=s,exports.GIFT_PAYOUT_MIN_MINOR=1e3,exports.GOOGLE_SIGN_IN_ERRORS=["not_configured","state","exchange","invalid_token","expired","email_unverified","no_account","linked_elsewhere","denied"],exports.GUEST_CODE_COOLDOWN="GUEST_CODE_COOLDOWN",exports.GUEST_CODE_EXPIRED="GUEST_CODE_EXPIRED",exports.GUEST_CODE_INVALID="GUEST_CODE_INVALID",exports.GUEST_CODE_LOCKED="GUEST_CODE_LOCKED",exports.GUEST_CODE_RATE_LIMITED="GUEST_CODE_RATE_LIMITED",exports.GrantStore=jt,exports.HANDLE_TAKEN="HANDLE_TAKEN",exports.HOP_PUSH_DECLINE_PATH="/api/v1/hops/push-decline",exports.HOP_RATE_LIMITED="RATE_LIMITED",exports.HOP_RATE_LIMITS={reaction:20,vote:20,hand:6,pollVote:10},exports.HOP_RATE_WINDOW_SECONDS=10,exports.HttpAPI=W,exports.IFRAME_ALLOW=kt,exports.IFRAME_SANDBOX=Mt,exports.INBOX_TOPIC_MAX=8,exports.INCOMING_CALL_ACTIONS=["ANSWER","DECLINE"],exports.INCOMING_CALL_ANDROID_CHANNEL="livechatta_calls",exports.INCOMING_CALL_CATEGORY="INCOMING_CALL",exports.INCOMING_CALL_RING_SECONDS=30,exports.INCOMING_WEBHOOK_LIMITS={nameMax:60,botNameMax:40,textMax:7500,iconUrlMax:500,activePerConversation:10,blocksMax:20,attachmentsMax:10,postsPerMinutePerUrl:150,bodyMaxBytes:65536,listPageSize:20},exports.INCOMING_WEBHOOK_URL_RE=Ft,exports.INTERNAL_NOTE_MAX_LENGTH=3e3,exports.INVITE_ONLY="INVITE_ONLY",exports.ISOLATION_ERRORS=["WORKSPACE_ISOLATED"],exports.JOIN_REQUEST_STATUSES=["pending","approved","denied"],exports.LAUNCHER_FULLSCREEN_MAX=640,exports.LEGACY_DEFAULT_BRAND=et,exports.LINK_CODE_ERROR_CODES=le,exports.LINK_CODE_MAX=40,exports.LINK_CODE_MIN=3,exports.LINK_CODE_REASONS=ce,exports.LINK_FULL="LINK_FULL",exports.LINK_MEMBER_BLOCKED="LINK_MEMBER_BLOCKED",exports.LINK_MEMBER_FILTERS=["all","active","blocked","invited"],exports.LINK_MODES=["standard","support","creator","school","community","tech","public","private","webinar"],exports.LINK_NOTIFY_LEVELS=["all","mentions","off"],exports.LINK_WHO_CAN_JOIN=["guest","members","invite"],exports.LIVEFLEX_ERRORS=["LIVEFLEX_OFF","LIVEFLEX_CODE_REQUIRED","LIVEFLEX_CODE_WRONG","WORKSPACE_ISOLATED","FEES_CHANGED"],exports.LIVEFLEX_PIN_ERRORS=["LIVEFLEX_PIN_SETUP","LIVEFLEX_PIN_REQUIRED","LIVEFLEX_PIN_WRONG","LIVEFLEX_PIN_LOCKED"],exports.Launcher=wt,exports.LiveChatta=$t,exports.LiveChattaError=f,exports.LiveChattaSDK=Gt,exports.MESSAGE_LAYOUT_PREFS=["auto","bubbles","lines"],exports.MUTE_FOREVER_AT="9999-12-31T23:59:59.000Z",exports.MY_LINK_ROLES=["owner","admin","agent","member"],exports.ModeratorPermissions=["pin_message","delete_message","mute_member"],exports.PASSWORD_MAX_LENGTH=200,exports.PASSWORD_MIN_LENGTH=8,exports.PAYMENT_CHANNELS=["card","bank_transfer"],exports.PENDING_TRANSFER_KINDS=["plan_change","extra_seats"],exports.PERSONAL_NOTE_MAX_LENGTH=2e3,exports.PLAN_BILLING_CYCLES=["MONTHLY","QUARTERLY","SEMI_YEARLY","YEARLY"],exports.PLAN_NOT_AVAILABLE=ae,exports.PLAN_NOT_AVAILABLE_MESSAGE=re,exports.PLAN_NOT_FOUND=oe,exports.PLAN_NOT_FOUND_MESSAGE=ne,exports.PLAN_TEAM_ACTIVATED=ie,exports.PLAN_TEAM_ACTIVATED_MESSAGE=se,exports.PLAN_TYPES=["FLASH","PULSE","FLASH_PRO","ORBIT","CUSTOM"],exports.POST_REPLIES_OFF_MESSAGE="Replies are turned off for this post.",exports.PREFERENCE_LANGUAGES=["en","fr","es","ar","pt","de","yo","ha","ig","sw","zh","hi"],exports.PUSH_REPLY_MAX_LENGTH=4e3,exports.PUSH_REPLY_TTL_SECONDS=21600,exports.Permissions=h,exports.RATE_LIMITED=Jt,exports.RECORDING_DOWNLOAD_EXPIRED="RECORDING_DOWNLOAD_EXPIRED",exports.RECORDING_DOWNLOAD_OFF="RECORDING_DOWNLOAD_OFF",exports.SENT_FROM_VALUES=["ios-app","android-app","desktop-app","mobile-web","web","api","bot","automation"],exports.SERVER_PAGE_CAPS={conversations:100,sidebarConversations:40,messages:50,stories:20,billingHistory:100,signups:100,giftPurchases:100,cursorLists:20},exports.SHARED_CHANNEL_LIMITS={inviteDefaultHours:168,inviteMaxHours:720,maxPickedMembers:500,maxPartners:10,archiveMaxMessages:1e4,pickPageSize:20,listPageSize:30,auditPageSize:30},exports.SIDEBAR_PAGE_SIZE=40,exports.SIGNAL_BRAND=Z,exports.SIGNAL_INK=nt,exports.SIGNAL_SECONDARY=tt,exports.SIGN_IN_REQUIRED="SIGN_IN_REQUIRED",exports.SOUND_PRESETS=["default","gentle","chime","pop","none"],exports.STAFF_ONLY_CREATE_MESSAGE="Only the team can start groups and channels here.",exports.STORAGE_LIMIT="STORAGE_LIMIT",exports.STORY_BACKGROUNDS=["ink","brand","lagoon","sun"],exports.SUBSCRIPTION_FAILED_TRANSFER_UNPAID="transfer_unpaid",exports.SocketAPI=I,exports.TEXT_SIZE_PREFS=["s","m","l","xl"],exports.THEME_ALL_KEYS=X,exports.THEME_COLOR_KEYS=Q,exports.TRANSCRIBE_ERROR_CODES=["OUT_OF_AI_CREDITS","NOT_AVAILABLE","NO_MEDIA","TOO_LONG","PROVIDER_FAILED"],exports.UNREAD_TOTALS_MAX_EXCLUDE=1e3,exports.WEBHOOK_TEST_EVENT="webhook.test",exports.WORKSPACE_TEAM_DESCRIPTION_MAX=200,exports.WORKSPACE_TEAM_MAX_MEMBERS=50,exports.WORKSPACE_TEAM_NAME_MAX=40,exports.applyEmbedMessage=Y,exports.assignDefinedProps=J,exports.awayState=gt,exports.brandTextOn=ht,exports.buildAppSignature=Dt,exports.contrastRatio=at,exports.detectRuntime=o,exports.effectiveMode=function(t){return"system"!==t?t:"undefined"==typeof window||"function"!=typeof window.matchMedia?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"},exports.encryptEmbedToken=n,exports.frameOrigin=V,exports.getPromoVisitorId=function(){if(Te)return Te;try{const t="undefined"!=typeof window?window.localStorage:null,e=null==t?void 0:t.getItem(me);if(e&&ye.test(e))return Te=e;Te=ge(),null==t||t.setItem(me,Te)}catch(t){Te=Te||ge()}return Te},exports.getRuntime=i,exports.hasCustomBrand=st,exports.helloOnLoad=j,exports.hmacSha256Hex=Lt,exports.isApiKeyOriginError=function(t){var e;return("string"==typeof t?t:String(null!==(e=null==t?void 0:t.message)&&void 0!==e?e:"")).includes(ue)},exports.isEditWindowClosed=function(t){if(!t||"object"!=typeof t)return!1;const{code:e,details:n}=t,r=n&&"object"==typeof n?n.code:void 0;return e===Zt||r===Zt},exports.isLinkCodeError=function(t){return!!t&&le.includes(t)},exports.isRateLimited=function(t){if(!t||"object"!=typeof t)return!1;const{code:e,details:n,error:r}=t,s=[n,r].map(t=>t&&"object"==typeof t?t.code:void 0);return e===Jt||r===Jt||s.includes(Jt)},exports.isSharedArchive=function(t){const e=(null==t?void 0:t.sharedWith)||[];return e.length>0&&e.every(t=>!0===t.ended)},exports.isSharedChannelBadgeEvent=function(t){return Array.isArray(t.sharedWith)&&!("sharedChannelId"in t)},exports.isSharedConversation=function(t){var e;return!!(null===(e=null==t?void 0:t.sharedWith)||void 0===e?void 0:e.some(t=>!t.ended))},exports.isSocketError=function(t){return t instanceof f&&("socket"===t.transport||"SOCKET_ERROR"===t.code)},exports.isWithinHours=mt,exports.newPasswordProblem=function(t,e){return"string"!=typeof t||t.length<8?"too-short":t.length>200?"too-long":t===e?null:"mismatch"},exports.nextOpening=Tt,exports.normalizeHex=rt,exports.normalizeThemeMode=ct,exports.onBrandColor=it,exports.parseCallPush=function(t){if(!t||"object"!=typeof t)return null;const e=String(t.sessionId||t.callId||"");if(!e)return null;if(t.type===te){const n=ee.includes(t.reason)?t.reason:"ended";return{type:te,callId:String(t.callId||e),sessionId:e,reason:n}}return"HOP_INVITE"!==t.type?null:{...t,callId:String(t.callId||e),sessionId:e}},exports.parseClock=pt,exports.parseDeepLink=zt,exports.parsePermissionDenial=function(t){var e;const n=null===(e=function(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){const e=t.message;if("string"==typeof e)return e;if(Array.isArray(e)&&"string"==typeof e[0])return e[0]}return null}(t))||void 0===e?void 0:e.trim();if(!n)return null;const r=Se.exec(n);if(r)return{action:"slowMode",retryAfterSeconds:Number(r[1]),message:n};if(n===ve)return{action:"locked",message:n};const s=Ce.find(([,t])=>t===n);return s?{action:s[0],message:n}:null},exports.pickDefined=function(t,e){const n={};for(const r of e)void 0!==t[r]&&null!==t[r]&&(n[r]=t[r]);return n},exports.planAccessError=function(t){if(!t||"object"!=typeof t)return null;const{statusCode:e,message:n,code:r}=t;return"string"==typeof r&&he[r]?he[r]:404===e&&n===ne?"not-found":400!==e?null:n===re||n===ne?"not-available":n===se?"team-activated":null},exports.postIncomingWebhook=async function(t,e,n={}){var r;if(!Ft.test(String(t||"").trim()))throw new f("That is not an https incoming webhook URL (https://<host>/hooks/in/lhk_...).",400,"INVALID_URL");const s="string"==typeof e?{text:e}:e,o=n.fetch||fetch,a=new AbortController,i=setTimeout(()=>a.abort(),null!==(r=n.timeoutMs)&&void 0!==r?r:15e3);let h;try{h=await o(t.trim(),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain"},body:JSON.stringify(s),signal:a.signal,redirect:"error"})}catch(t){const e="AbortError"===(null==t?void 0:t.name);throw new f(e?"Request timeout":"Could not reach the webhook URL",e?408:0,e?"TIMEOUT":"NETWORK")}finally{clearTimeout(i)}if(h.ok)return{ok:!0};let c={};try{c=await h.json()}catch(t){}const l="string"==typeof c.code?c.code.toUpperCase():404===h.status?"NOT_FOUND":void 0,u=Number(h.headers.get("Retry-After")),p=Number(c.retryAfter)||(Number.isFinite(u)&&u>0?u:void 0),d="string"==typeof c.message&&c.message?c.message:`Webhook answered ${h.status}`;throw new f(d,h.status,l,p?{retryAfter:p}:void 0)},exports.relativeLuminance=ot,exports.resolveBrand=function(t){return st(t)?rt(t):Z},exports.resolvePreChat=vt,exports.sendHello=K,exports.sentFromLabel=function(t){return"string"==typeof t&&Object.prototype.hasOwnProperty.call(Xt,t)?Xt[t]:""},exports.serverErrorCode=_,exports.sharedParticipantLabel=function(t){if(!t)return"Member";const e=[Ee(t.firstName),Ee(t.lastName)].filter(Boolean).join(" ");return Ee(t.displayName)||Ee(t.handle)||e||Ee(t.username)||"Member"},exports.toLinkWidgetConfig=function(t,e){if(!t)return{};const n=t.preChat,r=(e||[]).filter(t=>"string"==typeof t&&t.trim()),s=((null==n?void 0:n.fields)||[]).filter(t=>t&&Wt[t.key]).map(t=>{const e={...Wt[t.key],required:!!t.required};return"topic"===t.key&&r.length?{...e,type:"select",options:r}:e}),o=t.businessHours;return{preChat:n?{enabled:!!n.enabled,intro:n.intro||void 0,fields:s}:null,businessHours:o?{enabled:!!o.enabled,timezone:o.timezone,awayMessage:o.awayMessage||void 0,windows:o.week||[]}:null}},exports.validatePreChat=Ot,exports.zonedClock=dt;
1
+ "use strict";var t=require("socket.io-client");class e{constructor(t){if(!t.linkCode)throw new Error("LiveChatta: linkCode is required");if(!t.apiKey)throw new Error("LiveChatta: apiKey is required");if(!t.publicKey)throw new Error("LiveChatta: publicKey is required");this.linkCode=t.linkCode,this.apiKey=t.apiKey,this.baseUrl=(t.baseUrl||"https://api.livechatta.com").replace(/\/+$/,""),this.chatUsername=t.chatUsername,this.publicKey=t.publicKey,this.enableSocket=!1!==t.enableSocket,this.enableHttp=!1!==t.enableHttp,this.debug=!0===t.debug,this.ownerToken=t.ownerToken||void 0,this.memberToken=t.memberToken||void 0}get wsUrl(){try{const t=new URL(this.baseUrl);return t.protocol="https:"===t.protocol?"wss:":"ws:",t.toString().replace(/\/+$/,"")}catch(t){return this.baseUrl.replace(/^http/,"ws")}}get apiUrl(){return`${this.baseUrl}/api/v1`}get rootUrl(){return this.baseUrl}get externalUrl(){return`${this.baseUrl}/api/v1/external`}get embedUrl(){return`${this.baseUrl}/in/${this.linkCode}/embed/chat`}get appEmbedUrl(){return`${this.baseUrl}/in/${this.linkCode}/app/embed/chat`}}async function n(t,e){return"undefined"!=typeof window&&"undefined"!=typeof crypto&&void 0!==crypto.subtle?async function(t,e){const n=function(t){const e=t.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s/g,""),n=atob(e),r=new Uint8Array(n.length);for(let t=0;t<n.length;t++)r[t]=n.charCodeAt(t);return r.buffer}(t),r=await crypto.subtle.importKey("spki",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),s=(new TextEncoder).encode(JSON.stringify(e));return function(t){const e=new Uint8Array(t);let n="";for(let t=0;t<e.length;t++)n+=String.fromCharCode(e[t]);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.encrypt({name:"RSA-OAEP"},r,s))}(t,e):async function(t,e){const{publicEncrypt:n,constants:r}=await(import("crypto")),s=(new TextEncoder).encode(JSON.stringify(e));return n({key:t,padding:r.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},s).toString("base64url")}(t,e)}class r{constructor(t,e,n,r){this.apiKey=t,this.linkCode=e,this.chatUsername=n,this.publicKey=r,this.cachedToken=null}get hasPublicKey(){return!!this.publicKey}async getToken(){if(this.cachedToken)return this.cachedToken;if(this.publicKey){const t={apiKey:this.apiKey,linkCode:this.linkCode,chatUsername:this.chatUsername};this.cachedToken=await n(this.publicKey,t)}else this.cachedToken=this.apiKey;return this.cachedToken}invalidate(){this.cachedToken=null}async refresh(){return this.invalidate(),this.getToken()}}class s{constructor(){this.listeners=new Map,this.onceListeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),this}once(t,e){return this.onceListeners.has(t)||this.onceListeners.set(t,new Set),this.onceListeners.get(t).add(e),this}off(t,e){var n,r;return e?(null===(n=this.listeners.get(t))||void 0===n||n.delete(e),null===(r=this.onceListeners.get(t))||void 0===r||r.delete(e)):(this.listeners.delete(t),this.onceListeners.delete(t)),this}emit(t,...e){var n;null===(n=this.listeners.get(t))||void 0===n||n.forEach(t=>{try{t(...e)}catch(t){}});const r=this.onceListeners.get(t);return r&&(r.forEach(t=>{try{t(...e)}catch(t){}}),r.clear()),this}removeAllListeners(){return this.listeners.clear(),this.onceListeners.clear(),this}}function o(){if("undefined"!=typeof window){const t=window;if(t.Capacitor&&"function"==typeof t.Capacitor.getPlatform){const e=String(t.Capacitor.getPlatform()).toLowerCase();if("ios"===e)return{kind:"capacitor-ios",platform:"mobile-ios",isAppShell:!0};if("android"===e)return{kind:"capacitor-android",platform:"mobile-android",isAppShell:!0}}if(t.__TAURI_INTERNALS__||t.__TAURI__){const t="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent:"";return/Mac OS X|Macintosh/i.test(t)?{kind:"tauri-macos",platform:"desktop-macos",isAppShell:!0}:/Windows/i.test(t)?{kind:"tauri-windows",platform:"desktop-windows",isAppShell:!0}:{kind:"tauri-linux",platform:"desktop-linux",isAppShell:!0}}return t.ReactNativeWebView?{kind:"react-native",platform:"mobile-ios",isAppShell:!0}:{kind:"web",platform:"web",isAppShell:!1}}return{kind:"node",platform:"node",isAppShell:!1}}let a=null;function i(){return a||(a=o()),a}class h{async requestMedia(t){var e;const n=!t||!1!==t.audio,r=!(!t||!t.video),s=i();let o="prompt",a="prompt";if("capacitor-ios"===s.kind||"capacitor-android"===s.kind)try{const{Capacitor:t,registerPlugin:e}=await(import("@capacitor/core"));if(t&&t.isPluginAvailable&&t.isPluginAvailable("HopBridge")){const t=e("HopBridge"),s=await t.requestPermissions({wantVideo:r,wantAudio:n});o=(null==s?void 0:s.mic)||"prompt",a=(null==s?void 0:s.cam)||"prompt"}}catch(t){}if("undefined"!=typeof navigator&&(null===(e=navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia)){const t={};n&&(t.audio=!0),r&&(t.video=!0),t.audio||t.video||(t.audio=!0);try{(await navigator.mediaDevices.getUserMedia(t)).getTracks().forEach(t=>t.stop()),n&&(o="granted"),r&&(a="granted")}catch(t){n&&"granted"!==o&&(o="denied"),r&&"granted"!==a&&(a="denied")}}else o="unsupported",a="unsupported";return{granted:!(n&&"granted"!==o||r&&"granted"!==a),mic:o,cam:a}}async requestNotifications(){const t=i();if("capacitor-ios"===t.kind||"capacitor-android"===t.kind)try{const{registerPlugin:t}=await(import("@capacitor/core")),e=t("PushNotifications"),n=await e.requestPermissions();return"granted"===(null==n?void 0:n.receive)?"granted":(null==n?void 0:n.receive)||"prompt"}catch(t){return"unsupported"}if("undefined"==typeof Notification)return"unsupported";if("granted"===Notification.permission)return"granted";if("denied"===Notification.permission)return"denied";try{return await Notification.requestPermission()}catch(t){return"denied"}}}var c,l,u,p,d,E,m,y,T,g,C,S,v,O,A,b;function _(t){const e=t&&"object"==typeof t?t.code:void 0;return"string"==typeof e&&/^[A-Z][A-Z0-9_]{2,47}$/.test(e)?e:void 0}exports.ChatEvent=void 0,(c=exports.ChatEvent||(exports.ChatEvent={})).ALL_CONVERSATIONS="all-conversations",c.NEW_CONVERSATION="new-conversation",c.ENTER_CONVERSATION="enter-conversation",c.JOIN_CONVERSATION="join-conversation",c.EDIT_CONVERSATION="edit-conversation",c.MAKE_ADMIN_CONVERSATION="make-admin-conversation",c.TOGGLE_CONVERSATION="toggle-conversation",c.STATUS_CHANGE_CONVERSATION="status-change-conversation",c.MEMBER_STATUS_CHANGE_CONVERSATION="member-status-change-conversation",c.MEMBERSHIP_REVOKED="membership-revoked",c.SHARED_CHANNEL_INVITE="shared-channel-invite",c.SHARED_CHANNEL_UPDATED="shared-channel-updated",c.MESSAGE_STATUS_CHANGE="message-status-change",c.MESSAGE_REACTION="message-reaction",c.VALIDATE_PASSWORD="validate-password",c.ALL_MESSAGES="all-messages",c.NEW_MESSAGE="new-message",c.NEW_TYPING="new-typing",c.SAVE_DRAFT="save-draft",c.DRAFT_UPDATED="draft-updated",c.SET_STATUS="set-status",c.STATUS_UPDATED="status-updated",c.UPDATE_LIVE_LOCATION="update-live-location",c.LIVE_LOCATION_UPDATED="live-location-updated",c.STOP_LIVE_LOCATION="stop-live-location",c.LIVE_LOCATION_ENDED="live-location-ended",c.FORGOT_PASSWORD="forgot-password",c.CHANGE_PASSWORD="change-password",c.RESET_PASSWORD="reset-password",c.REFRESH_TOKEN="refresh-token",c.REVOKE_TOKEN="revoke-token",c.ONLINE="online",c.OFFLINE="offline",c.CHAT_ERROR="chat-error",c.AUTH_ERROR="auth-error",c.UNREAD_COUNT_UPDATE="unread-count-update",c.NOTIFICATION="notification",c.EDIT_MESSAGE="edit-message",c.FORWARD_MESSAGE="forward-message",c.FORWARD_POST="forward-post",c.MESSAGE_FAILED="message-failed",c.MESSAGE_READ="message-read",c.SEARCH_MESSAGES="search-messages",c.SCHEDULED_MESSAGE="scheduled-message",c.SEARCH_CHAT_USERS="search-chat-users",c.THREAD_MESSAGES="thread-messages",c.TOGGLE_BOOKMARK="toggle-bookmark",c.GET_BOOKMARKS="get-bookmarks",c.GET_ALL_BOOKMARKS="get-all-bookmarks",c.VOTE_POLL="vote-poll",c.CREATE_POST="create-post",c.GET_POSTS="get-posts",c.GET_STORIES="get-stories",c.VIEW_POST="view-post",c.REACT_TO_POST="react-to-post",c.REPLY_TO_POST="reply-to-post",c.UPDATE_POST="update-post",c.DELETE_POST="delete-post",c.GET_POST_MESSAGES="get-post-messages",c.ALL_THREADS="all-threads",c.NEW_STORY="new-story",c.TRANSLATE_MESSAGE="translate-message",c.SET_LANGUAGE="set-language",c.PIN_CONVERSATION="pin-conversation",c.CONVERSATION_MEMBERS="conversation-members",c.LINK_HANDLES="link-handles",c.LINK_HOPS="link-hops",c.LINK_USER_JOINED="link-user-joined",c.LINK_USER_UPDATED="link-user-updated",c.ONLINE_USERS="online-users",c.HEARTBEAT="heartbeat",c.HOP_START="hop-start",c.HOP_END="hop-end",c.HOP_JOIN="hop-join",c.HOP_LEAVE="hop-leave",c.HOP_CONNECT_TRANSPORT="hop-connect-transport",c.HOP_PRODUCE="hop-produce",c.HOP_CONSUME="hop-consume",c.HOP_RESUME_CONSUMER="hop-resume-consumer",c.HOP_MEDIA_CHANGE="hop-media-change",c.HOP_SCREENSHARE_START="hop-screenshare-start",c.HOP_SCREENSHARE_STOP="hop-screenshare-stop",c.HOP_RECORDING_START="hop-recording-start",c.HOP_RECORDING_STOP="hop-recording-stop",c.HOP_INVITE_DECLINE="hop-invite-decline",c.HOP_ADMIT="hop-admit",c.HOP_DENY="hop-deny",c.HOP_ICE_RESTART="hop-ice-restart",c.HOP_REJOIN_ROOM="hop-rejoin-room",c.HOP_AD_HOC_START="hop-ad-hoc-start",c.HOP_INVITE_REQUEST="hop-invite-request",c.HOP_GET_SESSION="hop-get-session",c.HOP_MEETING_CREATE="hop-meeting-create",c.HOP_MEETING_CANCEL="hop-meeting-cancel",c.HOP_MEETING_LIST="hop-meeting-list",c.HOP_LIST_PRODUCERS="hop-list-producers",c.HOP_LIST_PARTICIPANTS="hop-list-participants",c.HOP_MUTE_PARTICIPANT="hop-mute-participant",c.HOP_DROP_PARTICIPANT="hop-drop-participant",c.HOP_PIN_FOR_ALL="hop-pin-for-all",c.HOP_LIST_ACTIVE="hop-list-active",c.HOP_TRANSPORT_PARAMS="hop-transport-params",c.HOP_STARTED="hop-started",c.HOP_ENDED="hop-ended",c.HOP_PARTICIPANT_JOINED="hop-participant-joined",c.HOP_PARTICIPANT_LEFT="hop-participant-left",c.HOP_NEW_PRODUCER="hop-new-producer",c.HOP_PRODUCER_CLOSED="hop-producer-closed",c.HOP_INVITE="hop-invite",c.HOP_MEETING_UPDATED="hop-meeting-updated",c.HOP_LOBBY_WAITING="hop-lobby-waiting",c.HOP_DENIED="hop-denied",c.HOP_REDIRECT="hop-redirect",c.HOP_RECORDING_STARTED="hop-recording-started",c.HOP_RECORDING_STOPPED="hop-recording-stopped",c.HOP_RECORDING_READY="hop-recording-ready",c.HOP_RECORDING_ALREADY_ACTIVE="hop-recording-already-active",c.HOP_RECORDING_FORBIDDEN="hop-recording-forbidden",c.HOP_INVITE_DECLINED="hop-invite-declined",c.HOP_SCREENSHARE_STARTED="hop-screenshare-started",c.HOP_MEDIA_CHANGED="hop-media-changed",c.HOP_MEETING_REMINDER="hop-meeting-reminder",c.HOP_PARTICIPANT_MUTED="hop-participant-muted",c.HOP_PINNED_FOR_ALL="hop-pinned-for-all",c.HOP_PARTICIPANT_DROPPED="hop-participant-dropped",c.HOP_YOU_WERE_DROPPED="hop-you-were-dropped",c.HOP_INVITE_ANSWERED="hop-invite-answered",c.HOP_UNMUTE_REQUESTED="hop-unmute-requested",c.HOP_REACTION="hop-reaction",c.HOP_KEEP_WAITING="hop-keep-waiting",c.HOP_VOTE="hop-vote",c.HOP_VOTE_UPDATED="hop-vote-updated",c.HOP_RAISE_HAND="hop-raise-hand",c.HOP_NEW_VOTE_ROUND="hop-new-vote-round",c.HOP_VOTE_COMPLETE="hop-vote-complete",c.HOP_HOST_CHANGED="hop-host-changed",c.HOP_MAKE_HOST="hop-make-host",c.HOP_ADMITTED="hop-admitted",c.HOP_CO_HOST_ASSIGN="hop-co-host-assign",c.HOP_CO_HOST_ASSIGNED="hop-co-host-assigned",c.HOP_POLL_LAUNCH="hop-poll-launch",c.HOP_POLL_LAUNCHED="hop-poll-launched",c.HOP_POLL_VOTE="hop-poll-vote",c.HOP_POLL_VOTE_UPDATED="hop-poll-vote-updated",c.HOP_WHITEBOARD_SYNC="hop-whiteboard-sync",c.HOP_WHITEBOARD_DELTA="hop-whiteboard-delta",c.HOP_POLL_CLOSE="hop-poll-close",c.HOP_COLLAB_STATE="hop-collab-state",c.HOP_CAPTIONS_TOGGLE="hop-captions-toggle",c.HOP_CAPTION="hop-caption",c.HOP_RECORDING_LIST="hop-recording-list",c.HOP_CAPTIONS_STATE="hop-captions-state",c.HOP_CAPTION_TEXT="hop-caption-text",c.AI_CREDITS_UPDATED="ai-credits-updated",c.AI_CREDITS_EXHAUSTED="ai-credits-exhausted",c.WHITEBOARD_OPEN="whiteboard-open",c.WHITEBOARD_STROKE="whiteboard-stroke",c.WHITEBOARD_CLEAR="whiteboard-clear",c.WHITEBOARD_CLOSE="whiteboard-close",c.WHITEBOARD_SNAPSHOT="whiteboard-snapshot",c.CREATE_AUTOMATION="create-automation",c.UPDATE_AUTOMATION="update-automation",c.DELETE_AUTOMATION="delete-automation",c.GET_AUTOMATIONS="get-automations",c.START_WEBINAR="start-webinar",c.RAISE_HAND="raise-hand",c.LOWER_HAND="lower-hand",c.PROMOTE_ATTENDEE_AUDIO="promote-attendee-audio",c.WEBINAR_QA_SUBMIT="webinar-qa-submit",c.WEBINAR_QA_ANSWER="webinar-qa-answer",c.WEBINAR_STARTED="webinar-started",c.WEBINAR_HAND_RAISED="webinar-hand-raised",c.WEBINAR_HAND_LOWERED="webinar-hand-lowered",c.WEBINAR_ATTENDEE_PROMOTED="webinar-attendee-promoted",c.WEBINAR_QA_UPDATED="webinar-qa-updated",c.GET_CONVERSATION_STATS="get-conversation-stats",c.UPDATE_CHAT_USER_SETTINGS="update-chat-user-settings",c.MESSAGE_DELIVERED="message-delivered",c.MESSAGE_INFO="message-info",c.MUTE_CONVERSATION="mute-conversation",c.CONVERSATION_MUTED="conversation-muted",c.UPDATE_QUIET_HOURS="update-quiet-hours",c.QUIET_HOURS_UPDATED="quiet-hours-updated",c.SET_MESSAGE_REMINDER="set-message-reminder",c.CANCEL_MESSAGE_REMINDER="cancel-message-reminder",c.MESSAGE_REMINDERS_CHANGED="message-reminders-changed",c.MESSAGE_REMINDER_DUE="message-reminder-due",c.UPDATE_CONVERSATION_PERMISSIONS="update-conversation-permissions",c.CONVERSATION_PERMISSIONS_UPDATED="conversation-permissions-updated",c.HUDDLE_START="huddle-start",c.HUDDLE_STATUS="huddle-status",c.HUDDLE_END="huddle-end",c.HUDDLE_UPDATED="huddle-updated",c.TRANSCRIBE_MESSAGE="transcribe-message",c.MESSAGE_TRANSCRIPT_UPDATED="message-transcript-updated",c.INBOX_UPDATED="inbox-updated",c.INTERNAL_NOTE="internal-note",c.INTERNAL_NOTE_DELETED="internal-note-deleted",c.CONVERSATION_NOTES_UPDATED="conversation-notes-updated",c.CSAT_UPDATED="csat-updated",c.CONVERSATION_READ="conversation-read",c.CONVERSATION_UNREAD="conversation-unread",c.UNREAD_TOTALS="unread-totals",c.DELETE_MESSAGE="delete-message",c.MESSAGE_DELETED="message-deleted",c.SEARCH_ALL="search-all",c.SUBMIT_PRE_CHAT="submit-pre-chat",c.PRE_CHAT_SUBMITTED="pre-chat-submitted",c.LINK_SETTINGS_UPDATED="link-settings-updated",c.CALL_LOGGED="call-logged",c.STICKERS_MINE="stickers-mine",c.STICKERS_SEARCH="stickers-search",c.STICKER_UPLOAD="sticker-upload",c.STICKER_ADD="sticker-add",c.STICKER_REMOVE="sticker-remove",c.CHATTA_MONEY_CARD="chatta-money-card",c.CHATTA_MONEY_CONFIRM="chatta-money-confirm",c.MONEY_CARD_GET="money-card-get",c.MONEY_CARD_ACTION="money-card-action",c.MONEY_CARD_UPDATE="money-card-update",c.WEBINAR_QA_ANSWER_LIVE="webinar-qa-answer-live",c.WEBINAR_QA_VOTE="webinar-qa-vote",c.WEBINAR_VIEWER_COUNT="webinar-viewer-count",exports.SDKEvent=void 0,(l=exports.SDKEvent||(exports.SDKEvent={})).CONNECTING="sdk:connecting",l.CONNECTED="sdk:connected",l.DISCONNECTED="sdk:disconnected",l.RECONNECTING="sdk:reconnecting",l.RECONNECTED="sdk:reconnected",l.ERROR="sdk:error",l.QUEUE_FLUSH="sdk:queue-flush",exports.ChatConversationType=void 0,(u=exports.ChatConversationType||(exports.ChatConversationType={})).SINGLE="SINGLE",u.GROUP="GROUP",u.CHANNEL="CHANNEL",u.SELF="SELF",exports.ChatMessageStatus=void 0,(p=exports.ChatMessageStatus||(exports.ChatMessageStatus={})).SENT="SENT",p.DELIVERED="DELIVERED",p.READ="READ",p.DELETED="DELETED",p.SCHEDULED="SCHEDULED",exports.ChatMessageType=void 0,(d=exports.ChatMessageType||(exports.ChatMessageType={})).SYSTEM="SYSTEM",d.USER="USER",d.ADMIN="ADMIN",exports.ChatMessageKind=void 0,(E=exports.ChatMessageKind||(exports.ChatMessageKind={})).PARENT="PARENT",E.THREAD="THREAD",E.POLL="POLL",E.STICKER="STICKER",E.GIF="GIF",E.HOP_SYSTEM="HOP_SYSTEM",E.HOP_RECORDING="HOP_RECORDING",E.HOP_VOTE="HOP_VOTE",E.HOP_MEETING="HOP_MEETING",E.CSAT="CSAT",exports.UserStatus=void 0,(m=exports.UserStatus||(exports.UserStatus={})).ACTIVE="ACTIVE",m.DISABLE="DISABLE",m.DEACTIVATE="DEACTIVATE",m.BLOCKED="BLOCKED",m.LEAVE="LEAVE",m.FULLY_CLOSED="FULLY_CLOSED",exports.UserConversationRole=void 0,(y=exports.UserConversationRole||(exports.UserConversationRole={})).SUPER_ADMIN="SUPER_ADMIN",y.ADMIN="ADMIN",y.MODERATOR="MODERATOR",y.MEMBER="MEMBER",exports.MessageChangeStatus=void 0,(T=exports.MessageChangeStatus||(exports.MessageChangeStatus={})).DELETE="DELETE",T.PIN="PIN",T.UNPIN="UNPIN",T.STARRED="STARRED",T.UNSTARRED="UNSTARRED",exports.ConnectionState=void 0,(g=exports.ConnectionState||(exports.ConnectionState={})).DISCONNECTED="DISCONNECTED",g.CONNECTING="CONNECTING",g.CONNECTED="CONNECTED",g.RECONNECTING="RECONNECTING",exports.AttachmentType=void 0,(C=exports.AttachmentType||(exports.AttachmentType={})).PHOTO="PHOTO",C.VIDEO="VIDEO",C.AUDIO="AUDIO",C.WORD="WORD",C.PDF="PDF",C.EXCEL="EXCEL",C.ZIP="ZIP",C.OTHER="OTHER",exports.PostType=void 0,(S=exports.PostType||(exports.PostType={})).STORY="STORY",S.POST="POST",S.PROMOTION="PROMOTION",exports.HopMode=void 0,(v=exports.HopMode||(exports.HopMode={})).NOW="NOW",v.CIRCLE="CIRCLE",v.MEETING="MEETING",exports.HopStatus=void 0,(O=exports.HopStatus||(exports.HopStatus={})).IDLE="IDLE",O.SCHEDULED="SCHEDULED",O.LIVE="LIVE",O.ENDED="ENDED",O.CANCELLED="CANCELLED",exports.WebhookStatus=void 0,(A=exports.WebhookStatus||(exports.WebhookStatus={})).ACTIVE="ACTIVE",A.DISABLED="DISABLED",exports.WebhookEvent=void 0,(b=exports.WebhookEvent||(exports.WebhookEvent={})).MESSAGE_SENT="message.sent",b.CONVERSATION_CREATED="conversation.created",b.USER_JOINED="user.joined",b.USER_LEFT="user.left",b.CONVERSATION_LOCKED="conversation.locked",b.CONVERSATION_UNLOCKED="conversation.unlocked",b.CSAT_SUBMITTED="csat.submitted";class f extends Error{constructor(t,e,n,r,s){super(t),this.statusCode=e,this.code=n,this.details=r,this.transport=s,this.name="LiveChattaError"}}class R{constructor(t,e,n){this.config=t,this.tokenManager=e,this.eventBus=n,this.maxRetries=2,this.timeout=3e4,this.ownerToken=t.ownerToken||null,this.memberToken=t.memberToken||null}setMemberToken(t){this.memberToken=t||null}hasMemberToken(){return!!this.memberToken}bearerFor(t){return"owner"===t?this.ownerToken:"member"===t?this.memberToken:"user"===t?this.memberToken||this.ownerToken:null}setOwnerToken(t){this.ownerToken=t||null}hasOwnerToken(){return!!this.ownerToken}buildHeaders(t="apiKey"){return"owner"===t||"member"===t||"user"===t?{"Content-Type":"application/json",Authorization:`Bearer ${this.bearerFor(t)}`}:"none"===t?{"Content-Type":"application/json"}:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"x-embed":"true"}}baseFor(t="external"){return"api"===t?this.config.apiUrl:"root"===t?this.config.rootUrl:this.config.externalUrl}buildQueryString(t){if(!t)return"";const e=Object.entries(t).filter(([,t])=>null!=t&&""!==t);return e.length?"?"+new URLSearchParams(e.map(([t,e])=>[t,String(e)])).toString():""}async request(t,e,n){return this._doRequest(t,e,n,!1)}async _doRequest(t,e,n,r){var s,o;const a=(null==n?void 0:n.auth)||"apiKey";if("owner"===a&&!this.ownerToken)throw new f("Owner token required — pass ownerToken to init() or call api().setOwnerToken()",401,"OWNER_TOKEN_REQUIRED");if(("member"===a||"user"===a)&&!this.bearerFor(a))throw new f("member"===a?"Member token required — pass memberToken to init() or call api().setMemberToken()":"Member or owner token required — call api().setMemberToken() or api().setOwnerToken()",401,"member"===a?"MEMBER_TOKEN_REQUIRED":"USER_TOKEN_REQUIRED");const i=`${this.baseFor(null==n?void 0:n.base)}${e}${this.buildQueryString(null==n?void 0:n.query)}`,h={...(null==n?void 0:n.headers)||{},...this.buildHeaders(a)},c=(null==n?void 0:n.noRetry)?0:this.maxRetries;let l=null;for(let u=0;u<=c;u++){const p=new AbortController,d=setTimeout(()=>p.abort(),this.timeout);try{const c={method:t,headers:h,signal:p.signal};(null==n?void 0:n.body)&&(c.body=JSON.stringify(n.body)),this.log(`${t} ${e}`);const u=await fetch(i,c);if(u.ok)return u.json();if(401===u.status&&"apiKey"===a&&!r&&this.tokenManager){clearTimeout(d);try{return await this.tokenManager.refresh(),this._doRequest(t,e,n,!0)}catch(t){throw null===(s=this.eventBus)||void 0===s||s.emit(exports.ChatEvent.AUTH_ERROR,{message:"Authentication failed after token refresh"}),new f("Unauthorized — token refresh failed",401,"AUTH_ERROR")}}if(u.status<500){const t=await u.json().catch(()=>({message:u.statusText}));401===u.status&&(null===(o=this.eventBus)||void 0===o||o.emit(exports.ChatEvent.AUTH_ERROR,{message:"Unauthorized"}));const e=401!==u.status&&403!==u.status||"apiKey"===a||"none"===a?void 0:"owner"===a?"OWNER_AUTH":"USER_AUTH";throw new f(t.message||`Request failed: ${u.status}`,u.status,_(t)||e,t)}const E=await u.json().catch(()=>({message:u.statusText}));l=new f(E.message||`Server error: ${u.status}`,u.status)}catch(t){if(t instanceof f&&t.statusCode<500)throw t;l="AbortError"===t.name?new f("Request timeout",408,"TIMEOUT"):t}finally{clearTimeout(d)}u<c&&await new Promise(t=>setTimeout(t,1e3*Math.pow(2,u)))}throw l||new Error("LiveChatta: Request failed")}get(t,e){return this.request("GET",t,{query:e})}post(t,e,n){return this.request("POST",t,{body:e,query:n})}put(t,e,n){return this.request("PUT",t,{body:e,query:n})}patch(t,e,n){return this.request("PATCH",t,{body:e,query:n})}delete(t,e){return this.request("DELETE",t,{query:e})}owner(t,e,n){return this.request(t,e,{...n,base:"api",auth:"owner"})}user(t,e,n){return this.request(t,e,{...n,base:"api",auth:(null==n?void 0:n.auth)||"user"})}urlFor(t,e,n){return`${this.baseFor(t)}${e}${this.buildQueryString(n)}`}log(t){this.config.debug&&console.log(`[LiveChatta HTTP] ${t}`)}}class x{constructor(t,e,n){this.config=t,this.tokenManager=e,this.eventBus=n,this.socket=null,this.state=exports.ConnectionState.DISCONNECTED,this.queue=[],this.reconnectAttempt=0,this.selfUserId=null}async connect(){var e;if(null===(e=this.socket)||void 0===e?void 0:e.connected)return;this.setState(exports.ConnectionState.CONNECTING);const n=await this.tokenManager.getToken(),r={linkCode:this.config.linkCode};return this.tokenManager.hasPublicKey?r.token=n:r.apiKey=n,this.config.chatUsername&&(r.chatUsername=this.config.chatUsername),this.config.linkCode&&(r.chatLinkCode=this.config.linkCode),this.socket=t.io(this.config.baseUrl,{query:r,auth:{token:`Bearer ${n}`},extraHeaders:{"x-api-key":this.config.apiKey,"x-embed":"true"},transports:["websocket"],reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,reconnectionAttempts:1/0}),this.setupLifecycleListeners(),new Promise((t,e)=>{let n=!1;const r=()=>{var t,e,n;null===(t=this.socket)||void 0===t||t.off("connect",o),null===(e=this.socket)||void 0===e||e.off(exports.ChatEvent.CHAT_ERROR,a),null===(n=this.socket)||void 0===n||n.off("connect_error",i)},s=setTimeout(()=>{n||(n=!0,r(),e(new Error("LiveChatta: Socket connection timeout")))},15e3),o=()=>{n||(n=!0,clearTimeout(s),r(),this.setState(exports.ConnectionState.CONNECTED),this.reconnectAttempt=0,this.log("Socket connected"),this.flushQueue(),t())},a=t=>{n||(n=!0,clearTimeout(s),r(),e(new Error((null==t?void 0:t.message)||"LiveChatta: Connection failed")))},i=t=>{n||(n=!0,clearTimeout(s),r(),e(t))};this.socket.on("connect",o),this.socket.on(exports.ChatEvent.CHAT_ERROR,a),this.socket.on("connect_error",i)})}getSelfUserId(){return this.selfUserId}disconnect(){this.selfUserId=null,this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,this.setState(exports.ConnectionState.DISCONNECTED),this.rejectQueue("LiveChatta: Socket disconnected before flush"),this.log("Socket disconnected"))}rejectQueue(t){if(!this.queue.length)return void(this.queue=[]);const e=this.queue;this.queue=[];for(const n of e)n.reject(new Error(t))}isConnected(){var t;return this.state===exports.ConnectionState.CONNECTED&&!!(null===(t=this.socket)||void 0===t?void 0:t.connected)}getState(){return this.state}emit(t,e){var n;return(null===(n=this.socket)||void 0===n?void 0:n.connected)?this.doEmit(t,e):this.queue.length>=x.MAX_QUEUE_SIZE?Promise.reject(new Error("LiveChatta: Emit queue full — socket disconnected, too many pending emits")):(this.log(`Queuing emit: ${t}`),new Promise((n,r)=>{this.queue.push({event:t,data:e,resolve:n,reject:r})}))}on(t,e){var n;null===(n=this.socket)||void 0===n||n.on(t,e)}off(t,e){var n,r;e?null===(n=this.socket)||void 0===n||n.off(t,e):null===(r=this.socket)||void 0===r||r.removeAllListeners(t)}getSocket(){return this.socket}doEmit(t,e){return new Promise((n,r)=>{var s;if(!(null===(s=this.socket)||void 0===s?void 0:s.connected))return r(new Error("LiveChatta: Socket not connected"));this.socket.emit(t,e,t=>{const e=function(t){const e=t&&"object"==typeof t?t.error:void 0;if(!e)return null;const n="object"==typeof e?e:null;let r=n?n.message:e;Array.isArray(r)&&(r=r.join(", "));const s=n&&"number"==typeof n.statusCode?n.statusCode:400;return new f("string"==typeof r&&r?r:"Request failed",s,_(n)||"SOCKET_ERROR",e,"socket")}(t);e?r(e):n(t)})})}setupLifecycleListeners(){this.socket&&(this.socket.on(exports.ChatEvent.ONLINE,t=>{var e;const n=(null==t?void 0:t.isSelfConnection)?null===(e=t.user)||void 0===e?void 0:e._id:void 0;"string"==typeof n&&n&&(this.selfUserId=n)}),this.socket.on("disconnect",t=>{this.log(`Socket disconnected: ${t}`),this.setState(exports.ConnectionState.DISCONNECTED),this.eventBus.emit(exports.SDKEvent.DISCONNECTED,{reason:t})}),this.socket.io.on("reconnect_attempt",t=>{this.reconnectAttempt=t,this.setState(exports.ConnectionState.RECONNECTING),this.log(`Reconnecting... attempt ${t}`),this.eventBus.emit(exports.SDKEvent.RECONNECTING,{attempt:t})}),this.socket.io.on("reconnect",t=>{this.setState(exports.ConnectionState.CONNECTED),this.reconnectAttempt=0,this.log(`Reconnected after ${t} attempts`),this.eventBus.emit(exports.SDKEvent.RECONNECTED,{attempt:t}),this.flushQueue()}),this.socket.io.on("reconnect_error",t=>{this.log(`Reconnect error: ${t.message}`),this.eventBus.emit(exports.SDKEvent.ERROR,{error:t,type:"reconnect"})}))}flushQueue(){if(!this.queue.length)return;this.log(`Flushing ${this.queue.length} queued emits`);const t=[...this.queue];this.queue=[],this.eventBus.emit(exports.SDKEvent.QUEUE_FLUSH,{count:t.length});for(const e of t)this.doEmit(e.event,e.data).then(e.resolve).catch(e.reject)}setState(t){this.state=t}log(t){this.config.debug&&console.log(`[LiveChatta] ${t}`)}}async function P(t,e,n,r){const s=await t.emit(e,n);return null==r||r(s),s}x.MAX_QUEUE_SIZE=100;class I{constructor(t,e){this.transport=t,this.eventBus=e}async getConversations(t,e){const n=await this.transport.emit(exports.ChatEvent.ALL_CONVERSATIONS,t||{});return null==e||e(n),n}async startConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.NEW_CONVERSATION,t);return null==e||e(n),n}async enterConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.ENTER_CONVERSATION,{conversationId:t});return null==e||e(n),n}async joinConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.JOIN_CONVERSATION,t);return null==e||e(n),n}async editConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.EDIT_CONVERSATION,t);return null==e||e(n),n}async pinConversation(t,e){const n=await this.transport.emit(exports.ChatEvent.PIN_CONVERSATION,t);return null==e||e(n),n}async makeAdmin(t,e){const n=await this.transport.emit(exports.ChatEvent.MAKE_ADMIN_CONVERSATION,t);return null==e||e(n),n}async toggleLock(t,e){const n=await this.transport.emit(exports.ChatEvent.TOGGLE_CONVERSATION,t);return null==e||e(n),n}async changeConversationStatus(t,e){const n=await this.transport.emit(exports.ChatEvent.STATUS_CHANGE_CONVERSATION,t);return null==e||e(n),n}async changeMemberStatus(t,e){const n=await this.transport.emit(exports.ChatEvent.MEMBER_STATUS_CHANGE_CONVERSATION,t);return null==e||e(n),n}async getMessages(t,e){const n=await this.transport.emit(exports.ChatEvent.ALL_MESSAGES,t);return null==e||e(n),n}async sendMessage(t,e){const n=await this.transport.emit(exports.ChatEvent.NEW_MESSAGE,t);return null==e||e(n),n}async typing(t,e){const n=await this.transport.emit(exports.ChatEvent.NEW_TYPING,t);return null==e||e(n),n}async saveDraft(t,e){const n=await this.transport.emit(exports.ChatEvent.SAVE_DRAFT,t);return null==e||e(n),n}async setChatStatus(t,e){const n=await this.transport.emit(exports.ChatEvent.SET_STATUS,t);return null==e||e(n),n}async updateLiveLocation(t,e){const n=await this.transport.emit(exports.ChatEvent.UPDATE_LIVE_LOCATION,t);return null==e||e(n),n}async stopLiveLocation(t,e){const n=await this.transport.emit(exports.ChatEvent.STOP_LIVE_LOCATION,t);return null==e||e(n),n}async changeMessageStatus(t,e){const n=await this.transport.emit(exports.ChatEvent.MESSAGE_STATUS_CHANGE,t);return null==e||e(n),n}async reactToMessage(t,e){const n=await this.transport.emit(exports.ChatEvent.MESSAGE_REACTION,t);return null==e||e(n),n}async editMessage(t,e){var n,r,s;const o=null!==(n=t.senderId)&&void 0!==n?n:null===(s=(r=this.transport).getSelfUserId)||void 0===s?void 0:s.call(r),a=await this.transport.emit(exports.ChatEvent.EDIT_MESSAGE,o?{...t,senderId:o}:t);return null==e||e(a),a}async forwardMessage(t,e){const n=t,{conversationId:r,targetConversationId:s,...o}=n,a={...o,fromConversationId:n.fromConversationId||r,toConversationId:n.toConversationId||s},i=await this.transport.emit(exports.ChatEvent.FORWARD_MESSAGE,a);return null==e||e(i),i}async forwardPost(t,e){const n=await this.transport.emit(exports.ChatEvent.FORWARD_POST,t);return null==e||e(n),n}async markMessagesRead(t,e){const n=await this.transport.emit(exports.ChatEvent.MESSAGE_READ,t);return null==e||e(n),n}async searchMessages(t,e){const n=await this.transport.emit(exports.ChatEvent.SEARCH_MESSAGES,t);return null==e||e(n),n}async searchChatUsers(t,e){const n=await this.transport.emit(exports.ChatEvent.SEARCH_CHAT_USERS,t);return null==e||e(n),n}async getThreadMessages(t,e){const n=await this.transport.emit(exports.ChatEvent.THREAD_MESSAGES,t);return null==e||e(n),n}async toggleBookmark(t,e){const n=await this.transport.emit(exports.ChatEvent.TOGGLE_BOOKMARK,t);return null==e||e(n),n}async getBookmarks(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_BOOKMARKS,t);return null==e||e(n),n}async getAllBookmarks(t={},e){const n=await this.transport.emit(exports.ChatEvent.GET_ALL_BOOKMARKS,t);return null==e||e(n),n}async votePoll(t,e){const n=await this.transport.emit(exports.ChatEvent.VOTE_POLL,t);return null==e||e(n),n}async validatePassword(t,e){const n=await this.transport.emit(exports.ChatEvent.VALIDATE_PASSWORD,t);return null==e||e(n),n}async forgotPassword(t,e){const n=await this.transport.emit(exports.ChatEvent.FORGOT_PASSWORD,t);return null==e||e(n),n}async resetPassword(t,e){const n=await this.transport.emit(exports.ChatEvent.RESET_PASSWORD,t);return null==e||e(n),n}async changePassword(t,e){const n=await this.transport.emit(exports.ChatEvent.CHANGE_PASSWORD,t);return null==e||e(n),n}async refreshToken(t,e){const n=await this.transport.emit(exports.ChatEvent.REFRESH_TOKEN,t);return null==e||e(n),n}async revokeToken(t,e){const n=await this.transport.emit(exports.ChatEvent.REVOKE_TOKEN,t);return null==e||e(n),n}async createPost(t,e){const n=!t.cta&&t.ctaLabel&&t.ctaUrl?{...t,cta:{label:t.ctaLabel,url:t.ctaUrl}}:t,r=await this.transport.emit(exports.ChatEvent.CREATE_POST,n);return null==e||e(r),r}async getPosts(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_POSTS,t||{});return null==e||e(n),n}async getStories(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_STORIES,t||{});return null==e||e(n),n}async viewPost(t,e){const n=await this.transport.emit(exports.ChatEvent.VIEW_POST,t);return null==e||e(n),n}async reactToPost(t,e){const n=await this.transport.emit(exports.ChatEvent.REACT_TO_POST,t);return null==e||e(n),n}async replyToPost(t,e){const n=await this.transport.emit(exports.ChatEvent.REPLY_TO_POST,t);return null==e||e(n),n}async updatePost(t,e){const n=await this.transport.emit(exports.ChatEvent.UPDATE_POST,t);return null==e||e(n),n}async deletePost(t,e){const n=await this.transport.emit(exports.ChatEvent.DELETE_POST,t);return null==e||e(n),n}async getPostMessages(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_POST_MESSAGES,t);return null==e||e(n),n}async getAllThreads(t,e){const n=await this.transport.emit(exports.ChatEvent.ALL_THREADS,t||{});return null==e||e(n),n}async getConversationMembers(t,e){const n=await this.transport.emit(exports.ChatEvent.CONVERSATION_MEMBERS,t);return null==e||e(n),n}async getLinkHandles(t){const e=await this.transport.emit(exports.ChatEvent.LINK_HANDLES,{});return null==t||t(e),e}async startHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_START,t);return null==e||e(n),n}async startHopAdHoc(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_AD_HOC_START,t);return null==e||e(n),n}async joinHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_JOIN,t);return null==e||e(n),n}async connectHopTransport(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_CONNECT_TRANSPORT,t);return null==e||e(n),n}async hopProduce(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_PRODUCE,t);return null==e||e(n),n}async hopConsume(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_CONSUME,t);return null==e||e(n),n}async resumeHopConsumer(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_RESUME_CONSUMER,t);return null==e||e(n),n}async leaveHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_LEAVE,t);return null==e||e(n),n}async endHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_END,t);return null==e||e(n),n}async inviteToHop(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_INVITE_REQUEST,t);return null==e||e(n),n}async getHopSession(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_GET_SESSION,t);return null==e||e(n),n}async startHopRecording(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_RECORDING_START,t);return null==e||e(n),n}async stopHopRecording(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_RECORDING_STOP,t);return null==e||e(n),n}async scheduleHopMeeting(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_MEETING_CREATE,t);return null==e||e(n),n}async cancelHopMeeting(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_MEETING_CANCEL,t);return null==e||e(n),n}async listHopMeetings(t={},e){const n=await this.transport.emit(exports.ChatEvent.HOP_MEETING_LIST,t);return null==e||e(n),n}async listHopProducers(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_LIST_PRODUCERS,t);return null==e||e(n),n}async listHopParticipants(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_LIST_PARTICIPANTS,t);return null==e||e(n),n}async muteHopParticipant(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_MUTE_PARTICIPANT,t);return null==e||e(n),n}async dropHopParticipant(t,e){const n=await this.transport.emit(exports.ChatEvent.HOP_DROP_PARTICIPANT,t);return null==e||e(n),n}async hopPinForAll(t,e){return P(this.transport,exports.ChatEvent.HOP_PIN_FOR_ALL,t,e)}async listActiveHops(t){const e=await this.transport.emit(exports.ChatEvent.HOP_LIST_ACTIVE,{});return null==t||t(e),e}async sendHopReaction(t){return this.transport.emit(exports.ChatEvent.HOP_REACTION,t)}async keepHopWaiting(t){return this.transport.emit(exports.ChatEvent.HOP_KEEP_WAITING,t)}async sendHopVote(t){return this.transport.emit(exports.ChatEvent.HOP_VOTE,t)}async raiseHand(t){return this.transport.emit(exports.ChatEvent.HOP_RAISE_HAND,t)}async startNewVoteRound(t){return this.transport.emit(exports.ChatEvent.HOP_NEW_VOTE_ROUND,t)}async makeHost(t){return this.transport.emit(exports.ChatEvent.HOP_MAKE_HOST,t)}async stopHopScreenShare(t){return this.transport.emit(exports.ChatEvent.HOP_SCREENSHARE_STOP,t)}async startHopScreenShare(t){return this.transport.emit(exports.ChatEvent.HOP_SCREENSHARE_START,t)}async hopMediaChange(t){return this.transport.emit(exports.ChatEvent.HOP_MEDIA_CHANGE,t)}async hopInviteDecline(t){return this.transport.emit(exports.ChatEvent.HOP_INVITE_DECLINE,t)}async rejoinHop(t){return this.transport.emit(exports.ChatEvent.HOP_REJOIN_ROOM,t)}async restartHopIce(t){return this.transport.emit(exports.ChatEvent.HOP_ICE_RESTART,t)}async hopAdmit(t){return this.transport.emit(exports.ChatEvent.HOP_ADMIT,t)}async translateMessage(t,e){const n=await this.transport.emit(exports.ChatEvent.TRANSLATE_MESSAGE,t);return null==e||e(n),n}async setLanguage(t,e){const n=await this.transport.emit(exports.ChatEvent.SET_LANGUAGE,t);return null==e||e(n),n}async getOnlineUsers(t,e){const n=await this.transport.emit(exports.ChatEvent.ONLINE_USERS,t);return null==e||e(n),n}async heartbeat(t){await this.transport.emit(exports.ChatEvent.HEARTBEAT,"boolean"==typeof(null==t?void 0:t.visible)?{visible:t.visible}:{})}async messageDelivered(t,e){return P(this.transport,exports.ChatEvent.MESSAGE_DELIVERED,t,e)}async messageInfo(t,e){return P(this.transport,exports.ChatEvent.MESSAGE_INFO,t,e)}async muteConversation(t,e){return P(this.transport,exports.ChatEvent.MUTE_CONVERSATION,t,e)}async updateQuietHours(t,e){return P(this.transport,exports.ChatEvent.UPDATE_QUIET_HOURS,t,e)}async setMessageReminder(t,e){return P(this.transport,exports.ChatEvent.SET_MESSAGE_REMINDER,t,e)}async cancelMessageReminder(t,e){return P(this.transport,exports.ChatEvent.CANCEL_MESSAGE_REMINDER,{reminderId:t},e)}async updateConversationPermissions(t,e){return P(this.transport,exports.ChatEvent.UPDATE_CONVERSATION_PERMISSIONS,t,e)}async huddleStart(t,e){return P(this.transport,exports.ChatEvent.HUDDLE_START,t,e)}async huddleStatus(t,e){return P(this.transport,exports.ChatEvent.HUDDLE_STATUS,{conversationId:t},e)}async huddleEnd(t,e){return P(this.transport,exports.ChatEvent.HUDDLE_END,{conversationId:t},e)}async transcribeMessage(t,e){return P(this.transport,exports.ChatEvent.TRANSCRIBE_MESSAGE,t,e)}async conversationRead(t,e){return P(this.transport,exports.ChatEvent.CONVERSATION_READ,{conversationId:t},e)}async conversationUnread(t,e,n){return P(this.transport,exports.ChatEvent.CONVERSATION_UNREAD,{conversationId:t,messageId:e},n)}async getUnreadTotals(t={},e){return P(this.transport,exports.ChatEvent.UNREAD_TOTALS,t,e)}async deleteMessage(t,e){return P(this.transport,exports.ChatEvent.DELETE_MESSAGE,t,e)}async searchAll(t,e){return P(this.transport,exports.ChatEvent.SEARCH_ALL,t,e)}async submitPreChat(t,e){return P(this.transport,exports.ChatEvent.SUBMIT_PRE_CHAT,t,e)}async hopPollClose(t,e){return P(this.transport,exports.ChatEvent.HOP_POLL_CLOSE,t,e)}async hopCollabState(t,e){return P(this.transport,exports.ChatEvent.HOP_COLLAB_STATE,{sessionId:t},e)}async hopCaptionsToggle(t,e){return P(this.transport,exports.ChatEvent.HOP_CAPTIONS_TOGGLE,t,e)}async hopCaption(t,e){return P(this.transport,exports.ChatEvent.HOP_CAPTION,t,e)}async hopRecordingList(t,e){return P(this.transport,exports.ChatEvent.HOP_RECORDING_LIST,t,e)}async stickersMine(t){return P(this.transport,exports.ChatEvent.STICKERS_MINE,{},t)}async stickersSearch(t={},e){return P(this.transport,exports.ChatEvent.STICKERS_SEARCH,t,e)}async stickerUpload(t,e){return P(this.transport,exports.ChatEvent.STICKER_UPLOAD,t,e)}async stickerAdd(t,e){return P(this.transport,exports.ChatEvent.STICKER_ADD,t,e)}async stickerRemove(t,e){return P(this.transport,exports.ChatEvent.STICKER_REMOVE,t,e)}async chattaMoneyConfirm(t,e){return P(this.transport,exports.ChatEvent.CHATTA_MONEY_CONFIRM,t,e)}async getMoneyCard(t,e){return P(this.transport,exports.ChatEvent.MONEY_CARD_GET,t,e)}async moneyCardAction(t,e){return P(this.transport,exports.ChatEvent.MONEY_CARD_ACTION,t,e)}async webinarQaAnswerLive(t,e){return P(this.transport,exports.ChatEvent.WEBINAR_QA_ANSWER_LIVE,t,e)}async webinarQaVote(t,e){return P(this.transport,exports.ChatEvent.WEBINAR_QA_VOTE,t,e)}onMessage(t){return this.transport.on(exports.ChatEvent.NEW_MESSAGE,t),this}onConversation(t){return this.transport.on(exports.ChatEvent.NEW_CONVERSATION,t),this}onEditConversation(t){return this.transport.on(exports.ChatEvent.EDIT_CONVERSATION,t),this}onMakeAdmin(t){return this.transport.on(exports.ChatEvent.MAKE_ADMIN_CONVERSATION,t),this}onMemberStatusChange(t){return this.transport.on(exports.ChatEvent.MEMBER_STATUS_CHANGE_CONVERSATION,t),this}onToggleConversation(t){return this.transport.on(exports.ChatEvent.TOGGLE_CONVERSATION,t),this}onStatusChangeConversation(t){return this.transport.on(exports.ChatEvent.STATUS_CHANGE_CONVERSATION,t),this}onPinConversation(t){return this.transport.on(exports.ChatEvent.PIN_CONVERSATION,t),this}onLinkUserJoined(t){return this.transport.on(exports.ChatEvent.LINK_USER_JOINED,t),this}onLinkUserUpdated(t){return this.transport.on(exports.ChatEvent.LINK_USER_UPDATED,t),this}onMessageStatusChange(t){return this.transport.on(exports.ChatEvent.MESSAGE_STATUS_CHANGE,t),this}onMessageReaction(t){return this.transport.on(exports.ChatEvent.MESSAGE_REACTION,t),this}onTyping(t){return this.transport.on(exports.ChatEvent.NEW_TYPING,t),this}onDraftUpdated(t){return this.transport.on(exports.ChatEvent.DRAFT_UPDATED,t),this}onStatusUpdated(t){return this.transport.on(exports.ChatEvent.STATUS_UPDATED,t),this}onLiveLocationUpdated(t){return this.transport.on(exports.ChatEvent.LIVE_LOCATION_UPDATED,t),this}onLiveLocationEnded(t){return this.transport.on(exports.ChatEvent.LIVE_LOCATION_ENDED,t),this}onOnline(t){return this.transport.on(exports.ChatEvent.ONLINE,t),this}onOffline(t){return this.transport.on(exports.ChatEvent.OFFLINE,t),this}onJoinConversation(t){return this.transport.on(exports.ChatEvent.JOIN_CONVERSATION,t),this}onUnreadCountUpdate(t){return this.transport.on(exports.ChatEvent.UNREAD_COUNT_UPDATE,t),this}onMembershipRevoked(t){return this.transport.on(exports.ChatEvent.MEMBERSHIP_REVOKED,t),this}onSharedChannelInvite(t){return this.transport.on(exports.ChatEvent.SHARED_CHANNEL_INVITE,t),this}onSharedChannelUpdated(t){return this.transport.on(exports.ChatEvent.SHARED_CHANNEL_UPDATED,t),this}onNotification(t){return this.transport.on(exports.ChatEvent.NOTIFICATION,t),this}onEditMessage(t){return this.transport.on(exports.ChatEvent.EDIT_MESSAGE,t),this}onForwardMessage(t){return this.transport.on(exports.ChatEvent.FORWARD_MESSAGE,t),this}onMessageRead(t){return this.transport.on(exports.ChatEvent.MESSAGE_READ,t),this}onScheduledMessage(t){return this.transport.on(exports.ChatEvent.SCHEDULED_MESSAGE,t),this}onMessageFailed(t){return this.transport.on(exports.ChatEvent.MESSAGE_FAILED,t),this}onVotePoll(t){return this.transport.on(exports.ChatEvent.VOTE_POLL,t),this}onError(t){return this.transport.on(exports.ChatEvent.CHAT_ERROR,t),this}onAuthError(t){return this.transport.on(exports.ChatEvent.AUTH_ERROR,t),this}onCreatePost(t){return this.transport.on(exports.ChatEvent.CREATE_POST,t),this}onNewStory(t){return this.transport.on(exports.ChatEvent.NEW_STORY,t),this}onUpdatePost(t){return this.transport.on(exports.ChatEvent.UPDATE_POST,t),this}onDeletePost(t){return this.transport.on(exports.ChatEvent.DELETE_POST,t),this}onReactToPost(t){return this.transport.on(exports.ChatEvent.REACT_TO_POST,t),this}onReplyToPost(t){return this.transport.on(exports.ChatEvent.REPLY_TO_POST,t),this}onTranslateMessage(t){return this.transport.on(exports.ChatEvent.TRANSLATE_MESSAGE,t),this}onAiCreditsUpdated(t){return this.transport.on(exports.ChatEvent.AI_CREDITS_UPDATED,t),this}onAiCreditsExhausted(t){return this.transport.on(exports.ChatEvent.AI_CREDITS_EXHAUSTED,t),this}onHopAdmitted(t){return this.transport.on(exports.ChatEvent.HOP_ADMITTED,t),this}onHopReaction(t){return this.transport.on(exports.ChatEvent.HOP_REACTION,t),this}onHopVoteUpdated(t){return this.transport.on(exports.ChatEvent.HOP_VOTE_UPDATED,t),this}onHopVoteComplete(t){return this.transport.on(exports.ChatEvent.HOP_VOTE_COMPLETE,t),this}onHopNewVoteRound(t){return this.transport.on(exports.ChatEvent.HOP_NEW_VOTE_ROUND,t),this}onHopRaiseHand(t){return this.transport.on(exports.ChatEvent.HOP_RAISE_HAND,t),this}onHopHostChanged(t){return this.transport.on(exports.ChatEvent.HOP_HOST_CHANGED,t),this}onHopStarted(t){return this.transport.on(exports.ChatEvent.HOP_STARTED,t),this}onHopEnded(t){return this.transport.on(exports.ChatEvent.HOP_ENDED,t),this}onHopParticipantJoined(t){return this.transport.on(exports.ChatEvent.HOP_PARTICIPANT_JOINED,t),this}onHopParticipantLeft(t){return this.transport.on(exports.ChatEvent.HOP_PARTICIPANT_LEFT,t),this}onHopInvite(t){return this.transport.on(exports.ChatEvent.HOP_INVITE,t),this}onHopLobbyWaiting(t){return this.transport.on(exports.ChatEvent.HOP_LOBBY_WAITING,t),this}onHopDenied(t){return this.transport.on(exports.ChatEvent.HOP_DENIED,t),this}onHopRedirect(t){return this.transport.on(exports.ChatEvent.HOP_REDIRECT,t),this}onHopRecordingStarted(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_STARTED,t),this}onHopRecordingStopped(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_STOPPED,t),this}onHopRecordingReady(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_READY,t),this}onHopRecordingAlreadyActive(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_ALREADY_ACTIVE,t),this}onHopParticipantMuted(t){return this.transport.on(exports.ChatEvent.HOP_PARTICIPANT_MUTED,t),this}onHopPinnedForAll(t){return this.transport.on(exports.ChatEvent.HOP_PINNED_FOR_ALL,t),this}onHopParticipantDropped(t){return this.transport.on(exports.ChatEvent.HOP_PARTICIPANT_DROPPED,t),this}onHopYouWereDropped(t){return this.transport.on(exports.ChatEvent.HOP_YOU_WERE_DROPPED,t),this}onHopInviteAnswered(t){return this.transport.on(exports.ChatEvent.HOP_INVITE_ANSWERED,t),this}onHopUnmuteRequested(t){return this.transport.on(exports.ChatEvent.HOP_UNMUTE_REQUESTED,t),this}onHopMeetingReminder(t){return this.transport.on(exports.ChatEvent.HOP_MEETING_REMINDER,t),this}onHopVote(t){return this.transport.on(exports.ChatEvent.HOP_VOTE,t),this}onHopNewProducer(t){return this.transport.on(exports.ChatEvent.HOP_NEW_PRODUCER,t),this}onHopProducerClosed(t){return this.transport.on(exports.ChatEvent.HOP_PRODUCER_CLOSED,t),this}hopDeny(t,e,n){return this.transport.emit(exports.ChatEvent.HOP_DENY,{sessionId:t,userId:e,...n?{block:!0}:{}}),this}onHopInviteDeclined(t){return this.transport.on(exports.ChatEvent.HOP_INVITE_DECLINED,t),this}onHopScreenshareStarted(t){return this.transport.on(exports.ChatEvent.HOP_SCREENSHARE_STARTED,t),this}onHopMediaChanged(t){return this.transport.on(exports.ChatEvent.HOP_MEDIA_CHANGED,t),this}onHopTransportParams(t){return this.transport.on(exports.ChatEvent.HOP_TRANSPORT_PARAMS,t),this}onHopRecordingForbidden(t){return this.transport.on(exports.ChatEvent.HOP_RECORDING_FORBIDDEN,t),this}hopScreenshareStart(t){return this.transport.emit(exports.ChatEvent.HOP_SCREENSHARE_START,t),this}hopCoHostAssign(t){return this.transport.emit(exports.ChatEvent.HOP_CO_HOST_ASSIGN,t),this}onHopCoHostAssigned(t){return this.transport.on(exports.ChatEvent.HOP_CO_HOST_ASSIGNED,t),this}hopPollLaunch(t){return this.transport.emit(exports.ChatEvent.HOP_POLL_LAUNCH,t),this}onHopPollLaunched(t){return this.transport.on(exports.ChatEvent.HOP_POLL_LAUNCHED,t),this}hopPollVote(t){return this.transport.emit(exports.ChatEvent.HOP_POLL_VOTE,t),this}onHopPollVoteUpdated(t){return this.transport.on(exports.ChatEvent.HOP_POLL_VOTE_UPDATED,t),this}hopWhiteboardSync(t){return this.transport.emit(exports.ChatEvent.HOP_WHITEBOARD_SYNC,t),this}onHopWhiteboardDelta(t){return this.transport.on(exports.ChatEvent.HOP_WHITEBOARD_DELTA,t),this}openWhiteboard(t,e){return this.transport.emit(exports.ChatEvent.WHITEBOARD_OPEN,{conversationId:t,...e?{chatLinkId:e}:{}}),this}sendWhiteboardStroke(t){return this.transport.emit(exports.ChatEvent.WHITEBOARD_STROKE,t),this}clearWhiteboard(t,e){return this.transport.emit(exports.ChatEvent.WHITEBOARD_CLEAR,{conversationId:t,...e?{whiteboardId:e}:{}}),this}closeWhiteboard(t,e){return this.transport.emit(exports.ChatEvent.WHITEBOARD_CLOSE,{conversationId:t,...e?{whiteboardId:e}:{}}),this}snapshotWhiteboard(t){return this.transport.emit(exports.ChatEvent.WHITEBOARD_SNAPSHOT,t),this}onWhiteboardStroke(t){return this.transport.on(exports.ChatEvent.WHITEBOARD_STROKE,t),this}onWhiteboardCleared(t){return this.transport.on(exports.ChatEvent.WHITEBOARD_CLEAR,t),this}onWhiteboardClosed(t){return this.transport.on(exports.ChatEvent.WHITEBOARD_CLOSE,t),this}onWhiteboardSnapshot(t){return this.transport.on(exports.ChatEvent.WHITEBOARD_SNAPSHOT,t),this}async createAutomation(t,e){const n=await this.transport.emit(exports.ChatEvent.CREATE_AUTOMATION,t);return null==e||e(n),n}async updateAutomation(t,e){const n=await this.transport.emit(exports.ChatEvent.UPDATE_AUTOMATION,t);return null==e||e(n),n}async deleteAutomation(t,e){const n=await this.transport.emit(exports.ChatEvent.DELETE_AUTOMATION,t);return null==e||e(n),n}async getAutomations(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_AUTOMATIONS,t);return null==e||e(n),n}async startWebinar(t,e){const n=await this.transport.emit(exports.ChatEvent.START_WEBINAR,t);return null==e||e(n),n}raiseHandWebinar(t){return this.transport.emit(exports.ChatEvent.RAISE_HAND,t),this}lowerHand(t){return this.transport.emit(exports.ChatEvent.LOWER_HAND,t),this}async promoteAttendeeAudio(t,e){const n=await this.transport.emit(exports.ChatEvent.PROMOTE_ATTENDEE_AUDIO,t);return null==e||e(n),n}async submitWebinarQa(t,e){const n=await this.transport.emit(exports.ChatEvent.WEBINAR_QA_SUBMIT,t);return null==e||e(n),n}async answerWebinarQa(t,e){const n=await this.transport.emit(exports.ChatEvent.WEBINAR_QA_ANSWER,t);return null==e||e(n),n}onCallLogged(t){return this.transport.on(exports.ChatEvent.CALL_LOGGED,t),this}onChattaMoneyCard(t){return this.transport.on(exports.ChatEvent.CHATTA_MONEY_CARD,t),this}onMoneyCardUpdate(t){return this.transport.on(exports.ChatEvent.MONEY_CARD_UPDATE,t),this}onLinkSettingsUpdated(t){return this.transport.on(exports.ChatEvent.LINK_SETTINGS_UPDATED,t),this}onWebinarViewerCount(t){return this.transport.on(exports.ChatEvent.WEBINAR_VIEWER_COUNT,t),this}onWebinarStarted(t){return this.transport.on(exports.ChatEvent.WEBINAR_STARTED,t),this}onWebinarRaisedHand(t){return this.transport.on(exports.ChatEvent.WEBINAR_HAND_RAISED,t),this}onWebinarHandLowered(t){return this.transport.on(exports.ChatEvent.WEBINAR_HAND_LOWERED,t),this}onWebinarAttendeePromoted(t){return this.transport.on(exports.ChatEvent.WEBINAR_ATTENDEE_PROMOTED,t),this}onWebinarQaSubmitted(t){return this.transport.on(exports.ChatEvent.WEBINAR_QA_UPDATED,t),this}async getConversationStats(t,e){const n=await this.transport.emit(exports.ChatEvent.GET_CONVERSATION_STATS,{conversationId:t});return null==e||e(n),n}onConversationStats(t){return this.transport.on(exports.ChatEvent.GET_CONVERSATION_STATS,t),this}async updateChatUserSettings(t,e){const n=await this.transport.emit(exports.ChatEvent.UPDATE_CHAT_USER_SETTINGS,t);return null==e||e(n),n}onConnect(t){return this.eventBus.on(exports.SDKEvent.CONNECTED,t),this}onDisconnect(t){return this.eventBus.on(exports.SDKEvent.DISCONNECTED,t),this}onReconnect(t){return this.eventBus.on(exports.SDKEvent.RECONNECTED,t),this}onReconnecting(t){return this.eventBus.on(exports.SDKEvent.RECONNECTING,t),this}off(t,e){return this.transport.off(t,e),this}onMessageDelivered(t){return this.transport.on(exports.ChatEvent.MESSAGE_DELIVERED,t),this}onConversationMuted(t){return this.transport.on(exports.ChatEvent.CONVERSATION_MUTED,t),this}onQuietHoursUpdated(t){return this.transport.on(exports.ChatEvent.QUIET_HOURS_UPDATED,t),this}onMessageRemindersChanged(t){return this.transport.on(exports.ChatEvent.MESSAGE_REMINDERS_CHANGED,t),this}onMessageReminderDue(t){return this.transport.on(exports.ChatEvent.MESSAGE_REMINDER_DUE,t),this}onConversationPermissionsUpdated(t){return this.transport.on(exports.ChatEvent.CONVERSATION_PERMISSIONS_UPDATED,t),this}onHopMeetingUpdated(t){return this.transport.on(exports.ChatEvent.HOP_MEETING_UPDATED,t),this}onHuddleUpdated(t){return this.transport.on(exports.ChatEvent.HUDDLE_UPDATED,t),this}onMessageTranscriptUpdated(t){return this.transport.on(exports.ChatEvent.MESSAGE_TRANSCRIPT_UPDATED,t),this}onInboxUpdated(t){return this.transport.on(exports.ChatEvent.INBOX_UPDATED,t),this}onInternalNote(t){return this.transport.on(exports.ChatEvent.INTERNAL_NOTE,t),this}onInternalNoteDeleted(t){return this.transport.on(exports.ChatEvent.INTERNAL_NOTE_DELETED,t),this}onConversationNotesUpdated(t){return this.transport.on(exports.ChatEvent.CONVERSATION_NOTES_UPDATED,t),this}onCsatUpdated(t){return this.transport.on(exports.ChatEvent.CSAT_UPDATED,t),this}onThreadUpdate(t){return this.transport.on(exports.ChatEvent.THREAD_MESSAGES,t),this}onConversationUnread(t){return this.transport.on(exports.ChatEvent.CONVERSATION_UNREAD,t),this}onConversationRead(t){return this.transport.on(exports.ChatEvent.CONVERSATION_READ,t),this}onMessageDeleted(t){return this.transport.on(exports.ChatEvent.MESSAGE_DELETED,t),this}onPreChatSubmitted(t){return this.transport.on(exports.ChatEvent.PRE_CHAT_SUBMITTED,t),this}onHopCaptionsState(t){return this.transport.on(exports.ChatEvent.HOP_CAPTIONS_STATE,t),this}onHopCaptionText(t){return this.transport.on(exports.ChatEvent.HOP_CAPTION_TEXT,t),this}}const w=encodeURIComponent,N=({limit:t,...e})=>({...e,...void 0!==t?{limit:String(t)}:{}});function L(t){if(!t)return;const{limit:e,...n}=t;return{...n,...void 0!==e?{limit:String(e)}:{}}}function D(t){if(t)return{...t,limit:void 0!==t.limit?String(t.limit):void 0}}function k(t){if(!t)return;const e={};return t.q&&(e.q=t.q),t.nextCursor&&(e.nextCursor=t.nextCursor),t.source&&(e.source=t.source),e}function M(t){const e={};for(const[n,r]of Object.entries(t))r&&(e[n]=r);return e}function H(t){const{handles:e,...n}=t||{};return{...n,handles:Array.isArray(e)?e.join(","):e}}const U=(t,e)=>`/chat-users/links/${w(t)}/members/${w(e)}/follow`,G=/^[A-Za-z0-9_-]{8,64}$/,$=(t,e)=>`/chats/conversations/${w(t)}/messages/${w(e)}`,F=t=>`/chats/agent-inbox/${w(t)}`;class W{constructor(t){this.transport=t}setOwnerToken(t){this.transport.setOwnerToken(t)}setMemberToken(t){this.transport.setMemberToken(t)}async registerMembers(t){return this.transport.post("/members",t)}async registerMember(t){const e=await this.transport.post("/members/single",t);return Array.isArray(e)?e[0]:e}async listMembers(t){return this.transport.get("/members",t)}async getMember(t){return this.transport.get(`/members/${t}`)}async createChatLink(t){return this.transport.post("/chat-links",t)}async listChatLinks(t){return this.transport.get("/chat-links",t)}async getChatLink(t){return this.transport.get(`/chat-links/${t}`)}async updateChatLink(t,e){return this.transport.patch(`/chat-links/${t}`,e)}async createConversation(t,e){return this.transport.post(`/chat-links/${t}/conversations`,e)}async listPublicConversations(t,e){return this.transport.get(`/public/${t}/conversations`,e)}async getMemberConversations(t,e){return this.transport.get(`/members/${t}/conversations`,e)}async getConversationUsers(t,e){return this.transport.get(`/conversations/${t}/users`,e)}async getMessages(t,e,n){return this.transport.get(`/members/${t}/conversations/${e}/messages`,n)}async sendMessage(t){return this.transport.post("/chats/messages/send",t)}async listSentMessages(t){const{conversationId:e,...n}=t||{};return this.transport.get("/chats/messages",{...n,...e?{chatMessageByConversationIds:e}:{}})}async cancelScheduledMessage(t,e){return this.transport.request("DELETE",`/chats/messages/${t}`,{body:{conversationId:e}})}async rescheduleMessage(t,e,n){return this.transport.patch(`/chats/messages/${t}`,{scheduledAt:n,conversationId:e})}async sendPushNotification(t){return this.transport.post("/chats/push-notification",t)}async exportChat(t){return this.transport.post("/chats/exports",t)}async getExports(t){return this.transport.get("/chats/exports",t)}async getCannedResponses(){return this.transport.get("/chats/canned-responses")}async createCannedResponse(t){return this.transport.post("/chats/canned-responses",t)}async updateCannedResponse(t,e){return this.transport.patch(`/chats/canned-responses/${t}`,e)}async deleteCannedResponse(t){return this.transport.delete(`/chats/canned-responses/${t}`)}async markCannedResponseUsed(t){return this.transport.post(`/chats/canned-responses/${encodeURIComponent(t)}/used`,{})}async getWebhooks(t){return this.transport.get("/chats/webhooks",t)}async getWebhook(t){return this.transport.get(`/chats/webhooks/${t}`)}async createWebhook(t){return this.transport.post("/chats/webhooks",t)}async updateWebhook(t,e){return this.transport.patch(`/chats/webhooks/${t}`,e)}async deleteWebhook(t){return this.transport.delete(`/chats/webhooks/${t}`)}async testWebhook(t){return this.transport.post(`/chats/webhooks/${w(t)}/test`)}async testAutomationKeywords(t,e){return this.transport.owner("POST","/chats/automations/test",{body:{chatLinkId:t,keywords:e}})}async testWebhookAsOwner(t){return this.transport.owner("POST",`/chats/webhooks/${w(t)}/test`)}async getWebhookDeliveries(t,e){return this.transport.owner("GET",`/chats/webhooks/${w(t)}/deliveries`,{query:void 0!==(null==e?void 0:e.limit)?{limit:String(e.limit)}:void 0})}async retryWebhookDelivery(t,e){return this.transport.owner("POST",`/chats/webhooks/${w(t)}/deliveries/${w(e)}/retry`,{noRetry:!0})}async rotateWebhookSecret(t){return this.transport.owner("POST",`/chats/webhooks/${w(t)}/rotate-secret`,{noRetry:!0})}async startWebhookCapture(t){return this.transport.owner("POST",`/chats/webhooks/${w(t)}/capture`,{noRetry:!0})}async readWebhookCapture(t,e=0){return this.transport.owner("GET",`/chats/webhooks/${w(t)}/capture`,{query:{after:String(e)}})}async stopWebhookCapture(t){return this.transport.owner("DELETE",`/chats/webhooks/${w(t)}/capture`,{noRetry:!0})}async listIncomingWebhooks(t,e){const n=e?{...e.status?{status:e.status}:{},...e.nextCursor?{nextCursor:e.nextCursor}:{},...void 0!==e.limit?{limit:String(e.limit)}:{}}:void 0;return this.transport.get(`/chats/conversations/${w(t)}/incoming-webhooks`,n)}async createIncomingWebhook(t,e){return this.transport.request("POST",`/chats/conversations/${w(t)}/incoming-webhooks`,{body:e,noRetry:!0})}async updateIncomingWebhook(t,e,n){return this.transport.request("PATCH",`/chats/conversations/${w(t)}/incoming-webhooks/${w(e)}`,{body:n,noRetry:!0})}async regenerateIncomingWebhook(t,e){return this.transport.request("POST",`/chats/conversations/${w(t)}/incoming-webhooks/${w(e)}/regenerate`,{body:{},noRetry:!0})}async revokeIncomingWebhook(t,e){return this.transport.request("DELETE",`/chats/conversations/${w(t)}/incoming-webhooks/${w(e)}`,{noRetry:!0})}async listMeetings(t){return this.transport.owner("GET","/hops/owner/meetings",{query:N(t)})}async scheduleMeeting(t,e){const n=null==e?void 0:e.idempotencyKey;return this.transport.owner("POST","/hops/owner/meetings",{body:t,noRetry:!n,...n?{headers:{"Idempotency-Key":n}}:{}})}async cancelMeeting(t,e){return this.transport.owner("DELETE",`/hops/owner/meetings/${w(t)}`,{query:e?{reason:e}:void 0,noRetry:!0})}async listMeetingsWithKey(t){return this.transport.get("/meetings",N(t))}async scheduleMeetingWithKey(t,e){const n=null==e?void 0:e.idempotencyKey;return this.transport.request("POST","/meetings",{body:t,noRetry:!n,...n?{headers:{"Idempotency-Key":n}}:{}})}async cancelMeetingWithKey(t,e){return this.transport.request("DELETE",`/meetings/${w(t)}`,{query:e?{reason:e}:void 0,noRetry:!0})}async translateMessage(t,e){return this.transport.post("/chats/translate",{messageId:t,targetLanguage:e})}async getChatUserProfile(){return this.transport.get("/chat-users/me")}async updateChatUserProfile(t){return this.transport.patch("/chat-users/me",t)}async getHandleEditInfo(){return this.transport.get("/chat-users/me/handle-edits")}async sendAdminReply(t){return this.transport.post("/chats/messages/admin-reply",t)}async getFeaturePricing(){return this.transport.get("/subscriptions/features")}async giftFeature(t){return this.transport.post("/subscriptions/features/gift",t)}async verifyGiftFeature(t){return this.transport.post("/subscriptions/features/gift/verify",t)}async getCannedResponseSuggested(t){return this.transport.get("/chats/canned-responses/suggested",t?{category:t}:void 0)}async useSuggestedCannedResponse(t){return this.transport.post("/chats/canned-responses/use-suggested",{suggestedId:t})}async getAdminMentions(t){return this.transport.get("/chats/messages/admin-mentions",H(t))}async getAdminMentionsAsOwner(t){return this.transport.owner("GET","/chats/messages/admin-mentions",{query:H(t)})}async globalSearch(t){return this.transport.get("/chats/global-search",{q:t})}async bulkExportChat(t){return this.transport.post("/chats/conversations/bulk-export",t)}async getLinkWorkspaceInfo(t){return this.transport.get(`/chat-links/${t}/info`)}async getWebinarRegistrations(t){return this.transport.get(`/chats/conversations/${t}/webinar/registrations`)}async getAppVersion(){return this.transport.get("/version")}async createLinkEmoji(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/emojis`,{body:e})}async listLinkEmojis(t,e){return this.transport.owner("GET",`/chats/links/${w(t)}/emojis`,{query:e})}async updateLinkEmoji(t,e,n){return this.transport.owner("PATCH",`/chats/links/${w(t)}/emojis/${w(e)}`,{body:n})}async enableLinkEmoji(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/emojis/${w(e)}/enable`)}async disableLinkEmoji(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/emojis/${w(e)}/disable`)}async deleteLinkEmoji(t,e){return this.transport.owner("DELETE",`/chats/links/${w(t)}/emojis/${w(e)}`)}async getLinkEmojiPack(t){return this.transport.request("GET",`/in/${w(t)}/emoji-pack`,{base:"root",auth:"none"})}async createPost(t){return this.transport.owner("POST","/posts",{body:t})}async listPosts(t){return this.transport.owner("GET","/posts",{query:t})}async schedulePost(t,e){return this.transport.owner("POST",`/posts/${w(t)}/schedule`,{body:e})}async publishPost(t){return this.transport.owner("POST",`/posts/${w(t)}/publish`)}async cancelPostSchedule(t){return this.transport.owner("POST",`/posts/${w(t)}/cancel-schedule`)}async getPromoAnalytics(t){return this.transport.owner("GET",`/posts/${w(t)}/analytics`)}async trackPromoClick(t,e){const n=e&&G.test(e)?{visitorId:e}:{};return this.transport.request("POST",`/promos/${w(t)}/click`,{body:n,base:"api",auth:"none",noRetry:!0})}async getMessageInfo(t,e,n){return this.transport.user("GET",`/chats/conversations/${w(t)}/messages/${w(e)}/info`,{query:n})}async getMessageEditHistory(t,e){return this.transport.user("GET",`/chats/conversations/${w(t)}/messages/${w(e)}/history`)}async exportConversationAsAdmin(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/member-export`,{body:e?{format:e}:{},auth:"member"})}async exportConversationAsMember(t,e={}){return this.transport.user("POST",`/chats/conversations/${w(t)}/member-export`,{body:e,auth:"member"})}async getMemberExportStatus(t,e){return this.transport.user("GET",`/chats/conversations/${w(t)}/member-export/${w(e)}`,{auth:"member"})}async exportConversationAsOwner(t,e){return this.transport.owner("POST",`/chats/conversations/${w(t)}/export`,{body:e})}async muteConversation(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/mute`,{body:{duration:e},auth:"member"})}async getQuietHours(){return this.transport.user("GET","/chats/settings/quiet-hours",{auth:"member"})}async setQuietHours(t){return this.transport.user("POST","/chats/settings/quiet-hours",{body:t,auth:"member"})}async createReminder(t){return this.transport.user("POST","/chats/reminders",{body:t,auth:"member"})}async listReminders(t){return this.transport.user("GET","/chats/reminders",{query:t,auth:"member"})}async cancelReminder(t){return this.transport.user("DELETE",`/chats/reminders/${w(t)}`,{auth:"member"})}async completeReminder(t){return this.transport.user("POST",`/chats/reminders/${w(t)}/done`,{auth:"member"})}async getConversationPermissions(t){return this.transport.user("GET",`/chats/conversations/${w(t)}/permissions`)}async updateConversationPermissions(t,e){return this.transport.user("PATCH",`/chats/conversations/${w(t)}/permissions`,{body:e})}async getTranscribeAvailability(){return this.transport.user("GET","/chats/transcription/availability")}async transcribeMessage(t,e){return this.transport.user("POST",`${$(t,e)}/transcribe`)}async getTranscript(t,e){return this.transport.user("GET",`${$(t,e)}/transcript`)}async summarizeTranscript(t,e){return this.transport.user("POST",`${$(t,e)}/transcript/summary`)}async translateTranscript(t,e,n){return this.transport.user("POST",`${$(t,e)}/transcript/translate`,{body:{targetLanguage:n}})}async startHuddle(t,e){return this.transport.user("POST",`/hops/huddles/${w(t)}/start`,{body:e?{initialMediaKind:e}:{},auth:"member"})}async getHuddle(t){return this.transport.user("GET",`/hops/huddles/${w(t)}`,{auth:"member"})}async endHuddle(t){return this.transport.user("POST",`/hops/huddles/${w(t)}/end`,{auth:"member"})}async declineHopInvite(t){return this.transport.user("POST",`/hops/${w(t)}/decline`,{auth:"member"})}async pushDeclineCall(t){return this.transport.request("POST","/hops/push-decline",{base:"api",auth:"none",body:{token:t},noRetry:!0})}async registerDevice(t){return this.transport.user("POST","/notifications/register-device",{body:t})}async inviteToHop(t,e){return this.transport.user("POST",`/hops/${w(t)}/invite`,{body:{chatUserIds:e},auth:"member",noRetry:!0})}async setLinkAutoTranscribe(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/auto-transcribe`,{body:{enabled:e}})}async setLinkAgentInbox(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/agent-inbox`,{body:{enabled:e}})}async listInbox(t){return this.transport.owner("GET","/chats/inbox",{query:t})}async assignInbox(t,e){return this.transport.owner("POST",`/chats/inbox/${w(t)}/assign`,{body:{assigneeId:e}})}async setInboxStatus(t,e){return this.transport.owner("POST",`/chats/inbox/${w(t)}/status`,{body:{status:e}})}async setLinkInboxSettings(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/inbox-settings`,{body:e})}async setLinkDiscoverable(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/discoverable`,{body:{enabled:e}})}async submitCsat(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/csat`,{body:e,auth:"member",noRetry:!0})}async listCsatRatings(t){return this.transport.get("/chats/csat",L(t))}async getCsatSummary(t){return this.transport.get("/chats/csat/summary",L(t))}async listCsatRatingsAsOwner(t){return this.transport.owner("GET","/chats/csat",{query:L(t)})}async getCsatSummaryAsOwner(t){return this.transport.owner("GET","/chats/csat/summary",{query:L(t)})}async getLinkMemberList(t,e){const n=e?{...e,limit:void 0!==e.limit?String(e.limit):void 0}:void 0;return this.transport.owner("GET",`/chats/links/${w(t)}/member-list`,{query:n})}async revokeLinkInvite(t,e){return this.transport.owner("DELETE",`/chats/links/${w(t)}/members/${w(e)}/invite`,{noRetry:!0})}async setWidgetConfig(t,e){return this.transport.owner("PUT",`/chats/links/${w(t)}/widget`,{body:e})}async getInboxAgentProfile(){return this.transport.user("GET","/chats/agent-inbox/me",{auth:"member"})}async listInternalNotes(t,e){return this.transport.user("GET",`${F(t)}/internal-notes`,{query:e,auth:"member"})}async createInternalNote(t,e){return this.transport.user("POST",`${F(t)}/internal-notes`,{body:e,auth:"member"})}async deleteInternalNote(t,e){return this.transport.user("DELETE",`${F(t)}/internal-notes/${w(e)}`,{auth:"member"})}async getAgentInboxState(t){return this.transport.user("GET",`${F(t)}/state`,{auth:"member"})}async agentAssignConversation(t,e){return this.transport.user("POST",`${F(t)}/assign`,{body:{assigneeId:e},auth:"member"})}async agentSetInboxStatus(t,e){return this.transport.user("POST",`${F(t)}/status`,{body:{status:e},auth:"member"})}async listConversationNotes(t,e){return this.transport.user("GET",`${F(t)}/notes`,{query:e,auth:"member"})}async createConversationNote(t,e){return this.transport.user("POST",`${F(t)}/notes`,{body:{text:e},auth:"member"})}async updateConversationNote(t,e,n){return this.transport.user("PATCH",`${F(t)}/notes/${w(e)}`,{body:{text:n},auth:"member"})}async deleteConversationNote(t,e){return this.transport.user("DELETE",`${F(t)}/notes/${w(e)}`,{auth:"member"})}async getConversationSummary(t){return this.transport.user("GET",`${F(t)}/summary`,{auth:"member"})}async draftConversationReply(t,e){return this.transport.user("POST",`/chats/conversations/${encodeURIComponent(t)}/draft-reply`,{body:e?{note:e}:{},auth:"member",noRetry:!0})}async getDraftReply(t){return this.transport.user("POST",`${F(t)}/draft-reply`,{auth:"member"})}async getConversationCatchUp(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/catch-up`,{body:{unreadCount:e},auth:"member"})}async getDrafts(){return this.transport.user("GET","/chats/drafts",{auth:"member"})}async setConversationTopic(t,e){return this.transport.user("POST",`/chats/conversations/${w(t)}/topic`,{body:{topicId:e},auth:"member"})}async getPresenceStats(t){return this.transport.request("GET",`/in/${w(t)}/presence-stats`,{base:"root",auth:"none"})}async listMyChatLinks(t){return this.transport.user("GET","/chat-users/me/links",{query:t,auth:"member"})}async leaveMyLink(t){return this.transport.user("POST",`/chat-users/me/links/${w(t)}/leave`,{auth:"member"})}async claimGuest(t){return this.transport.user("POST","/chat-users/me/claim-guest",{body:t,auth:"member",noRetry:!0})}async setMyLinkNotify(t,e){return this.transport.user("PUT",`/chat-users/me/links/${w(t)}/notify`,{body:{level:e},auth:"member"})}async listLinkMembers(t,e){const n=void 0===e?{chatLinkId:t}:{chatLinkId:t,limit:String(e)};return this.transport.user("GET","/chat-users/me/link-members",{query:n,auth:"member"})}async getLinkAvailability(t){return this.transport.request("GET",`/in/${w(t)}/availability`,{base:"root",auth:"none"})}async announceGift(t,e,n){return this.transport.user("POST",`/chats/conversations/${w(t)}/gift-announce`,{body:n?{reference:e,note:n}:{reference:e},auth:"member"})}async listAccountSessions(){return this.transport.owner("GET","/users/sessions")}async revokeAccountSession(t){return this.transport.owner("DELETE",`/users/sessions/${w(t)}`)}async revokeOtherAccountSessions(){return this.transport.owner("POST","/users/sessions/revoke-others")}async listMySessions(){return this.transport.user("GET","/chat-users/me/sessions",{auth:"member"})}async revokeMySession(t){return this.transport.user("DELETE",`/chat-users/me/sessions/${w(t)}`,{auth:"member"})}async revokeMyOtherSessions(){return this.transport.user("POST","/chat-users/me/sessions/revoke-others",{auth:"member"})}async getAccountQuietHours(){return this.transport.owner("GET","/users/me/quiet-hours")}async setAccountQuietHours(t){return this.transport.owner("PUT","/users/me/quiet-hours",{body:t})}async sendScheduledMessageNow(t){return this.transport.user("POST",`/chats/messages/${w(t)}/send-now`,{auth:"member"})}async getLinkOnlineCount(t){return this.transport.request("GET",`/in/${w(t)}/online-count`,{base:"root",auth:"none"})}async joinLinkAsGuest(t,e){return this.transport.request("POST",`/in/${w(t)}/join-guest`,{base:"root",auth:"none",body:e,noRetry:!0})}async verifyMeetingGuest(t,e){return this.transport.request("POST",`/in/${w(t)}/join-guest/verify`,{base:"root",auth:"none",body:e,noRetry:!0})}async notifyWhenLinkReopens(t,e){return this.transport.request("POST",`/in/${w(t)}/notify-reopen`,{base:"root",auth:"none",body:{email:e}})}async subscribeToStatusUpdates(t){return this.transport.request("POST","/health/subscribe",{base:"api",auth:"none",body:{email:t}})}async unsubscribeFromStatusUpdates(t,e){return this.transport.request("GET","/health/unsubscribe",{base:"api",auth:"none",query:{email:t,token:e}})}async getWebinarInfo(t){return this.transport.request("GET",`/chats/conversations/${w(t)}/webinar/info`,{base:"api",auth:"none"})}async registerForWebinar(t,e){return this.transport.request("POST",`/chats/conversations/${w(t)}/webinar/register`,{base:"api",auth:"none",body:e,noRetry:!0})}async requestBusinessSignInCode(t){return this.transport.request("POST","/users/sign-in-code",{base:"api",auth:"none",body:{email:t},noRetry:!0})}async verifyBusinessSignInCode(t,e){const n=await this.transport.request("POST","/users/sign-in-code/verify",{base:"api",auth:"none",body:{email:t,code:e},noRetry:!0});return"accessToken"in n&&n.accessToken&&this.transport.setOwnerToken(n.accessToken),n}async verifyBusinessTotp(t,e){const n=await this.transport.request("POST","/users/2fa/verify",{base:"api",auth:"none",body:{pendingToken:t,token:e},noRetry:!0});return(null==n?void 0:n.accessToken)&&this.transport.setOwnerToken(n.accessToken),n}async listAccountChatLinks(t){return this.transport.owner("GET","/chats/links",{query:t})}async updateAccountProfile(t){return this.transport.owner("PATCH","/users/me",{body:t})}async listWorkspaceTeams(){return this.transport.owner("GET","/users/teams")}async createWorkspaceTeam(t){return this.transport.owner("POST","/users/teams",{body:t})}async updateWorkspaceTeam(t,e){return this.transport.owner("PATCH",`/users/teams/${w(t)}`,{body:e})}async deleteWorkspaceTeam(t){return this.transport.owner("DELETE",`/users/teams/${w(t)}`)}async inviteTeamMember(t){return this.transport.owner("POST","/users/team/invite",{body:t,noRetry:!0})}async inviteChatUser(t){return this.transport.owner("POST","/chats/chat-users/invite",{body:t,noRetry:!0})}async getMemberFollowStatus(t,e){return this.transport.user("GET",U(t,e),{auth:"member"})}async followMember(t,e){return this.transport.user("POST",U(t,e),{auth:"member"})}async unfollowMember(t,e){return this.transport.user("DELETE",U(t,e),{auth:"member"})}async getCalendarSyncStatus(){return this.transport.user("GET","/calendar-sync/status",{auth:"member"})}async connectCalendar(t,e){return this.transport.user("POST",`/calendar-sync/${w(t)}/connect`,{body:e||{},auth:"member",noRetry:!0})}async completeNativeCalendarConnect(t){return this.transport.user("POST","/calendar-sync/native/complete",{body:{code:t},auth:"member",noRetry:!0})}async disconnectCalendar(t){return this.transport.user("DELETE",`/calendar-sync/${w(t)}`,{auth:"member"})}async setCalendarShareBusy(t,e){return this.transport.user("PATCH",`/calendar-sync/${w(t)}/settings`,{body:{shareBusy:e},auth:"member"})}async syncCalendarNow(){return this.transport.user("POST","/calendar-sync/sync",{auth:"member",noRetry:!0})}async getCalendarBusy(t){return this.transport.user("GET","/calendar-sync/busy",{query:{userIds:t.userIds.join(","),from:t.from,to:t.to},auth:"member"})}async listActivity(t){return this.transport.user("GET","/notifications/activity",{query:D(t)})}async getActivityUnreadCount(){return this.transport.user("GET","/notifications/activity/unread-count")}async markAllActivityRead(){return this.transport.user("PATCH","/notifications/activity/read-all")}async getSidebarCategories(t){return this.transport.user("GET","/chats/categories",{query:t?{chatLinkId:t}:void 0})}async setConversationCategory(t,e){return this.transport.user("PUT",`/chats/conversations/${w(t)}/category`,{body:{category:e}})}async renameSidebarCategory(t){return this.transport.user("PATCH","/chats/categories",{body:t})}async deleteSidebarCategory(t,e){return this.transport.user("DELETE","/chats/categories",{query:{name:t,...e?{chatLinkId:e}:{}}})}async sendPushReply(t,e,n){return this.transport.request("POST","/chats/push-reply",{base:"api",auth:"none",body:{token:t,message:e,...n?{deviceHint:n}:{}},noRetry:!0})}async redeemMeetingGuestPass(t,e){return this.transport.user("POST","/hops/meetings/guest-pass",{body:{code:t,token:e},auth:"member"})}async joinMeetingByLink(t){return this.transport.user("POST","/hops/meetings/join-by-link",{body:{code:t},auth:"member"})}async joinMeetingFromChannel(t){return this.transport.user("POST",`/hops/meetings/${w(t)}/join-from-channel`,{auth:"member"})}async requestWebinarRecordingLink(t,e){return this.transport.request("POST",`/chats/conversations/${w(t)}/webinar/recording-link`,{base:"api",auth:"none",body:{email:e},noRetry:!0})}async getWebinarRecording(t,e){return this.transport.request("GET",`/chats/conversations/${w(t)}/webinar/recording`,{base:"api",auth:"none",headers:{"X-Recording-Token":e}})}async getWebinarRecordingsAsOwner(t){return this.transport.owner("GET",`/chats/conversations/${w(t)}/webinar/recordings`)}async getGiftCatalog(){return this.transport.user("GET","/gifts/catalog")}async sendPeerGift(t){return this.transport.user("POST","/gifts/peer",{body:t,auth:"member",noRetry:!0})}async verifyPeerGift(t){return this.transport.request("POST","/gifts/peer/verify",{base:"api",auth:"none",body:{reference:t}})}async listReceivedGifts(t){return this.transport.user("GET","/gifts/received",{query:t,auth:"member"})}async getOwnerGifts(t){return this.transport.owner("GET","/gifts/owner",{query:D(t)})}async getGiftBalance(){return this.transport.user("GET","/gifts/balance",{auth:"member"})}async requestGiftPayout(){return this.transport.user("POST","/gifts/payouts",{auth:"member",noRetry:!0})}async requestBusinessPasswordReset(t){return this.transport.request("POST","/users/forgot-password",{base:"api",auth:"none",body:{identifier:t},noRetry:!0})}async resetBusinessPassword(t){return this.transport.request("POST","/users/reset-password",{base:"api",auth:"none",body:t,noRetry:!0})}async getPasswordResetStatus(t){return this.transport.request("GET","/users/reset-password/status",{base:"api",auth:"none",query:{token:t}})}async requestChatPasswordReset(t){return this.transport.request("POST","/chat-users/forgot-password",{base:"api",auth:"none",body:t,noRetry:!0})}async resetChatPassword(t){return this.transport.request("POST","/chat-users/reset-password",{base:"api",auth:"none",body:t,noRetry:!0})}async requestLinkPasswordReset(t,e){return this.transport.request("POST",`/in/${w(t)}/forgot-password`,{base:"root",auth:"none",body:{identifier:e},noRetry:!0})}async resetLinkPassword(t,e){return this.transport.request("POST",`/in/${w(t)}/reset-password`,{base:"root",auth:"none",body:e,noRetry:!0})}async setLinkMode(t,e){return this.transport.owner("PATCH",`/chats/links/${w(t)}/mode`,{body:e})}async setConversationMode(t,e){return this.transport.user("PATCH",`/chats/conversations/${w(t)}/mode`,{body:e})}async getPublicLinkInfo(t){return this.transport.request("GET",`/in/${w(t)}`,{base:"root",auth:"none"})}async createAccountChatLink(t){return this.transport.owner("POST","/chats/links",{body:t,noRetry:!0})}async getLinkChannels(t){return this.transport.request("GET",`/in/${w(t)}/channels`,{base:"root",auth:"none"})}async getGiftStoreData(t){return this.transport.request("GET",`/in/${w(t)}/gift-store-data`,{base:"root",auth:"none"})}async setLinkJoinPolicy(t,e){return this.transport.owner("PATCH",`/chats/links/${w(t)}/join-policy`,{body:e})}async requestToJoinLink(t,e){return this.transport.request("POST",`/in/${w(t)}/join-request`,{base:"root",auth:"none",body:e,noRetry:!0})}async listJoinRequests(t,e){const n=e?{...e,limit:void 0!==e.limit?String(e.limit):void 0}:void 0;return this.transport.owner("GET",`/chats/links/${w(t)}/join-requests`,{query:n})}async approveJoinRequest(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/join-requests/${w(e)}/approve`,{noRetry:!0})}async denyJoinRequest(t,e){return this.transport.owner("POST",`/chats/links/${w(t)}/join-requests/${w(e)}/deny`,{noRetry:!0})}async getSupportGroupTeam(t){return this.transport.user("GET",`/chats/conversations/${w(t)}/support-team`,{auth:"member"})}async setSupportGroupTeam(t,e){return this.transport.user("PATCH",`/chats/conversations/${w(t)}/support-team`,{body:{teamId:e},auth:"member"})}async setLinkAppOrigins(t,e){return this.transport.owner("PUT",`/chats/links/${w(t)}/app-origins`,{body:{origins:e}})}async setLinkEmbedDomains(t,e){return this.transport.owner("PUT",`/chats/links/${w(t)}/embed-domains`,{body:{domains:e}})}async listPlans(){const t=this.transport.hasOwnerToken()?"owner":"none";return this.transport.request("GET","/subscriptions/plans",{base:"api",auth:t})}async getPlan(t){const e=this.transport.hasOwnerToken()?"owner":"none";return this.transport.request("GET",`/subscriptions/plans/${w(t)}`,{base:"api",auth:e})}async subscribeToPlan(t){return this.transport.owner("POST","/subscriptions/subscribe",{body:t,noRetry:!0})}async verifySubscription(t){return this.transport.request("POST","/subscriptions/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async listMySubscriptions(){return this.transport.owner("GET","/subscriptions/my-subscriptions")}async changePlan(t,e){return this.transport.owner("POST",`/subscriptions/${w(t)}/change-plan`,{body:e,noRetry:!0})}async cancelSubscription(t){return this.transport.owner("DELETE",`/subscriptions/${w(t)}`)}async cancelScheduledPlanChange(t){return this.transport.owner("DELETE",`/subscriptions/${w(t)}/scheduled-change`)}async giftPlan(t){return this.transport.user("POST","/subscriptions/plan/gift",{body:t,noRetry:!0})}async verifyPlanGift(t){return this.transport.request("POST","/subscriptions/plan/gift/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async getTrialStatus(){return this.transport.owner("GET","/subscriptions/trial")}async startTrial(t){return this.transport.owner("POST","/subscriptions/trial",{body:t,noRetry:!0})}async getRenewalStatus(){return this.transport.owner("GET","/subscriptions/renewal")}async renewSubscription(t,e){return this.transport.owner("POST",`/subscriptions/${w(t)}/renew`,{body:e||{},noRetry:!0})}async useBankTransferRenewals(){return this.transport.owner("POST","/subscriptions/payment-method/bank-transfer",{noRetry:!0})}async getStorageUsage(){return this.transport.user("GET","/subscriptions/storage")}async listStaffAccess(t){return this.transport.owner("GET","/staff-access",{query:D(t)})}async requestCustomPlan(t){return this.transport.request("POST","/plan-requests",{base:"api",auth:"none",body:t,noRetry:!0})}async requestCustomPlanAsOwner(t){return this.transport.owner("POST","/plan-requests/me",{body:t,noRetry:!0})}async getMyLatestPlanRequest(){return this.transport.owner("GET","/plan-requests/me/latest")}async listStoreFeatures(){return this.transport.request("GET","/subscriptions/features",{base:"api",auth:"none"})}async purchaseFeature(t){return this.transport.owner("POST","/subscriptions/features/purchase",{body:t,noRetry:!0})}async verifyFeaturePurchase(t){return this.transport.request("POST","/subscriptions/features/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async listMyFeaturePurchases(){return this.transport.user("GET","/subscriptions/features/my-purchases")}async giftWorkspaceFeature(t){return this.transport.user("POST","/subscriptions/features/gift",{body:t,noRetry:!0})}async verifyWorkspaceFeatureGift(t){return this.transport.request("POST","/subscriptions/features/gift/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async checkLinkCode(t){return this.transport.owner("GET","/chats/links/code-available",{query:{code:t}})}async getLinkModeCatalog(){return this.transport.owner("GET","/chats/links/modes")}async updateLinkTheme(t,e){return this.transport.owner("PATCH",`/chats/links/${w(t)}/theme`,{body:e})}async setLinkWhoCanJoin(t,e){return this.transport.owner("PATCH",`/chats/links/${w(t)}/who-can-join`,{body:{who:e}})}async getLinkCustomDomain(t){return this.transport.owner("GET",`/chats/links/${w(t)}/custom-domain`)}async setLinkCustomDomain(t,e){return this.transport.owner("PUT",`/chats/links/${w(t)}/custom-domain`,{body:{domain:e}})}async verifyLinkCustomDomain(t){return this.transport.owner("POST",`/chats/links/${w(t)}/custom-domain/verify`)}async wipeLinkMessages(t){return this.transport.owner("POST",`/chats/links/${w(t)}/wipe-messages`,{noRetry:!0})}async getLinkOverview(t){return this.transport.owner("GET",`/chats/links/${w(t)}/overview`)}async getChatLinkModeCatalog(){return this.transport.get("/chat-links/modes")}async setChatLinkMode(t,e){return this.transport.patch(`/chat-links/${w(t)}/mode`,e)}async getMyNote(t){return this.transport.user("GET",`/chats/conversations/${w(t)}/my-note`,{auth:"member"})}async setMyNote(t,e){return this.transport.user("PUT",`/chats/conversations/${w(t)}/my-note`,{body:{text:e},auth:"member"})}async setConversationPinned(t,e){return this.transport.user("PUT",`/chats/conversations/${w(t)}/pin`,{body:{pinned:e},auth:"member"})}async listStarredPeople(t){return this.transport.user("GET","/chat-users/me/starred",{query:t,auth:"member"})}async listStarredIds(){return this.transport.user("GET","/chat-users/me/starred/ids",{auth:"member"})}async starPerson(t){return this.transport.user("PUT",`/chat-users/me/starred/${w(t)}`,{auth:"member"})}async unstarPerson(t){return this.transport.user("DELETE",`/chat-users/me/starred/${w(t)}`,{auth:"member"})}async getAccountProfile(){return this.transport.owner("GET","/users/me")}async getKnownFeatureFlags(){return this.transport.owner("GET","/admins/feature-flags/known")}async listPendingTransfers(){return this.transport.owner("GET","/subscriptions/pending-transfers")}async purchaseExtraSeats(t){return this.transport.user("POST","/subscriptions/extra-seats",{body:t,noRetry:!0})}async verifyExtraSeats(t){return this.transport.request("POST","/subscriptions/extra-seats/verify",{base:"api",auth:"none",body:{reference:t},noRetry:!0})}async setStorageAddonAutoRenew(t,e){return this.transport.owner("POST",`/subscriptions/storage/addons/${w(t)}/auto-renew`,{body:{autoRenew:e}})}async createApiKey(t){return this.transport.owner("POST","/api-keys",{body:t,noRetry:!0})}async listApiKeys(t){return this.transport.owner("GET","/api-keys",{query:t})}async updateApiKey(t,e){return this.transport.owner("PATCH",`/api-keys/${w(t)}`,{body:e})}async rotateApiKey(t){return this.transport.owner("POST",`/api-keys/${w(t)}/rotate`,{noRetry:!0})}async revokeApiKey(t){return this.transport.owner("DELETE",`/api-keys/${w(t)}`)}async getApiKeyUsage(t,e="7d"){return this.transport.owner("GET",`/api-keys/${w(t)}/usage`,{query:{period:e}})}async getLiveFlex(){return this.transport.user("GET","/wallet")}async listLiveFlexTransactions(t){return this.transport.user("GET","/wallet/transactions",{query:t})}async fundLiveFlex(t){return this.transport.user("POST","/wallet/fund",{body:t,noRetry:!0})}async verifyLiveFlexFunding(t){return this.transport.user("POST","/wallet/fund/verify",{body:{reference:t}})}async listLiveFlexRecipients(t){return this.transport.user("GET","/wallet/recipients",{query:t?{q:t}:void 0})}async listLiveFlexBanks(){return this.transport.user("GET","/wallet/banks")}async setLiveFlexPayoutBank(t){return this.transport.user("PUT","/wallet/payout/bank",{body:t,noRetry:!0})}async setLiveFlexPayoutCrypto(t){return this.transport.user("PUT","/wallet/payout/crypto",{body:t,noRetry:!0})}async confirmLiveFlexPayout(t){return this.transport.user("POST","/wallet/payout/confirm",{body:{code:t},noRetry:!0})}async clearLiveFlexPayout(t){return this.transport.user("DELETE",`/wallet/payout/${w(t)}`)}async withdrawLiveFlex(t){return this.transport.user("POST","/wallet/withdraw",{body:t,noRetry:!0})}async sendLiveFlex(t){return this.transport.user("POST","/wallet/send",{body:t,noRetry:!0})}async startLiveFlexPinSetup(){return this.transport.user("POST","/wallet/pin/start",{noRetry:!0})}async setLiveFlexPin(t){return this.transport.user("POST","/wallet/pin",{body:t,noRetry:!0})}async startLiveFlexLink(){return this.transport.user("POST","/wallet/link/start",{noRetry:!0})}async linkLiveFlex(t){return this.transport.user("POST","/wallet/link",{body:t,noRetry:!0})}async setLiveFlexTag(t){return this.transport.user("PUT","/wallet/tag",{body:{tag:t},noRetry:!0})}async findLiveFlexTag(t){return this.transport.user("GET",`/wallet/tags/${w(t.replace(/^\$/,""))}`)}async listLiveFlexApprovals(){return this.transport.owner("GET","/wallet/approvals")}async decideLiveFlexApproval(t,e){return this.transport.owner("PATCH",`/wallet/approvals/${w(t)}/${w(e)}`,{noRetry:!0})}async getLiveFlexTeamLimits(){return this.transport.owner("GET","/wallet/team-limits")}async setLiveFlexTeamLimits(t){return this.transport.owner("PUT","/wallet/team-limits",{body:t})}async createLiveFlexRequest(t){return this.transport.user("POST","/wallet/requests",{body:t,auth:"member",noRetry:!0})}async listLiveFlexRequests(t="incoming"){return this.transport.user("GET","/wallet/requests",{query:{box:t},auth:"member"})}async getLiveFlexRequest(t){return this.transport.user("GET",`/wallet/requests/${w(t)}`,{auth:"member"})}async payLiveFlexRequest(t,e={}){return this.transport.user("POST",`/wallet/requests/${w(t)}/pay`,{body:e,auth:"member",noRetry:!0})}async declineLiveFlexRequest(t){return this.transport.user("POST",`/wallet/requests/${w(t)}/decline`,{auth:"member",noRetry:!0})}async blockLiveFlexRequester(t){return this.transport.user("POST",`/wallet/requests/${w(t)}/block`,{auth:"member",noRetry:!0})}async cancelLiveFlexRequest(t){return this.transport.user("POST",`/wallet/requests/${w(t)}/cancel`,{auth:"member",noRetry:!0})}async createLiveFlexSplit(t){return this.transport.user("POST","/wallet/splits",{body:t,auth:"member",noRetry:!0})}async getLiveFlexSplit(t){return this.transport.user("GET",`/wallet/splits/${w(t)}`,{auth:"member"})}async cancelLiveFlexSplit(t){return this.transport.user("POST",`/wallet/splits/${w(t)}/cancel`,{auth:"member",noRetry:!0})}async listLiveFlexStanding(){return this.transport.user("GET","/wallet/standing")}async createLiveFlexStanding(t){return this.transport.user("POST","/wallet/standing",{body:t,auth:"member",noRetry:!0})}async pauseLiveFlexStanding(t){return this.transport.user("POST",`/wallet/standing/${w(t)}/pause`,{noRetry:!0})}async resumeLiveFlexStanding(t){return this.transport.user("POST",`/wallet/standing/${w(t)}/resume`,{noRetry:!0})}async cancelLiveFlexStanding(t){return this.transport.user("POST",`/wallet/standing/${w(t)}/cancel`,{noRetry:!0})}async createLiveFlexPot(t){return this.transport.user("POST","/wallet/pots",{body:t,auth:"member",noRetry:!0})}async getLiveFlexPot(t){return this.transport.user("GET",`/wallet/pots/${w(t)}`,{auth:"member"})}async contributeLiveFlexPot(t,e={}){return this.transport.user("POST",`/wallet/pots/${w(t)}/contribute`,{body:e,auth:"member",noRetry:!0})}async closeLiveFlexPot(t){return this.transport.user("POST",`/wallet/pots/${w(t)}/close`,{auth:"member",noRetry:!0})}async cancelLiveFlexPot(t){return this.transport.user("POST",`/wallet/pots/${w(t)}/cancel`,{auth:"member",noRetry:!0})}async refundLiveFlexTransaction(t,e={}){return this.transport.user("POST",`/wallet/transactions/${w(t)}/refund`,{body:e,noRetry:!0})}async createLiveFlexPayLink(t){return this.transport.user("POST","/wallet/pay-links",{body:t,auth:"member",noRetry:!0})}async getLiveFlexPayLink(t){return this.transport.user("GET",`/wallet/pay-links/${w(t)}`,{auth:"member"})}async cancelLiveFlexPayLink(t){return this.transport.user("POST",`/wallet/pay-links/${w(t)}/cancel`,{auth:"member",noRetry:!0})}async payLiveFlexPayLink(t,e){return this.transport.user("POST",`/wallet/pay-links/${w(t)}/pay`,{body:e,auth:"member",noRetry:!0})}async verifyLiveFlexPayLink(t){return this.transport.user("POST","/wallet/pay-links/verify",{body:{reference:t}})}async getLiveFlexPayLinkReceiptLink(t){return this.transport.user("GET",`/wallet/pay-links/${w(t)}/receipt/link`,{auth:"member"})}async listLiveFlexReceipts(){return this.transport.user("GET","/wallet/receipts")}async getLiveFlexReceiptLink(t){return this.transport.user("GET",`/wallet/receipts/${w(t)}/link`)}async getLiveFlexStatementLinks(t){return this.transport.user("GET",`/wallet/statements/${w(t)}/links`)}async getStaffAccessGrant(){return this.transport.owner("GET","/staff-access/grant")}async setStaffAccessGrant(t){return this.transport.owner("PUT","/staff-access/grant",{body:t})}async revokeStaffAccessGrant(){return this.transport.owner("DELETE","/staff-access/grant")}async listWorkspaceStickers(t){return this.transport.owner("GET","/chats/stickers",{query:t})}async setWorkspaceStickerState(t,e){return this.transport.owner("PATCH",`/chats/stickers/${encodeURIComponent(t)}/workspace/${e}`)}async takeDownSticker(t){return this.transport.owner("POST",`/chats/stickers/${encodeURIComponent(t)}/take-down`)}async listCallHistory(t){return this.transport.user("GET","/hops/calls",{query:t,auth:"member"})}async getRecordingDownloadLink(t){return this.transport.user("POST",`/hops/recordings/${w(t)}/download`,{auth:"member",noRetry:!0})}async sendContactMessage(t){return this.transport.request("POST","/public/contact",{base:"root",auth:"none",body:t,noRetry:!0})}googleSignInUrl(t){return this.transport.urlFor("api","/users/google/start",t?{returnUrl:t}:void 0)}async redeemGoogleSignIn(t){const e=await this.transport.request("POST","/users/google/redeem",{base:"api",auth:"none",body:{handoff:t},noRetry:!0});return"accessToken"in e&&e.accessToken&&this.transport.setOwnerToken(e.accessToken),e}async getGifConfig(){return this.transport.user("GET","/chats/gifs/config")}async searchGifs(t){return this.transport.user("GET","/chats/gifs/search",{query:k(t)})}async trendingGifs(t){return this.transport.user("GET","/chats/gifs/trending",{query:k(t)})}async registerGifShare(t){return this.transport.user("POST","/chats/gifs/share",{body:t})}async reportGif(t){return this.transport.user("POST","/chats/gifs/report",{body:t})}async inviteSharedChannel(t){return this.transport.user("POST","/shared-channels",{body:t,auth:"member",noRetry:!0})}async listSharedChannels(t){return this.transport.user("GET","/shared-channels",{query:M({chatLinkId:t.chatLinkId,nextCursor:t.nextCursor}),auth:"member"})}async previewSharedChannelInvite(t){return this.transport.user("POST","/shared-channels/preview",{body:{token:t},auth:"member",noRetry:!0})}async listSharedChannelMembers(t){return this.transport.user("GET","/shared-channels/members",{query:M({chatLinkId:t.chatLinkId,q:t.q,sharedChannelId:t.sharedChannelId,nextCursor:t.nextCursor}),auth:"member"})}async getConversationSharedChannels(t,e){return this.transport.user("GET",`/shared-channels/conversations/${w(t)}`,{query:M({chatLinkId:e.chatLinkId}),auth:"member"})}async getSharedChannelPermissions(t,e){return this.transport.user("GET",`/shared-channels/conversations/${w(t)}/permissions`,{query:M({chatLinkId:e.chatLinkId}),auth:"member"})}async acceptSharedChannel(t,e){return this.transport.user("POST",`/shared-channels/${w(t)}/accept`,{body:e,auth:"member",noRetry:!0})}async acceptSharedChannelByToken(t){return this.transport.user("POST","/shared-channels/accept-token",{body:t,auth:"member",noRetry:!0})}async endSharedChannel(t,e){return this.transport.user("POST",`/shared-channels/${w(t)}/end`,{body:{chatLinkId:e.chatLinkId},auth:"member",noRetry:!0})}async updateSharedChannelMembers(t,e){return this.transport.user("PUT",`/shared-channels/${w(t)}/members`,{body:e,auth:"member",noRetry:!0})}async getSharedChannelAudit(t,e){return this.transport.user("GET",`/shared-channels/${w(t)}/audit`,{query:M({chatLinkId:e.chatLinkId,nextCursor:e.nextCursor}),auth:"member"})}async openSharedDirect(t){return this.transport.user("POST","/shared-channels/direct",{body:t,auth:"member",noRetry:!0})}async removeSharedChannelMember(t){return this.transport.user("POST","/shared-channels/remove-member",{body:t,auth:"member",noRetry:!0})}async removeSharedChannelMessage(t){return this.transport.user("POST","/shared-channels/remove-message",{body:t,auth:"member",noRetry:!0})}async linkChatUserToAccount(t){return this.transport.owner("POST","/chats/chat-users/link-account",{body:t,noRetry:!0})}}const q=["ringing","cancel","end","mute","unmute","hold","unhold"],B={brand:"livechatta:brand",unread:"livechatta:unread",themeLoaded:"CHATTA_APP:onThemeLoaded",unreadChange:"CHATTA_APP:onUnreadChange",preChat:"livechatta:prechat",hello:"livechatta:hello"};function V(t){try{const e=new URL(String(t||""));return"https:"===e.protocol||"http:"===e.protocol?e.origin:null}catch(t){return null}}function K(t){const e=V(t.getAttribute("src")||t.src),n=t.contentWindow;return!(!e||!n||(n.postMessage({type:B.hello},e),0))}function j(t){t.addEventListener("load",()=>{K(t)})}function Y(t,e){if(!e||"object"!=typeof e)return!1;const n=e,r=void 0!==n.payload?n.payload:n;switch(n.type){case B.brand:case B.themeLoaded:return t.setLinkBrand(null==r?void 0:r.primaryColor),(null==r?void 0:r.secondaryColor)&&t.setLinkSecondary(r.secondaryColor),(null==r?void 0:r.mode)&&t.setFrameMode(r.mode),!0;case B.unread:case B.unreadChange:return t.setUnread("number"==typeof r?r:{count:Number(null==r?void 0:r.count)}),!0;default:return!1}}class z{constructor(t){this.iframe=null,this.warned=!1,this.listeners=new Map,this.boundMessageHandler=null,this.nextCallId=1,this.pendingCalls=new Map,this.allowedOrigin=V(t.allowedOrigin)||"",this.runtime=i()}attach(t){this.iframe=t,this.boundMessageHandler||(this.boundMessageHandler=t=>this.handleIncoming(t),window.addEventListener("message",this.boundMessageHandler))}detach(){this.boundMessageHandler&&(window.removeEventListener("message",this.boundMessageHandler),this.boundMessageHandler=null),this.listeners.clear(),this.pendingCalls.clear(),this.iframe=null}on(t,e){let n=this.listeners.get(t);return n||(n=new Set,this.listeners.set(t,n)),n.add(e),()=>n.delete(e)}warnOnce(t){this.warned||(this.warned=!0,"undefined"!=typeof console&&console.warn(`[LiveChatta] Bridge: ${t} Nothing is sent to the chat frame.`))}targetOrigin(){const t=this.iframe;if(!t||!t.contentWindow)return null;if(!this.allowedOrigin)return this.warnOnce("no allowedOrigin is configured (set baseUrl), so there is no safe target origin."),null;const e=V("function"==typeof t.getAttribute&&t.getAttribute("src")||t.src);return e?e!==this.allowedOrigin?(this.warnOnce(`the iframe is on ${e} but the allowed origin is ${this.allowedOrigin}.`),null):e:null}send(t,e){const n=this.targetOrigin();return!!n&&(this.iframe.contentWindow.postMessage({type:`CHATTA_APP:${t}`,payload:e},n),!0)}onOpenWorkspaceDrawer(t){return this.on("openWorkspaceDrawer",t)}onUnreadChange(t){return this.on("onUnreadChange",t)}onLoginSuccess(t){return this.on("onLoginSuccess",t)}onLogout(t){return this.on("onLogout",t)}onThemeLoaded(t){return this.on("onThemeLoaded",t)}onScreenshotProtection(t){return this.on("enableScreenshotProtection",t)}onNotify(t){return this.on("notify",t)}onHopStartCall(t){return this.on("hopStartCall",t)}onHopEndCall(t){return this.on("hopEndCall",t)}onHopMuteChanged(t){return this.on("hopMuteChanged",t)}onLinkUnavailable(t){return this.on("onLinkUnavailable",t)}restoreSession(t){this.send("restoreSession",t)}sendHopInvite(t){this.send("hopInvite",t)}notifyUpdateReady(t){this.send("updateReady",t)}sendInit(t){this.send("init",t)}sendNativeCall(t,e){return!(!q.includes(t)||!/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))||(this.send("nativeCall",{action:t,sessionId:e}),0))}shareFiles(t,e){if(!this.targetOrigin())return!1;const n=(t||[]).filter(t=>"undefined"!=typeof File&&t instanceof File).slice(0,10),r="string"==typeof e?e.trim().slice(0,4e3):"";return!(!n.length&&!r)&&this.send("shareFiles",r?{files:n,text:r}:{files:n})}request(t,e,n=5e3){if(!this.iframe||!this.iframe.contentWindow)return Promise.reject(new Error("Bridge: iframe not attached"));const r=this.targetOrigin();if(!r)return Promise.reject(new Error("Bridge: no safe target origin (allowedOrigin and the iframe src must match)"));const s="sdk-"+this.nextCallId++;return new Promise((o,a)=>{const i=setTimeout(()=>{this.pendingCalls.delete(s),a(new Error(`Bridge: ${t} timed out after ${n}ms`))},n);this.pendingCalls.set(s,t=>{clearTimeout(i),o(t)}),this.iframe.contentWindow.postMessage({type:`CHATTA_APP:${t}`,payload:e,callId:s},r)})}handleIncoming(t){var e;if(!t.data||"object"!=typeof t.data)return;const n=t.data;if("string"!=typeof n.type||!n.type.startsWith("CHATTA_APP:"))return;const r=null===(e=this.iframe)||void 0===e?void 0:e.contentWindow;if(!this.allowedOrigin||!r||t.source!==r)return;if(t.origin!==this.allowedOrigin&&"null"!==t.origin)return;if("CHATTA_APP:response"===n.type&&n.callId){const t=this.pendingCalls.get(n.callId);return void(t&&(this.pendingCalls.delete(n.callId),t(n.result)))}const s=n.type.slice(11),o=this.listeners.get(s);o&&o.forEach(t=>{try{t(n.payload)}catch(t){}})}}const Q=["primaryColor","secondaryColor","primaryLight","primaryDark","primaryBg","bg","bgDark","textColor","textLight","textMuted","borderColor","borderLight"],X=[...Q,"fontFamily","logoUrl","theme"];function J(t,e,n){for(const r of n){const n=t[r];null!=n&&(e[r]=n)}}const Z="#D2400B",tt="#0B6E66",et="#6C5CE7",nt="#191715";function rt(t){if("string"!=typeof t)return null;let e=t.trim().replace(/^#/,"");return/^[0-9a-f]{3}$/i.test(e)&&(e=e.split("").map(t=>t+t).join("")),/^[0-9a-f]{6}$/i.test(e)?`#${e.toUpperCase()}`:null}function st(t){const e=rt(t);return!!e&&e!==et}function ot(t){const e=(rt(t)||Z).slice(1),[n,r,s]=[0,2,4].map(t=>function(t){const e=t/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}(parseInt(e.substr(t,2),16)));return.2126*n+.7152*r+.0722*s}function at(t,e){const n=ot(t),r=ot(e);return(Math.max(n,r)+.05)/(Math.min(n,r)+.05)}function it(t){return at(t,"#FFFFFF")>=at(t,nt)?"#FFFFFF":nt}function ht(t,e){const n=(rt(t)||Z).slice(1),r=ot(e)>.18?0:255,s=[0,2,4].map(t=>parseInt(n.substr(t,2),16));for(let t=0;t<=1.0001;t+=.05){const n="#"+s.map(e=>Math.round(e+(r-e)*t).toString(16).padStart(2,"0")).join("").toUpperCase();if(at(n,e)>=4.5)return n}return 0===r?nt:"#FFFFFF"}function ct(t,e){return"light"===t||"dark"===t||"system"===t?t:e}class lt{constructor(t){var e,n,r,s,o,a,i,h,c,l;if(this.floating=!0===t.floating,!t.container&&!this.floating)throw new Error("LiveChatta UI: container is required");this.container=t.container,this.width=t.width||(this.floating?"380px":"100%"),this.height=t.height||(this.floating?"640px":"600px"),this.hasExplicitPrimary=st(t.primaryColor),this.hasExplicitSecondary=!!t.secondaryColor,this.primaryColor=(this.hasExplicitPrimary?t.primaryColor:Z).replace("#",""),this.secondaryColor=(t.secondaryColor||tt).replace("#",""),this.primaryLight=null===(e=t.primaryLight)||void 0===e?void 0:e.replace("#",""),this.primaryDark=null===(n=t.primaryDark)||void 0===n?void 0:n.replace("#",""),this.primaryBg=null===(r=t.primaryBg)||void 0===r?void 0:r.replace("#",""),this.bg=null===(s=t.bg)||void 0===s?void 0:s.replace("#",""),this.bgDark=null===(o=t.bgDark)||void 0===o?void 0:o.replace("#",""),this.textColor=null===(a=t.textColor)||void 0===a?void 0:a.replace("#",""),this.textLight=null===(i=t.textLight)||void 0===i?void 0:i.replace("#",""),this.textMuted=null===(h=t.textMuted)||void 0===h?void 0:h.replace("#",""),this.borderColor=null===(c=t.borderColor)||void 0===c?void 0:c.replace("#",""),this.borderLight=null===(l=t.borderLight)||void 0===l?void 0:l.replace("#",""),this.fontFamily=t.fontFamily,this.logoUrl=t.logoUrl,this.theme=ct(t.theme,this.floating?"system":"light"),this.layout="bubbles"===t.layout||"lines"===t.layout?t.layout:void 0,this.position="bottom-left"===t.position?"bottom-left":"bottom-right",this.preload=!1!==t.preload,this.embedMode=t.embedMode||"auto",this.appVersion=t.appVersion||"1.0.0"}themeRecord(){const t={};return J(this,t,X),this.hasExplicitPrimary||delete t.primaryColor,this.hasExplicitSecondary||delete t.secondaryColor,t}toQueryParams(){const t=this.themeRecord();return this.layout&&(t.layout=this.layout),new URLSearchParams(t).toString()}toPostMessagePayload(){return{type:"livechatta:theme",...this.themeRecord()}}}const ut=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function pt(t){const e="string"==typeof t?/^(\d{1,2}):(\d{2})$/.exec(t.trim()):null;if(!e)return null;const n=+e[1],r=+e[2];return n<=24&&r<60&&60*n+r<=1440?60*n+r:null}function dt(t,e){try{const n=new Intl.DateTimeFormat("en-US",{timeZone:e,weekday:"short",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(t),r=t=>{var e;return(null===(e=n.find(e=>e.type===t))||void 0===e?void 0:e.value)||""},s=ut.indexOf(r("weekday")),o=+r("hour")%24*60+ +r("minute");return s<0||!Number.isFinite(o)?null:{day:s,minutes:o}}catch(t){return null}}function Et(t){if(!t||!1===t.enabled||!Array.isArray(t.windows))return[];const e=[];for(const n of t.windows){const t=pt(null==n?void 0:n.open),r=pt(null==n?void 0:n.close);null!==t&&null!==r&&n.day>=0&&n.day<=6&&t!==r&&e.push({day:Math.floor(n.day),open:t,close:r})}return e}function mt(t,e=new Date){const n=Et(t);if(!n.length)return!0;const r=dt(e,t.timezone);if(!r)return!0;const s=(r.day+6)%7;return n.some(t=>t.open<t.close?t.day===r.day&&r.minutes>=t.open&&r.minutes<t.close:t.day===r.day&&r.minutes>=t.open||t.day===s&&r.minutes<t.close)}function yt(t){return`${Math.floor(t/60)%24}:${String(t%60).padStart(2,"0")}`}function Tt(t,e=new Date){const n=Et(t),r=n.length?dt(e,t.timezone):null;if(!r)return null;for(let e=0;e<=7;e++){const s=(r.day+e)%7,o=n.filter(t=>t.day===s&&(e>0||t.open>r.minutes)).map(t=>t.open);if(!o.length)continue;const a=0===e?"today":1===e?"tomorrow":ut[s],i=t.timezoneLabel?` ${t.timezoneLabel}`:"";return`${a} ${yt(Math.min(...o))}${i}`}return null}function gt(t,e=new Date){return mt(t,e)?null:{backAt:Tt(t,e),message:null==t?void 0:t.awayMessage}}const Ct=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,St=/^[A-Za-z][\w-]{0,39}$/;function vt(t){var e;if(!t)return null;const n=!0===t?{}:t;if(!1===n.enabled)return null;let r=Array.isArray(n.fields)?n.fields.filter(t=>t&&St.test(t.name)&&t.label):[];if(!r.length){r=[{name:"name",label:"Your name",type:"text",required:!0},{name:"email",label:"Email",type:"email",required:!0}];const t=(n.topics||[]).filter(t=>"string"==typeof t&&t.trim());t.length&&r.push({name:"topic",label:"What do you need?",type:"select",required:!0,options:t})}return{...n,fields:r,submitLabel:n.submitLabel||"Start chat",note:null!==(e=n.note)&&void 0!==e?e:"We only use your email to reply."}}function Ot(t,e){var n;const r={};for(const s of t){const t=(e[s.name]||"").trim();t?"email"!==s.type||Ct.test(t)?"select"===s.type&&(null===(n=s.options)||void 0===n?void 0:n.length)&&!s.options.includes(t)?r[s.name]="Choose an option":t.length>500&&(r[s.name]="Keep this under 500 characters"):r[s.name]="Enter an email like name@example.com":s.required&&(r[s.name]="select"===s.type?"Choose an option":`Enter ${s.label.toLowerCase()}`)}return r}const At={surface:"#FFFFFF",text:"#191715",text2:"#5A544F",line:"#DEDAD0",bubble:"#FFFFFF",lineStrong:"#8F887C",danger:"#B4123A",info:"#1E56C2",infoSoft:"#E3ECFB",focus:"#1E56C2",shadow2:"0 8px 24px rgba(25,23,21,0.10), 0 2px 6px rgba(25,23,21,0.06)",shadow3:"0 24px 64px rgba(25,23,21,0.18), 0 4px 12px rgba(25,23,21,0.08)"},bt={surface:"#1B1A17",text:"#F3F0EA",text2:"#BFB8AC",line:"#34312C",bubble:"#24221F",lineStrong:"#8A8378",danger:"#F26B8A",info:"#7AA7FF",infoSoft:"#142039",focus:"#7AA7FF",shadow2:"0 8px 24px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.06)",shadow3:"0 24px 64px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08)"};function _t(t){return`--lc-surface:${t.surface};--lc-text:${t.text};--lc-text-2:${t.text2};--lc-line:${t.line};--lc-bubble-in:${t.bubble};--lc-focus:${t.focus};--lc-shadow-2:${t.shadow2};--lc-shadow-3:${t.shadow3};--lc-line-strong:${t.lineStrong};--lc-danger:${t.danger};--lc-info:${t.info};--lc-info-soft:${t.infoSoft};`}const ft=`\n:host{all:initial}\n.lc{${_t(At)}color-scheme:light;position:fixed;bottom:calc(20px + env(safe-area-inset-bottom,0px));right:calc(20px + env(safe-area-inset-right,0px));display:flex;flex-direction:column;align-items:flex-end;gap:12px;font:400 15px/22px "Atkinson Hyperlegible Next","Atkinson Hyperlegible",system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--lc-text);-webkit-font-smoothing:antialiased}\n.lc[data-theme="dark"]{${_t(bt)}color-scheme:dark}\n.lc[data-pos="bottom-left"]{right:auto;left:calc(20px + env(safe-area-inset-left,0px));align-items:flex-start}\n.lc *,.lc *::before,.lc *::after{box-sizing:border-box}\n:where(.lc) button{font:inherit;color:inherit;cursor:pointer}\n.lc :focus-visible{outline:3px solid var(--lc-focus);outline-offset:2px}\n.lc-btn{position:relative;width:60px;height:60px;border:0;padding:0;border-radius:20px 20px 5px 20px;background:var(--lc-brand);color:var(--lc-on-brand);display:grid;place-items:center;box-shadow:var(--lc-shadow-3);transition:transform .15s ease}\n.lc[data-pos="bottom-left"] .lc-btn{border-radius:20px 20px 20px 5px}\n.lc-btn:hover{transform:translateY(-2px)}\n.lc-btn:active{transform:translateY(0) scale(.97)}\n.lc-btn svg{width:26px;height:26px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}\n.lc-btn .lc-ic-close{display:none}\n.lc[data-open="true"] .lc-btn .lc-ic-chat{display:none}\n.lc[data-open="true"] .lc-btn .lc-ic-close{display:block}\n.lc-count{position:absolute;top:-6px;right:-6px;min-width:22px;height:22px;padding:0 6px;border-radius:9999px;background:var(--lc-accent);color:var(--lc-on-accent);box-shadow:0 0 0 2px var(--lc-surface);font:700 11px/22px "JetBrains Mono",ui-monospace,"SF Mono",Menlo,monospace;text-align:center;font-variant-numeric:tabular-nums}\n.lc[data-pos="bottom-left"] .lc-count{right:auto;left:-6px}\n.lc-count[hidden],.lc[data-open="true"] .lc-count{display:none}\n.lc-greet{display:flex;align-items:flex-start;gap:4px;max-width:260px;padding:8px 6px 8px 12px;border-radius:20px 20px 4px 20px;background:var(--lc-bubble-in);color:var(--lc-text);box-shadow:var(--lc-shadow-2);animation:lc-in .2s ease}\n.lc[data-pos="bottom-left"] .lc-greet{border-radius:20px 20px 20px 4px}\n.lc-greet[hidden],.lc[data-open="true"] .lc-greet{display:none}\n.lc-greet__text{flex:1;border:0;background:none;padding:0;text-align:start;font-size:15px;line-height:22px}\n.lc-x{flex:none;width:28px;height:28px;border:0;border-radius:9999px;background:none;display:grid;place-items:center;color:var(--lc-text-2)}\n.lc-x:hover{background:var(--lc-line)}\n.lc-x svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round}\n.lc-panel{width:var(--lc-w);height:var(--lc-h);max-width:calc(100vw - 40px);max-height:calc(100vh - 120px);display:flex;flex-direction:column;border-radius:20px;overflow:hidden;background:var(--lc-surface);box-shadow:var(--lc-shadow-3);transform-origin:bottom right;transition:opacity .16s ease,transform .16s ease,visibility 0s linear .16s}\n.lc[data-pos="bottom-left"] .lc-panel{transform-origin:bottom left}\n.lc[data-open="false"] .lc-panel{visibility:hidden;opacity:0;transform:translateY(8px) scale(.98);pointer-events:none;position:absolute;bottom:72px}\n.lc[data-pos="bottom-right"][data-open="false"] .lc-panel{right:0}\n.lc[data-pos="bottom-left"][data-open="false"] .lc-panel{left:0}\n.lc[data-open="true"] .lc-panel{visibility:visible;opacity:1;transform:none;transition-delay:0s}\n.lc-head{flex:none;display:flex;align-items:center;gap:10px;padding:12px 10px 12px 14px;background:var(--lc-brand);color:var(--lc-on-brand)}\n.lc-logo{flex:none;width:32px;height:32px;border-radius:14px 14px 14px 4px;background:var(--lc-surface);color:var(--lc-brand-text);display:grid;place-items:center;overflow:hidden;font:800 11px/1 "Schibsted Grotesk","Helvetica Neue",Arial,sans-serif}\n.lc-logo img{width:100%;height:100%;object-fit:cover}\n.lc-head__t{flex:1;min-width:0;display:grid}\n.lc-head__t b{font:700 15px/20px "Schibsted Grotesk","Helvetica Neue",Arial,sans-serif;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n.lc-head__t span{font-size:12px;line-height:16px;opacity:.9}\n.lc-head .lc-x{width:40px;height:40px;color:inherit}\n.lc-head .lc-x:hover{background:rgba(127,127,127,.22)}\n.lc-head .lc-x:focus-visible{outline-color:currentColor;outline-offset:-3px}\n.lc-head__t span[hidden]{display:none}\n.lc-body{position:relative;flex:1;min-height:0;background:var(--lc-surface)}\n.lc-body iframe{display:block;width:100%;height:100%;border:0}\n.lc-gate{position:absolute;inset:0;overflow:auto;padding:16px;display:grid;align-content:start;gap:12px;background:var(--lc-surface)}\n.lc-gate[hidden]{display:none}\n.lc-gate p{margin:0}\n.lc-form{display:grid;gap:12px}\n.lc-f{display:grid;gap:4px}\n.lc-f label{font-size:13px;line-height:18px;font-weight:600;color:var(--lc-text-2)}\n.lc-in{width:100%;min-height:44px;padding:10px 12px;border:1px solid var(--lc-line-strong);border-radius:10px;background:var(--lc-surface);color:var(--lc-text);font:inherit}\ntextarea.lc-in{min-height:96px;resize:vertical}\n.lc-in[aria-invalid="true"]{border-color:var(--lc-danger);box-shadow:0 0 0 1px var(--lc-danger)}\n.lc-err{font-size:13px;line-height:18px;color:var(--lc-danger)}\n.lc-err:empty{display:none}\n.lc-go{min-height:48px;border:0;border-radius:10px;padding:0 16px;background:var(--lc-brand);color:var(--lc-on-brand);font-weight:700}\n.lc-go[disabled]{opacity:.6;cursor:progress}\n.lc-link{border:0;background:none;padding:10px 0;min-height:44px;color:var(--lc-brand-text);font-weight:600;text-decoration:underline;text-align:start}\n.lc-note{font-size:12px;line-height:16px;color:var(--lc-text-2)}\n.lc-ban{display:flex;gap:10px;align-items:flex-start;padding:12px;border-radius:10px;background:var(--lc-info-soft);color:var(--lc-text)}\n.lc-ban svg{flex:none;width:20px;height:20px;fill:none;stroke:var(--lc-info);stroke-width:2;stroke-linecap:round}\n@media (max-width:640px){\n.lc{bottom:calc(16px + env(safe-area-inset-bottom,0px));right:calc(16px + env(safe-area-inset-right,0px))}\n.lc[data-pos="bottom-left"]{left:calc(16px + env(safe-area-inset-left,0px))}\n.lc[data-open="true"]{inset:0;gap:0}\n.lc[data-open="true"] .lc-btn{display:none}\n.lc-panel{max-width:none;max-height:none}\n.lc[data-open="true"] .lc-panel{position:fixed;inset:0;width:100vw;height:100vh;height:100dvh;border-radius:0;padding-top:env(safe-area-inset-top,0px)}\n.lc[data-open="false"] .lc-panel{position:fixed;inset:0;width:100vw;height:100vh;bottom:auto;border-radius:0}\n.lc-head{min-height:56px}\n}\n@media (prefers-reduced-motion:reduce){.lc *{transition:none!important;animation:none!important}}\n@keyframes lc-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}\n`,Rt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>';function xt(t,e,n){const r=document.createElement(t);return e&&(r.className=e),n&&(r.textContent=n),r}let Pt=0;function It(){try{return"undefined"!=typeof window?window.localStorage:null}catch(t){return null}}class wt{constructor(t){var e;this.cfg=t,this.preChat=null,this.preChatValues=null,this.hours=null,this.awayDismissed=!1,this.awaySent=!1,this.gateKind="",this.linkAccent=null,this.iframe=null,this.pendingSrc=null,this.opened=!1,this.unread=0,this.frameMode=null,this.linkBrand=null,this.greetTimer=null,this.mql=null,this.prevOverflow=null,this.onMql=()=>this.applyTheme(),this.onResize=()=>this.syncModal();const n="lc-panel-"+ ++Pt;this.pid=n,this.mode=t.theme||"system",this.explicitBrand=st(t.brandColor)?rt(t.brandColor):null,this.explicitAccent=rt(t.secondaryColor),this.preChat=vt(t.preChat),this.hours=t.businessHours||null,this.host=document.createElement("div"),this.host.setAttribute("data-livechatta-launcher",""),this.root=this.host.attachShadow({mode:"open"});const r=document.createElement("style");r.textContent=ft,this.root.appendChild(r);const s=t.title||"Chat";this.wrap=document.createElement("div"),this.wrap.className="lc",this.wrap.setAttribute("data-pos","bottom-left"===t.position?"bottom-left":"bottom-right"),this.wrap.setAttribute("data-open","false"),this.wrap.style.zIndex=String(null!==(e=t.zIndex)&&void 0!==e?e:2147483e3),this.wrap.style.setProperty("--lc-w",t.width||"380px"),this.wrap.style.setProperty("--lc-h",t.height||"640px"),this.panel=document.createElement("div"),this.panel.className="lc-panel",this.panel.id=n,this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label",s),this.panel.setAttribute("aria-modal","false"),this.panel.setAttribute("inert","");const o=document.createElement("div");o.className="lc-head";const a=document.createElement("span");if(a.className="lc-logo",a.setAttribute("aria-hidden","true"),t.logoUrl&&/^https:\/\//.test(t.logoUrl)){const e=document.createElement("img");e.src=t.logoUrl,e.alt="",a.appendChild(e)}else a.textContent=function(t){var e,n;const r=t.trim().split(/\s+/).filter(Boolean);return(((null===(e=r[0])||void 0===e?void 0:e[0])||"L")+((null===(n=r[1])||void 0===n?void 0:n[0])||"")).toUpperCase()}(s);const i=document.createElement("div");i.className="lc-head__t";const h=document.createElement("b");h.textContent=s,this.sub=xt("span"),i.append(h,this.sub),this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="lc-x",this.closeBtn.setAttribute("aria-label","Close chat"),this.closeBtn.innerHTML=Rt,this.closeBtn.addEventListener("click",()=>this.close()),o.append(a,i,this.closeBtn),this.body=document.createElement("div"),this.body.className="lc-body",this.gate=xt("div","lc-gate"),this.gate.hidden=!0,this.body.appendChild(this.gate),this.panel.append(o,this.body),this.greet=document.createElement("div"),this.greet.className="lc-greet",this.greet.hidden=!0;const c=document.createElement("button");c.type="button",c.className="lc-greet__text",c.textContent=t.greeting||"",c.addEventListener("click",()=>this.open());const l=document.createElement("button");l.type="button",l.className="lc-x",l.setAttribute("aria-label","Dismiss greeting"),l.innerHTML=Rt,l.addEventListener("click",()=>this.dismissGreeting(!0)),this.greet.append(c,l),this.greet.setAttribute("role","status"),this.btn=document.createElement("button"),this.btn.type="button",this.btn.className="lc-btn",this.btn.setAttribute("aria-controls",n),this.btn.setAttribute("aria-expanded","false"),this.btn.innerHTML='<svg class="lc-ic-chat" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 5h14v10H9l-4 4z"/></svg><svg class="lc-ic-close" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>',this.count=document.createElement("span"),this.count.className="lc-count",this.count.hidden=!0,this.count.setAttribute("aria-hidden","true"),this.btn.appendChild(this.count),this.btn.addEventListener("click",()=>this.toggle()),this.wrap.append(this.panel,this.greet,this.btn),this.wrap.addEventListener("keydown",t=>{"Escape"===t.key&&(this.opened?(t.stopPropagation(),this.close()):this.greet.hidden||this.dismissGreeting(!0))}),this.root.appendChild(this.wrap),this.updateLabel(),this.applyBrand(),this.applyTheme(),this.renderGate()}mount(t,e){var n,r;this.iframe=t,this.pendingSrc=e||null,this.body.insertBefore(t,this.gate),this.syncFrameInert(),document.body.appendChild(this.host),"function"==typeof window.matchMedia&&(this.mql=window.matchMedia("(prefers-color-scheme: dark)"),this.mql.addEventListener?this.mql.addEventListener("change",this.onMql):null===(r=(n=this.mql).addListener)||void 0===r||r.call(n,this.onMql)),window.addEventListener("resize",this.onResize),this.applyTheme(),this.cfg.autoOpen?this.open(!1):this.scheduleGreeting()}open(t=!0){var e,n;this.opened||(this.pendingSrc&&this.iframe&&(this.iframe.src=this.pendingSrc,this.pendingSrc=null),this.opened=!0,this.wrap.setAttribute("data-open","true"),this.panel.removeAttribute("inert"),this.btn.setAttribute("aria-expanded","true"),this.dismissGreeting(!0),this.updateLabel(),this.syncModal(),this.renderGate(),t&&(this.firstGateControl()||this.closeBtn).focus(),null===(n=(e=this.cfg).onOpenChange)||void 0===n||n.call(e,!0))}close(){var t,e;this.opened&&(this.opened=!1,this.wrap.setAttribute("data-open","false"),this.panel.setAttribute("inert",""),this.btn.setAttribute("aria-expanded","false"),this.updateLabel(),this.syncModal(),this.btn.focus(),null===(e=(t=this.cfg).onOpenChange)||void 0===e||e.call(t,!1))}toggle(){this.opened?this.close():this.open()}isOpen(){return this.opened}setUnread(t){const e="number"==typeof t?t:Number(null==t?void 0:t.count);this.unread=Number.isFinite(e)&&e>0?Math.floor(e):0,this.count.hidden=0===this.unread,this.count.textContent=this.unread>99?"99+":String(this.unread),this.updateLabel()}setLinkBrand(t){this.linkBrand=st(t)?rt(t):null,this.applyBrand()}setLinkSecondary(t){this.linkAccent=rt(t),this.applyBrand()}setWidgetConfig(t){void 0===this.cfg.preChat&&t.preChat&&(this.preChat=vt(t.preChat)),!this.cfg.businessHours&&t.businessHours&&(this.hours=t.businessHours),this.renderGate()}getGate(){return this.gateKind}setBrand(t){this.explicitBrand=st(t)?rt(t):null,this.applyBrand()}setTheme(t){this.mode=t,this.frameMode=null,this.applyTheme()}setFrameMode(t){this.frameMode="dark"===t||"light"===t?t:null,this.applyTheme()}getEffectiveMode(){var t;return this.frameMode?this.frameMode:"system"!==this.mode?this.mode:(null===(t=this.mql)||void 0===t?void 0:t.matches)?"dark":"light"}destroy(){var t,e,n,r;this.greetTimer&&clearTimeout(this.greetTimer),(null===(t=this.mql)||void 0===t?void 0:t.removeEventListener)?this.mql.removeEventListener("change",this.onMql):null===(n=null===(e=this.mql)||void 0===e?void 0:e.removeListener)||void 0===n||n.call(e,this.onMql),window.removeEventListener("resize",this.onResize),this.opened&&(this.opened=!1,this.syncModal()),null===(r=this.host.parentNode)||void 0===r||r.removeChild(this.host),this.iframe=null}brand(){return this.explicitBrand||this.linkBrand||Z}applyBrand(){const t=this.brand();this.wrap.style.setProperty("--lc-brand",t),this.wrap.style.setProperty("--lc-on-brand",it(t));const e=this.explicitAccent||this.linkAccent||t;this.wrap.style.setProperty("--lc-accent",e),this.wrap.style.setProperty("--lc-on-accent",it(e)),this.applyBrandText()}applyBrandText(){const t="dark"===this.getEffectiveMode()?bt.surface:At.surface;this.wrap.style.setProperty("--lc-brand-text",ht(this.brand(),t))}applyTheme(){this.wrap.setAttribute("data-theme",this.getEffectiveMode()),this.applyBrandText()}updateLabel(){const t=this.cfg.launcherLabel||"Open chat",e=this.opened?"Close chat":this.unread?`${t}, ${this.unread} unread`:t;this.btn.setAttribute("aria-label",e)}greetingKey(){return`livechatta:greeting-dismissed:${this.cfg.storageKey}`}scheduleGreeting(){var t,e;const n=this.cfg.greeting;if(!n)return;try{if((null===(t=It())||void 0===t?void 0:t.getItem(this.greetingKey()))===n)return}catch(t){}const r=Math.max(0,null!==(e=this.cfg.greetingDelay)&&void 0!==e?e:1e4);this.greetTimer=setTimeout(()=>{this.opened||(this.greet.hidden=!1)},r)}dismissGreeting(t){var e;this.greetTimer&&(clearTimeout(this.greetTimer),this.greetTimer=null);const n=!this.greet.hidden;if(this.greet.hidden=!0,t&&this.cfg.greeting)try{null===(e=It())||void 0===e||e.setItem(this.greetingKey(),this.cfg.greeting)}catch(t){}n&&!this.opened&&this.root.activeElement&&this.btn.focus()}preChatKey(){return`livechatta:prechat-done:${this.cfg.storageKey}`}preChatDone(){var t;if(this.preChatValues)return!0;try{return"1"===(null===(t=It())||void 0===t?void 0:t.getItem(this.preChatKey()))}catch(t){return!1}}renderGate(){var t,e;const n=this.hours&&!this.awayDismissed?gt(this.hours,null===(e=(t=this.cfg).now)||void 0===e?void 0:e.call(t)):null,r=this.preChat&&!this.preChatDone()?"prechat":n?"away":"";this.sub.textContent=n?"Away"+(n.backAt?` · back ${n.backAt}`:""):this.cfg.subtitle||"",this.sub.hidden=!this.sub.textContent,r===this.gateKind&&"away"!==r||"away"===r&&"away"===this.gateKind&&this.gate.contains(this.root.activeElement)||(this.gateKind=r,this.gate.textContent="",this.gate.hidden=!r,"prechat"===r?this.buildPreChat():"away"===r&&this.buildAway(n),this.syncFrameInert())}syncFrameInert(){this.iframe&&(this.gateKind?this.iframe.setAttribute("inert",""):this.iframe.removeAttribute("inert"))}firstGateControl(){return this.gateKind?this.gate.querySelector("input,select,textarea,button"):null}uncover(){this.renderGate(),this.opened&&(this.firstGateControl()||this.closeBtn).focus()}field(t,e,n,r=!0){const s=xt("div","lc-f"),o=xt("label","",e);o.htmlFor=t,n.id=t,n.classList.add("lc-in");const a=xt("p","lc-err");return a.id=`${t}-err`,n.setAttribute("aria-describedby",a.id),s.append(o,n,a),r&&this.gate.appendChild(s),a}buildPreChat(){const t=this.preChat,e=xt("form","lc-form");e.noValidate=!0,e.setAttribute("aria-label","Before we start"),t.intro&&e.appendChild(xt("p","",t.intro));const n={},r={};for(const s of t.fields){let t;if("select"===s.type){const e=xt("select");e.appendChild(new Option("Choose…","")),(s.options||[]).forEach(t=>e.appendChild(new Option(t,t))),t=e}else if("textarea"===s.type)t=xt("textarea");else{const e=xt("input");e.type=s.type||"text","name"===s.name&&(e.autocomplete="name"),"email"===s.type&&(e.autocomplete="email"),t=e}t.name=s.name,s.required&&(t.required=!0),!s.placeholder||t instanceof HTMLSelectElement||(t.placeholder=s.placeholder),r[s.name]=t,n[s.name]=this.field(`${this.pid}-${s.name}`,s.label,t,!1),e.appendChild(n[s.name].parentElement)}const s=xt("p","lc-err");s.setAttribute("role","alert");const o=xt("button","lc-go",t.submitLabel);o.type="submit",e.append(s,o),t.note&&e.appendChild(xt("p","lc-note",t.note)),e.addEventListener("submit",async e=>{var a,i,h,c,l;e.preventDefault();const u={};for(const t of Object.keys(r))u[t]=r[t].value.trim();const p=Ot(t.fields,u);s.textContent="";for(const t of Object.keys(r))n[t].textContent=p[t]||"",r[t].setAttribute("aria-invalid",p[t]?"true":"false");const d=Object.keys(r).find(t=>p[t]);if(d)return r[d].focus();o.disabled=!0,o.setAttribute("aria-busy","true");try{await(null===(i=(a=this.cfg).onPreChatSubmit)||void 0===i?void 0:i.call(a,u))}catch(t){return o.disabled=!1,o.removeAttribute("aria-busy"),void(s.textContent="Couldn't start the chat. Check your connection and try again.")}this.preChatValues=u;try{null===(h=It())||void 0===h||h.setItem(this.preChatKey(),"1")}catch(t){}null===(l=(c=this.cfg).onPreChatComplete)||void 0===l||l.call(c,u),this.uncover()}),this.gate.appendChild(e)}buildAway(t){const e=xt("div","lc-ban");e.setAttribute("role","status"),e.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>';const n=xt("p");n.append(xt("b","","We're away"),document.createTextNode(t.backAt?` · back ${t.backAt}.`:".")),t.message&&n.append(document.createTextNode(` ${t.message}`)),e.appendChild(n),this.gate.appendChild(e);const r=xt("button","lc-link","Continue to chat");r.type="button",r.addEventListener("click",()=>{this.awayDismissed=!0,this.uncover()});const s=this.cfg.onAwayMessage;if(!s||this.awaySent)return this.awaySent&&this.gate.appendChild(xt("p","","Thanks, your message is with the team. We'll reply by email.")),void this.gate.appendChild(r);const o=xt("textarea"),a=this.field(`${this.pid}-away`,"Your message",o),i=xt("button","lc-go","Send");i.type="button",i.addEventListener("click",async()=>{var t;const e=o.value.trim();if(a.textContent=e?"":"Write a message first",o.setAttribute("aria-invalid",e?"false":"true"),!e)return o.focus();i.disabled=!0,i.setAttribute("aria-busy","true");try{await s(e,this.preChatValues)}catch(t){return i.disabled=!1,i.removeAttribute("aria-busy"),void(a.textContent="Couldn't send. Try again.")}this.awaySent=!0,this.gateKind="",this.renderGate(),null===(t=this.gate.querySelector(".lc-link"))||void 0===t||t.focus()}),this.gate.append(i,r)}syncModal(){const t=this.opened&&"undefined"!=typeof window&&window.innerWidth<=640;this.panel.setAttribute("aria-modal",t?"true":"false");const e=document.documentElement;t&&null===this.prevOverflow?(this.prevOverflow=e.style.overflow,e.style.overflow="hidden"):t||null===this.prevOverflow||(e.style.overflow=this.prevOverflow,this.prevOverflow=null)}}const Nt="0123456789abcdef";async function Lt(t,e){return"undefined"!=typeof crypto&&void 0!==crypto.subtle?async function(t,e){const n=await crypto.subtle.importKey("raw",(new TextEncoder).encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return function(t){const e=new Uint8Array(t);let n="";for(let t=0;t<e.length;t++){const r=e[t];n+=Nt[r>>>4]+Nt[15&r]}return n}(await crypto.subtle.sign("HMAC",n,(new TextEncoder).encode(t)))}(t,e):"undefined"!=typeof window||"undefined"==typeof globalThis||void 0===globalThis.process?function(t,e){const n=new TextEncoder,r=n.encode(e),s=n.encode(t),o=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function a(t,e){return e>>>t|e<<32-t}function i(t){let e=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,h=2600822924,c=528734635,l=1541459225;const u=t.length,p=8*u,d=u+9+63&-64,E=new Uint8Array(d);E.set(t),E[u]=128;const m=new DataView(E.buffer);m.setUint32(d-4,p,!1);const y=new Uint32Array(64);for(let t=0;t<d;t+=64){for(let e=0;e<16;e++)y[e]=m.getUint32(t+4*e,!1);for(let t=16;t<64;t++){const e=a(7,y[t-15])^a(18,y[t-15])^y[t-15]>>>3,n=a(17,y[t-2])^a(19,y[t-2])^y[t-2]>>>10;y[t]=y[t-16]+e+y[t-7]+n|0}let u=e,p=n,d=r,E=s,T=i,g=h,C=c,S=l;for(let t=0;t<64;t++){const e=S+(a(6,T)^a(11,T)^a(25,T))+(T&g^~T&C)+o[t]+y[t]|0,n=u&p^u&d^p&d;S=C,C=g,g=T,T=E+e|0,E=d,d=p,p=u,u=e+((a(2,u)^a(13,u)^a(22,u))+n|0)|0}e=e+u|0,n=n+p|0,r=r+d|0,s=s+E|0,i=i+T|0,h=h+g|0,c=c+C|0,l=l+S|0}const T=new Uint8Array(32),g=new DataView(T.buffer);return g.setUint32(0,e,!1),g.setUint32(4,n,!1),g.setUint32(8,r,!1),g.setUint32(12,s,!1),g.setUint32(16,i,!1),g.setUint32(20,h,!1),g.setUint32(24,c,!1),g.setUint32(28,l,!1),T}const h=64;let c=r;c.length>h&&(c=i(c));const l=new Uint8Array(h);l.set(c);const u=new Uint8Array(h),p=new Uint8Array(h);for(let t=0;t<h;t++)u[t]=54^l[t],p[t]=92^l[t];const d=new Uint8Array(h+s.length);d.set(u),d.set(s,h);const E=i(d),m=new Uint8Array(96);m.set(p),m.set(E,h);const y=i(m);return Array.from(y).map(t=>t.toString(16).padStart(2,"0")).join("")}(t,e):async function(t,e){const{createHmac:n}=await(import("crypto"));return n("sha256",e).update(t).digest("hex")}(t,e)}async function Dt(t){if(!t.linkCode)throw new Error("LiveChatta.signAppRequest: linkCode is required");if(!t.platform)throw new Error("LiveChatta.signAppRequest: platform is required");if(!t.version)throw new Error("LiveChatta.signAppRequest: version is required");if(!t.apiKey)throw new Error("LiveChatta.signAppRequest: apiKey is required");const e=`${t.linkCode}:${t.platform}:${t.version}`,n=await Lt(e,t.apiKey),r=`CHATTA-APP:${t.platform}:${t.version}:${n}`;return{header:r,querySig:encodeURIComponent(r),signature:n,platform:t.platform,version:t.version}}const kt="microphone *; camera *; display-capture *; clipboard-write *; autoplay *; fullscreen *; picture-in-picture *; clipboard-read *; encrypted-media *; screen-wake-lock *; web-share *; geolocation *; gyroscope *; accelerometer *; magnetometer *; speaker-selection *",Mt="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-presentation allow-downloads allow-orientation-lock";function Ht(t){const e={};for(const n of Object.keys(t))void 0!==t[n]&&null!==t[n]&&(e[n]=t[n]);return e}class Ut{constructor(t,e,n){this.config=t,this.tokenManager=e,this.loadWidgetConfig=n,this.iframe=null,this.embedConfig=null,this.options=null,this.launcher=null,this.unsubs=[],this.bridge=new z({allowedOrigin:this.config.baseUrl})}async mount(t){this.options={...t},this.embedConfig=new lt(t);const e=this.embedConfig;let n=null;if(!e.floating)if("string"==typeof e.container){const t=document.querySelector(e.container);if(!t)throw new Error(`LiveChatta UI: container "${e.container}" not found`);n=t}else n=e.container;const r=await this.buildEmbedUrl();return this.iframe=document.createElement("iframe"),this.iframe.setAttribute("allow",kt),this.iframe.setAttribute("sandbox",Mt),this.iframe.setAttribute("allowfullscreen",""),this.iframe.style.border="none",j(this.iframe),e.floating?this.mountFloating(this.iframe,r,t):(this.iframe.src=r,this.iframe.style.width=e.width,this.iframe.style.height=e.height,this.iframe.style.borderRadius="12px",this.iframe.setAttribute("loading","lazy"),this.iframe.title="LiveChatta workspace",n.innerHTML="",n.appendChild(this.iframe)),this.bridge.attach(this.iframe),this.iframe}mountFloating(t,e,n){const r=this.embedConfig;t.title=`${n.title||"LiveChatta"} chat`,this.launcher=new wt({storageKey:this.config.linkCode,position:r.position,theme:r.theme,brandColor:r.hasExplicitPrimary?`#${r.primaryColor}`:void 0,title:n.title,subtitle:n.subtitle,logoUrl:n.logoUrl,launcherLabel:n.launcherLabel,greeting:n.greeting,greetingDelay:n.greetingDelay,zIndex:n.zIndex,autoOpen:n.autoOpen,width:r.width,height:r.height,onOpenChange:n.onOpenChange,secondaryColor:r.hasExplicitSecondary?`#${r.secondaryColor}`:void 0,preChat:n.preChat,onPreChatSubmit:n.onPreChatSubmit,onPreChatComplete:e=>{var n;null===(n=t.contentWindow)||void 0===n||n.postMessage({type:B.preChat,payload:e},this.config.baseUrl)},businessHours:n.businessHours,onAwayMessage:n.onAwayMessage}),r.preload?(t.src=e,this.launcher.mount(t)):this.launcher.mount(t,e);const s=this.launcher,o=this.config.baseUrl,a=e=>{e.source!==t.contentWindow||e.origin!==o&&"null"!==e.origin||Y(s,e.data)};window.addEventListener("message",a),this.unsubs.push(()=>window.removeEventListener("message",a)),!1!==n.linkConfig&&this.loadWidgetConfig&&this.applyLinkWidget(s)}applyLinkWidget(t){this.loadWidgetConfig().then(e=>{e&&this.launcher===t&&t.setWidgetConfig({preChat:e.preChat,businessHours:e.businessHours})}).catch(()=>{})}unmount(){var t,e;this.unsubs.forEach(t=>t()),this.unsubs=[],this.bridge.detach(),null===(t=this.launcher)||void 0===t||t.destroy(),this.launcher=null,(null===(e=this.iframe)||void 0===e?void 0:e.parentNode)&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null,this.embedConfig=null,this.options=null}getIframe(){return this.iframe}getLauncher(){return this.launcher}open(){var t;null===(t=this.launcher)||void 0===t||t.open()}close(){var t;null===(t=this.launcher)||void 0===t||t.close()}toggle(){var t;null===(t=this.launcher)||void 0===t||t.toggle()}isOpen(){var t,e;return null!==(e=null===(t=this.launcher)||void 0===t?void 0:t.isOpen())&&void 0!==e&&e}setUnread(t){var e;null===(e=this.launcher)||void 0===e||e.setUnread(t)}async updateTheme(t){if(!this.iframe||!this.embedConfig||!this.options)return;this.options={...this.options,...Ht(t)};const e=new lt(this.options);this.embedConfig=e,this.launcher&&(t.primaryColor&&this.launcher.setBrand(t.primaryColor),t.theme&&this.launcher.setTheme(e.theme));const n=this.iframe.contentWindow;n?(n.postMessage(e.toPostMessagePayload(),this.config.baseUrl),t.theme&&n.postMessage({type:"CHATTA_APP:theme",mode:ct(t.theme,"system")},this.config.baseUrl)):this.iframe.src=await this.buildEmbedUrl()}async buildEmbedUrl(){var t,e,n;const r=await this.tokenManager.getToken(),s=(null===(t=this.embedConfig)||void 0===t?void 0:t.toQueryParams())||"",o=i(),a=(null===(e=this.embedConfig)||void 0===e?void 0:e.embedMode)||"auto";if(!("app"===a||"auto"===a&&o.isAppShell))return`${this.config.embedUrl}?token=${encodeURIComponent(r)}${s?`&${s}`:""}`;const h=await Dt({linkCode:this.config.linkCode,platform:"web"===o.platform?"web":o.platform,version:(null===(n=this.embedConfig)||void 0===n?void 0:n.appVersion)||"1.0.0",apiKey:this.config.apiKey});return`${this.config.appEmbedUrl}?token=${encodeURIComponent(r)}&_app_sig=${h.querySig}`+(s?`&${s}`:"")}}class Gt{constructor(){this.config=null,this.tokenManager=null,this.eventBus=null,this.socketTransport=null,this.socketAPI=null,this.httpTransport=null,this.httpAPI=null,this.embedUI=null,this.permissionsApi=new h,this.initialized=!1}init(t){this.config=new e(t),this.eventBus=new s,this.tokenManager=new r(this.config.apiKey,this.config.linkCode,this.config.chatUsername,this.config.publicKey),this.config.enableSocket&&(this.socketTransport=new x(this.config,this.tokenManager,this.eventBus),this.socketAPI=new I(this.socketTransport,this.eventBus)),this.config.enableHttp&&(this.httpTransport=new R(this.config,this.tokenManager,this.eventBus),this.httpAPI=new W(this.httpTransport));const n=this.config.linkCode;return this.embedUI=new Ut(this.config,this.tokenManager,this.httpAPI?()=>this.httpAPI.getLinkWorkspaceInfo(n).then(t=>null==t?void 0:t.widget):void 0),this.initialized=!0,this.config.debug&&console.log("[LiveChatta] SDK initialized",{linkCode:this.config.linkCode,socket:this.config.enableSocket,http:this.config.enableHttp}),this}async connect(){if(this.assertInitialized(),!this.socketTransport)throw new Error("LiveChatta: Socket transport is not enabled");await this.socketTransport.connect()}disconnect(){var t;null===(t=this.socketTransport)||void 0===t||t.disconnect()}sock(){if(this.assertInitialized(),!this.socketAPI)throw new Error("LiveChatta: Socket transport is not enabled. Set enableSocket: true in init().");return this.socketAPI}api(){if(this.assertInitialized(),!this.httpAPI)throw new Error("LiveChatta: HTTP transport is not enabled. Set enableHttp: true in init().");return this.httpAPI}async ui(t){if(this.assertInitialized(),!this.embedUI)throw new Error("LiveChatta: Embed UI not available");if(!this.config.chatUsername)throw new Error("LiveChatta: chatUsername is required for embed mode — each embed must identify the individual user. Pass chatUsername in init().");return this.embedUI.mount(t)}unmountUI(){var t;null===(t=this.embedUI)||void 0===t||t.unmount()}async updateTheme(t){var e;await(null===(e=this.embedUI)||void 0===e?void 0:e.updateTheme(t))}open(){var t;null===(t=this.embedUI)||void 0===t||t.open()}close(){var t;null===(t=this.embedUI)||void 0===t||t.close()}toggle(){var t;null===(t=this.embedUI)||void 0===t||t.toggle()}isOpen(){var t,e;return null!==(e=null===(t=this.embedUI)||void 0===t?void 0:t.isOpen())&&void 0!==e&&e}setUnread(t){var e;null===(e=this.embedUI)||void 0===e||e.setUnread(t)}on(t,e){var n;return null===(n=this.eventBus)||void 0===n||n.on(t,e),this}off(t,e){var n;return null===(n=this.eventBus)||void 0===n||n.off(t,e),this}isInitialized(){return this.initialized}isConnected(){var t,e;return null!==(e=null===(t=this.socketTransport)||void 0===t?void 0:t.isConnected())&&void 0!==e&&e}getConnectionState(){var t,e;return null!==(e=null===(t=this.socketTransport)||void 0===t?void 0:t.getState())&&void 0!==e?e:exports.ConnectionState.DISCONNECTED}getConfig(){return this.config}signAppRequest(t){return this.assertInitialized(),Dt({linkCode:this.config.linkCode,apiKey:this.config.apiKey,platform:t.platform,version:t.version})}buildUserToken(t){this.assertInitialized();const e=(null==t?void 0:t.chatUsername)||this.config.chatUsername;if(!e)throw new Error("LiveChatta.buildUserToken: chatUsername is required");return n(this.config.publicKey,{apiKey:this.config.apiKey,linkCode:this.config.linkCode,chatUsername:e,...(null==t?void 0:t.conversationId)?{conversationId:t.conversationId}:{}})}get bridge(){var t,e;return null!==(e=null===(t=this.embedUI)||void 0===t?void 0:t.bridge)&&void 0!==e?e:null}get permissions(){return this.permissionsApi}get runtime(){return i()}destroy(){var t;this.disconnect(),this.unmountUI(),null===(t=this.eventBus)||void 0===t||t.removeAllListeners(),this.config=null,this.tokenManager=null,this.eventBus=null,this.socketTransport=null,this.socketAPI=null,this.httpTransport=null,this.httpAPI=null,this.embedUI=null,this.initialized=!1}assertInitialized(){if(!this.initialized||!this.config)throw new Error("LiveChatta: SDK not initialized. Call LiveChatta.init() first.")}}const $t=new Gt,Ft=/^(?:https:\/\/[^/\s]+|http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?)\/hooks\/in\/lhk_[A-Za-z0-9_-]{43}\/?$/,Wt={name:{name:"name",label:"Your name",type:"text"},email:{name:"email",label:"Email",type:"email"},phone:{name:"phone",label:"Phone",type:"tel"},topic:{name:"topic",label:"What do you need?",type:"text"}},qt="chatta-bridge-grants";class Bt{async load(){if("undefined"==typeof localStorage)return{};try{const t=localStorage.getItem(qt);return t?JSON.parse(t):{}}catch(t){return{}}}async save(t){if("undefined"!=typeof localStorage)try{localStorage.setItem(qt,JSON.stringify(t))}catch(t){}}}class Vt{async load(){try{const{Preferences:t}=await(import("@capacitor/preferences")),{value:e}=await t.get({key:qt});return e?JSON.parse(e):{}}catch(t){return{}}}async save(t){try{const{Preferences:e}=await(import("@capacitor/preferences"));await e.set({key:qt,value:JSON.stringify(t)})}catch(t){}}}class Kt{constructor(){this.grants={}}async load(){return{...this.grants}}async save(t){this.grants={...t}}}class jt{constructor(t){this.cache=null,this.backend=t||new Bt}static withCapacitor(){return new jt(new Vt)}static inMemory(){return new jt(new Kt)}async getAll(){return this.cache||(this.cache=await this.backend.load()),{...this.cache}}async get(t){return!0===(await this.getAll())[t]}async set(t,e){this.cache||(this.cache=await this.backend.load()),this.cache[t]=e,await this.backend.save(this.cache)}async clear(){this.cache={},await this.backend.save({})}}const Yt=new Set(["livechatta.com","staging.livechatta.com","app.livechatta.com"]);function zt(t){if(!t||"string"!=typeof t)return{kind:"unknown",raw:t};if(0===t.indexOf("chatta://")){const e=t.slice(9).split("?")[0].split("/").filter(Boolean);return"open"===e[0]&&e[1]?{kind:"open",linkCode:e[1],raw:t}:"chat"===e[0]&&e[1]?{kind:"chat",linkCode:e[1],conversationId:e[2],raw:t}:"reset"===e[0]&&e[1]?{kind:"reset",resetToken:e[1],raw:t}:{kind:"unknown",raw:t}}try{const e=new URL(t);if(!Yt.has(e.hostname))return{kind:"unknown",raw:t};const n=e.pathname.split("/").filter(Boolean);if("in"===n[0]&&n[1]){const r=n[1],s=e.searchParams.get("conv");return s?{kind:"chat",linkCode:r,conversationId:s,raw:t}:{kind:"open",linkCode:r,raw:t}}return{kind:"unknown",raw:t}}catch(e){return{kind:"unknown",raw:t}}}const Qt=Object.freeze({membersCanSend:!0,membersCanAddPeople:!1,membersCanStartCalls:!0,membersCanShareMedia:!0,membersCanPin:!0,membersCanManageWebhooks:!1,slowModeSeconds:0}),Xt={"ios-app":"iPhone app","android-app":"Android app","desktop-app":"Desktop app","mobile-web":"Mobile web",web:"Web",api:"API",bot:"Bot",automation:"Automation"},Jt="RATE_LIMITED",Zt="EDIT_WINDOW_CLOSED",te="HOP_INVITE_CANCEL",ee=["answered","declined","ended"],ne="Plan not found.",re="This plan is not available.",se="This plan is activated by the LiveChatta team. Contact support to switch to it.",oe="PLAN_NOT_FOUND",ae="PLAN_NOT_AVAILABLE",ie="PLAN_TEAM_ACTIVATED",he={[oe]:"not-found",[ae]:"not-available",[ie]:"team-activated"},ce=["TOO_SHORT","TOO_LONG","INVALID","RESERVED","TAKEN"],le=ce.map(t=>`LINK_CODE_${t}`),ue="isn't allowed from",pe=/\S@\S|@\s*[\w-]+(?:\s*(?:\.|\[dot\]|\(dot\))\s*[a-z]{2,})|\[at\]|\(at\)|\bat\s+[\w-]+\s+dot\s+[a-z]{2,}/i,de=/\b\d{4}-\d{2}-\d{2}\b/g,Ee=t=>"string"==typeof t&&t.trim()&&!function(t){const e=t.normalize("NFKC");return!!pe.test(e)||(e.replace(de," ").match(/\+?\d[\d\s().-]{5,}\d/g)||[]).some(t=>{const e=t.replace(/\D/g,"").length;return e>=7&&e<=15})}(t)?t.trim():"",me="livechatta:visitor-id",ye=/^[A-Za-z0-9_-]{8,64}$/;let Te=null;function ge(){const t=new Uint8Array(16),e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(null==e?void 0:e.getRandomValues)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(256*Math.random());return"v_"+Array.from(t,t=>t.toString(16).padStart(2,"0")).join("")}const Ce=[["send","Only admins can send messages in this conversation."],["shareMedia","Only admins can share media in this conversation."],["addPeople","Only admins can add people to this conversation."],["startCall","Only admins can start calls in this conversation."],["pin","Only admins can pin messages in this conversation."]],Se=/^Slow mode is on\. You can send one message every (\d+)s\.$/,ve="This conversation is locked. Only admins can send messages.";exports.ACCOUNT_EXISTS="ACCOUNT_EXISTS",exports.ADMIN_NO_ACCESS="ADMIN_NO_ACCESS",exports.API_KEY_MAX_ORIGINS=20,exports.API_KEY_ORIGIN_ERROR_MARKER=ue,exports.APPROVAL_OFF="APPROVAL_OFF",exports.AutoRefresh=class{constructor(t){this.cfg=t,this.timer=null,this.inflight=null}start(){var t;if(this.timer)return;const e=null!==(t=this.cfg.intervalMs)&&void 0!==t?t:6e4;this.timer=setInterval(()=>this.tick(),e),this.tick()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}shouldRefresh(){var t;const{tokenIssuedAt:e,tokenExpiresAt:n,refreshToken:r}=this.cfg.getTokens();if(!r||!n)return!1;const s=Date.now();if(s>=n)return!0;const o=e||n-36e5,a=n-o;return!(a<=0)&&s>=o+a*(1-(null!==(t=this.cfg.threshold)&&void 0!==t?t:.2))}async refreshNow(){if(this.inflight)return this.inflight;const{refreshToken:t}=this.cfg.getTokens();return t?(this.inflight=(async()=>{try{const e=await this.cfg.refresh(t);(null==e?void 0:e.accessToken)&&this.cfg.onRefreshed(e)}catch(t){}this.inflight=null})(),this.inflight):void 0}async tick(){this.shouldRefresh()&&await this.refreshNow()}static pushToBridge(t,e){t.send("restoreSession",e)}},exports.Bridge=z,exports.CALENDAR_ACCOUNT_MISMATCH="CALENDAR_ACCOUNT_MISMATCH",exports.CALENDAR_PROVIDERS=["google","microsoft"],exports.CALENDAR_SIGNIN_EXPIRED="CALENDAR_SIGNIN_EXPIRED",exports.CALL_CANCEL_PUSH_TYPE=te,exports.CALL_CANCEL_REASONS=ee,exports.CALL_DECLINE_TTL_SECONDS=120,exports.CALL_WAITING_TUNES=["drift","pebble","lantern","tide","meadow","off"],exports.CATCH_UP_MIN_UNREAD=8,exports.CHAT_LINK_SETTINGS_KEYS=["maxMembers","allowAttachments","allowVoiceMessages","allowVideoMessages","allowMemberInvite","welcomeMessage","defaultLayout","hideRunsOn","allowMemberStart","allowHopCalls","allowScreenshots","retentionDays","allowLiveFlex","editHistoryAdminsOnly","allowSharedDms","isolated","allowRecordingDownload"],exports.CONVERSATION_CATEGORY_MAX=40,exports.CONVERSATION_LOCKED_MESSAGE=ve,exports.CONVERSATION_MODES=["standard","broadcast","announcement","qa","voice","support"],exports.CONVERSATION_NOTE_MAX_LENGTH=2e3,exports.CSAT_COMMENT_MAX=500,exports.CSAT_DEFAULT_QUESTION="How would you rate the help you got today?",exports.CSAT_QUESTION_MAX=140,exports.CSAT_SATISFIED_MIN=4,exports.CSAT_SCALE=5,exports.CUSTOM_PLAN_REQUEST_FEATURES=["SSO","WHITE_LABEL","API_ACCESS","WEBINARS","AUTOMATION","ADVANCED_ANALYTICS","HOP_RECORDING","LONG_RETENTION","DEDICATED_SUPPORT"],exports.CUSTOM_PLAN_REQUEST_STATUSES=["NEW","CONTACTED","QUOTED","ASSIGNED","CLOSED"],exports.ChattaEvent={OnLoginSuccess:"onLoginSuccess",OnLogout:"onLogout",OnUnreadChange:"onUnreadChange",OnThemeLoaded:"onThemeLoaded",OpenExternal:"openExternal",OpenWorkspaceDrawer:"openWorkspaceDrawer",EnableScreenshotProtection:"enableScreenshotProtection",HopStartCall:"hopStartCall",HopEndCall:"hopEndCall",HopRecordingStarted:"hopRecordingStarted",HopRecordingStopped:"hopRecordingStopped",Notify:"notify",GrantUpdate:"grantUpdate",SetClipboard:"setClipboard",Share:"share",Haptic:"haptic",WindowControl:"windowControl",OnLinkUnavailable:"onLinkUnavailable",HopMuteChanged:"hopMuteChanged",RestoreSession:"restoreSession",RestoreGrants:"restoreGrants",HopInvite:"hopInvite",OnLinkNotFound:"onLinkNotFound",UpdateReady:"updateReady",ConnectionLost:"connectionLost",ShareFiles:"shareFiles",Init:"init",NativeCall:"nativeCall"},exports.Config=e,exports.DEFAULT_CONVERSATION_PERMISSIONS=Qt,exports.DELETE_FOR_EVERYONE_WINDOW_MS=1728e5,exports.DeepLinks=class{constructor(){this.listeners=new Set}on(t){return this.listeners.add(t),()=>this.listeners.delete(t)}dispatch(t){const e=zt(t);return this.listeners.forEach(t=>{try{t(e)}catch(t){}}),e}},exports.EDIT_WINDOW_CLOSED=Zt,exports.EDIT_WINDOW_CLOSED_MESSAGE="Messages can only be edited within 24 hours of sending.",exports.EMAIL_REQUIRED="EMAIL_REQUIRED",exports.EMBED_IFRAME_ALLOW="microphone; camera; display-capture; clipboard-write",exports.EMBED_MESSAGE_TYPES=B,exports.EMBED_OPTION_KEYS=["floating","position","autoOpen","greeting","greetingDelay","title","subtitle","launcherLabel","zIndex","preload","layout","onOpenChange","preChat","onPreChatSubmit","businessHours","onAwayMessage","linkConfig"],exports.EmbedConfig=lt,exports.EmbedUI=Ut,exports.EventBus=s,exports.GIFT_PAYOUT_MIN_MINOR=1e3,exports.GOOGLE_SIGN_IN_ERRORS=["not_configured","state","exchange","invalid_token","expired","email_unverified","no_account","linked_elsewhere","denied"],exports.GUEST_CODE_COOLDOWN="GUEST_CODE_COOLDOWN",exports.GUEST_CODE_EXPIRED="GUEST_CODE_EXPIRED",exports.GUEST_CODE_INVALID="GUEST_CODE_INVALID",exports.GUEST_CODE_LOCKED="GUEST_CODE_LOCKED",exports.GUEST_CODE_RATE_LIMITED="GUEST_CODE_RATE_LIMITED",exports.GrantStore=jt,exports.HANDLE_TAKEN="HANDLE_TAKEN",exports.HOP_PUSH_DECLINE_PATH="/api/v1/hops/push-decline",exports.HOP_RATE_LIMITED="RATE_LIMITED",exports.HOP_RATE_LIMITS={reaction:20,vote:20,hand:6,pollVote:10},exports.HOP_RATE_WINDOW_SECONDS=10,exports.HttpAPI=W,exports.IFRAME_ALLOW=kt,exports.IFRAME_SANDBOX=Mt,exports.INBOX_TOPIC_MAX=8,exports.INCOMING_CALL_ACTIONS=["ANSWER","DECLINE"],exports.INCOMING_CALL_ANDROID_CHANNEL="livechatta_calls",exports.INCOMING_CALL_CATEGORY="INCOMING_CALL",exports.INCOMING_CALL_RING_SECONDS=30,exports.INCOMING_WEBHOOK_LIMITS={nameMax:60,botNameMax:40,textMax:7500,iconUrlMax:500,activePerConversation:10,blocksMax:20,attachmentsMax:10,postsPerMinutePerUrl:150,bodyMaxBytes:65536,listPageSize:20},exports.INCOMING_WEBHOOK_URL_RE=Ft,exports.INTERNAL_NOTE_MAX_LENGTH=3e3,exports.INVITE_ONLY="INVITE_ONLY",exports.ISOLATION_ERRORS=["WORKSPACE_ISOLATED"],exports.JOIN_REQUEST_STATUSES=["pending","approved","denied"],exports.LAUNCHER_FULLSCREEN_MAX=640,exports.LEGACY_DEFAULT_BRAND=et,exports.LINK_CODE_ERROR_CODES=le,exports.LINK_CODE_MAX=40,exports.LINK_CODE_MIN=3,exports.LINK_CODE_REASONS=ce,exports.LINK_FULL="LINK_FULL",exports.LINK_MEMBER_BLOCKED="LINK_MEMBER_BLOCKED",exports.LINK_MEMBER_FILTERS=["all","active","blocked","invited"],exports.LINK_MODES=["standard","support","creator","school","community","tech","public","private","webinar"],exports.LINK_NOTIFY_LEVELS=["all","mentions","off"],exports.LINK_WHO_CAN_JOIN=["guest","members","invite"],exports.LIVEFLEX_ERRORS=["LIVEFLEX_OFF","LIVEFLEX_CODE_REQUIRED","LIVEFLEX_CODE_WRONG","WORKSPACE_ISOLATED","FEES_CHANGED"],exports.LIVEFLEX_PIN_ERRORS=["LIVEFLEX_PIN_SETUP","LIVEFLEX_PIN_REQUIRED","LIVEFLEX_PIN_WRONG","LIVEFLEX_PIN_LOCKED"],exports.Launcher=wt,exports.LiveChatta=$t,exports.LiveChattaError=f,exports.LiveChattaSDK=Gt,exports.MESSAGE_LAYOUT_PREFS=["auto","bubbles","lines"],exports.MUTE_FOREVER_AT="9999-12-31T23:59:59.000Z",exports.MY_LINK_ROLES=["owner","admin","agent","member"],exports.ModeratorPermissions=["pin_message","delete_message","mute_member"],exports.PASSWORD_MAX_LENGTH=200,exports.PASSWORD_MIN_LENGTH=8,exports.PAYMENT_CHANNELS=["card","bank_transfer"],exports.PENDING_TRANSFER_KINDS=["plan_change","extra_seats"],exports.PERSONAL_NOTE_MAX_LENGTH=2e3,exports.PLAN_BILLING_CYCLES=["MONTHLY","QUARTERLY","SEMI_YEARLY","YEARLY"],exports.PLAN_NOT_AVAILABLE=ae,exports.PLAN_NOT_AVAILABLE_MESSAGE=re,exports.PLAN_NOT_FOUND=oe,exports.PLAN_NOT_FOUND_MESSAGE=ne,exports.PLAN_TEAM_ACTIVATED=ie,exports.PLAN_TEAM_ACTIVATED_MESSAGE=se,exports.PLAN_TYPES=["FLASH","PULSE","FLASH_PRO","ORBIT","CUSTOM"],exports.POST_REPLIES_OFF_MESSAGE="Replies are turned off for this post.",exports.PREFERENCE_LANGUAGES=["en","fr","es","ar","pt","de","yo","ha","ig","sw","zh","hi"],exports.PUSH_REPLY_MAX_LENGTH=4e3,exports.PUSH_REPLY_TTL_SECONDS=21600,exports.Permissions=h,exports.RATE_LIMITED=Jt,exports.RECORDING_DOWNLOAD_EXPIRED="RECORDING_DOWNLOAD_EXPIRED",exports.RECORDING_DOWNLOAD_OFF="RECORDING_DOWNLOAD_OFF",exports.SENT_FROM_VALUES=["ios-app","android-app","desktop-app","mobile-web","web","api","bot","automation"],exports.SERVER_PAGE_CAPS={conversations:100,sidebarConversations:40,messages:50,stories:20,billingHistory:100,signups:100,giftPurchases:100,cursorLists:20},exports.SHARED_CHANNEL_LIMITS={inviteDefaultHours:168,inviteMaxHours:720,maxPickedMembers:500,maxPartners:10,archiveMaxMessages:1e4,pickPageSize:20,listPageSize:30,auditPageSize:30},exports.SIDEBAR_PAGE_SIZE=40,exports.SIGNAL_BRAND=Z,exports.SIGNAL_INK=nt,exports.SIGNAL_SECONDARY=tt,exports.SIGN_IN_REQUIRED="SIGN_IN_REQUIRED",exports.SOUND_PRESETS=["default","gentle","chime","pop","none"],exports.STAFF_ONLY_CREATE_MESSAGE="Only the team can start groups and channels here.",exports.STORAGE_LIMIT="STORAGE_LIMIT",exports.STORY_BACKGROUNDS=["ink","brand","lagoon","sun"],exports.SUBSCRIPTION_FAILED_TRANSFER_UNPAID="transfer_unpaid",exports.SocketAPI=I,exports.TEXT_SIZE_PREFS=["s","m","l","xl"],exports.THEME_ALL_KEYS=X,exports.THEME_COLOR_KEYS=Q,exports.TRANSCRIBE_ERROR_CODES=["OUT_OF_AI_CREDITS","NOT_AVAILABLE","NO_MEDIA","TOO_LONG","PROVIDER_FAILED"],exports.UNREAD_TOTALS_MAX_EXCLUDE=1e3,exports.WEBHOOK_TEST_EVENT="webhook.test",exports.WORKSPACE_TEAM_DESCRIPTION_MAX=200,exports.WORKSPACE_TEAM_MAX_MEMBERS=50,exports.WORKSPACE_TEAM_NAME_MAX=40,exports.applyEmbedMessage=Y,exports.assignDefinedProps=J,exports.awayState=gt,exports.brandTextOn=ht,exports.buildAppSignature=Dt,exports.contrastRatio=at,exports.detectRuntime=o,exports.effectiveMode=function(t){return"system"!==t?t:"undefined"==typeof window||"function"!=typeof window.matchMedia?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"},exports.encryptEmbedToken=n,exports.frameOrigin=V,exports.getPromoVisitorId=function(){if(Te)return Te;try{const t="undefined"!=typeof window?window.localStorage:null,e=null==t?void 0:t.getItem(me);if(e&&ye.test(e))return Te=e;Te=ge(),null==t||t.setItem(me,Te)}catch(t){Te=Te||ge()}return Te},exports.getRuntime=i,exports.hasCustomBrand=st,exports.helloOnLoad=j,exports.hmacSha256Hex=Lt,exports.isApiKeyOriginError=function(t){var e;return("string"==typeof t?t:String(null!==(e=null==t?void 0:t.message)&&void 0!==e?e:"")).includes(ue)},exports.isEditWindowClosed=function(t){if(!t||"object"!=typeof t)return!1;const{code:e,details:n}=t,r=n&&"object"==typeof n?n.code:void 0;return e===Zt||r===Zt},exports.isLinkCodeError=function(t){return!!t&&le.includes(t)},exports.isRateLimited=function(t){if(!t||"object"!=typeof t)return!1;const{code:e,details:n,error:r}=t,s=[n,r].map(t=>t&&"object"==typeof t?t.code:void 0);return e===Jt||r===Jt||s.includes(Jt)},exports.isSharedArchive=function(t){const e=(null==t?void 0:t.sharedWith)||[];return e.length>0&&e.every(t=>!0===t.ended)},exports.isSharedChannelBadgeEvent=function(t){return Array.isArray(t.sharedWith)&&!("sharedChannelId"in t)},exports.isSharedConversation=function(t){var e;return!!(null===(e=null==t?void 0:t.sharedWith)||void 0===e?void 0:e.some(t=>!t.ended))},exports.isSocketError=function(t){return t instanceof f&&("socket"===t.transport||"SOCKET_ERROR"===t.code)},exports.isWithinHours=mt,exports.newPasswordProblem=function(t,e){return"string"!=typeof t||t.length<8?"too-short":t.length>200?"too-long":t===e?null:"mismatch"},exports.nextOpening=Tt,exports.normalizeHex=rt,exports.normalizeThemeMode=ct,exports.onBrandColor=it,exports.parseCallPush=function(t){if(!t||"object"!=typeof t)return null;const e=String(t.sessionId||t.callId||"");if(!e)return null;if(t.type===te){const n=ee.includes(t.reason)?t.reason:"ended";return{type:te,callId:String(t.callId||e),sessionId:e,reason:n}}return"HOP_INVITE"!==t.type?null:{...t,callId:String(t.callId||e),sessionId:e}},exports.parseClock=pt,exports.parseDeepLink=zt,exports.parsePermissionDenial=function(t){var e;const n=null===(e=function(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){const e=t.message;if("string"==typeof e)return e;if(Array.isArray(e)&&"string"==typeof e[0])return e[0]}return null}(t))||void 0===e?void 0:e.trim();if(!n)return null;const r=Se.exec(n);if(r)return{action:"slowMode",retryAfterSeconds:Number(r[1]),message:n};if(n===ve)return{action:"locked",message:n};const s=Ce.find(([,t])=>t===n);return s?{action:s[0],message:n}:null},exports.pickDefined=function(t,e){const n={};for(const r of e)void 0!==t[r]&&null!==t[r]&&(n[r]=t[r]);return n},exports.planAccessError=function(t){if(!t||"object"!=typeof t)return null;const{statusCode:e,message:n,code:r}=t;return"string"==typeof r&&he[r]?he[r]:404===e&&n===ne?"not-found":400!==e?null:n===re||n===ne?"not-available":n===se?"team-activated":null},exports.postIncomingWebhook=async function(t,e,n={}){var r;if(!Ft.test(String(t||"").trim()))throw new f("That is not an https incoming webhook URL (https://<host>/hooks/in/lhk_...).",400,"INVALID_URL");const s="string"==typeof e?{text:e}:e,o=n.fetch||fetch,a=new AbortController,i=setTimeout(()=>a.abort(),null!==(r=n.timeoutMs)&&void 0!==r?r:15e3);let h;try{h=await o(t.trim(),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain"},body:JSON.stringify(s),signal:a.signal,redirect:"error"})}catch(t){const e="AbortError"===(null==t?void 0:t.name);throw new f(e?"Request timeout":"Could not reach the webhook URL",e?408:0,e?"TIMEOUT":"NETWORK")}finally{clearTimeout(i)}if(h.ok)return{ok:!0};let c={};try{c=await h.json()}catch(t){}const l="string"==typeof c.code?c.code.toUpperCase():404===h.status?"NOT_FOUND":void 0,u=Number(h.headers.get("Retry-After")),p=Number(c.retryAfter)||(Number.isFinite(u)&&u>0?u:void 0),d="string"==typeof c.message&&c.message?c.message:`Webhook answered ${h.status}`;throw new f(d,h.status,l,p?{retryAfter:p}:void 0)},exports.relativeLuminance=ot,exports.resolveBrand=function(t){return st(t)?rt(t):Z},exports.resolvePreChat=vt,exports.sendHello=K,exports.sentFromLabel=function(t){return"string"==typeof t&&Object.prototype.hasOwnProperty.call(Xt,t)?Xt[t]:""},exports.serverErrorCode=_,exports.sharedParticipantLabel=function(t){if(!t)return"Member";const e=[Ee(t.firstName),Ee(t.lastName)].filter(Boolean).join(" ");return Ee(t.displayName)||Ee(t.handle)||e||Ee(t.username)||"Member"},exports.toLinkWidgetConfig=function(t,e){if(!t)return{};const n=t.preChat,r=(e||[]).filter(t=>"string"==typeof t&&t.trim()),s=((null==n?void 0:n.fields)||[]).filter(t=>t&&Wt[t.key]).map(t=>{const e={...Wt[t.key],required:!!t.required};return"topic"===t.key&&r.length?{...e,type:"select",options:r}:e}),o=t.businessHours;return{preChat:n?{enabled:!!n.enabled,intro:n.intro||void 0,fields:s}:null,businessHours:o?{enabled:!!o.enabled,timezone:o.timezone,awayMessage:o.awayMessage||void 0,windows:o.week||[]}:null}},exports.validatePreChat=Ot,exports.zonedClock=dt;
2
2
  //# sourceMappingURL=livechatta.cjs.min.js.map