sim-sdk-web 1.2.7 → 1.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.umd.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("event-source-polyfill")):"function"==typeof define&&define.amd?define(["exports","event-source-polyfill"],t):t((e||self).simSdkWeb={},e.eventSourcePolyfill)}(this,function(e,t){function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function o(e,t){var o="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(o)return(o=o.call(e)).next.bind(o);if(Array.isArray(e)||(o=function(e,t){if(e){if("string"==typeof e)return n(e,t);var o={}.toString.call(e).slice(8,-1);return"Object"===o&&e.constructor&&(o=e.constructor.name),"Map"===o||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?n(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){o&&(e=o);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function r(){return r=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},r.apply(null,arguments)}function i(e,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},i(e,t)}function s(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var a,c,u,d,l;e.ServiceName=void 0,(a=e.ServiceName||(e.ServiceName={})).MESSAGE="message",a.CONVERSATION="conversation",a.GROUP="group",a.USER="user",a.CONTACT="contact",e.ContactType=void 0,(c=e.ContactType||(e.ContactType={}))[c.MEMBER=0]="MEMBER",c[c.COLLEAGUE=1]="COLLEAGUE",c[c.GROUP=2]="GROUP",e.ErrorCode=void 0,(u=e.ErrorCode||(e.ErrorCode={}))[u.UnknownError=10005]="UnknownError",e.RequestApi=void 0,(d=e.RequestApi||(e.RequestApi={})).Login="/chat/member/login",d.Logout="/chat/member/logout",d.GetChatMember="/chat/member/getChatMember",d.GetGroupInfo="/chat/group/groupInfo",d.GetGroupMembers="/chat/group/groupMembers",d.JoinGroup="/chat/group/joinGroup",d.LeftGroup="/chat/group/leftGroup",d.AnonymousJoinGroup="/chat/group/anonymousJoinGroup",d.AnonymousLeftGroup="/chat/group/anonymousLeftGroup",d.CheckGroupBlock="/chat/group/checkBlock",d.GetMyGroupPermission="/chat/group/permission/getPermission",d.GetGroupPermission="/chat/group/permission/groupPermission",d.GetGroupMember="/chat/group/groupMember",d.GetGroupMemberPermission="/chat/group/permission/groupMemberPermission",d.UpdateGroupPermission="/chat/group/permission/updateGroupPermission",d.UpdateGroupMemberPermission="/chat/group/permission/updateGroupMemberPermission",d.editeGroupName="/chat/group/operation/editeGroupName",d.editeNotification="/chat/group/operation/editeNotification",d.editeGroupCustomer="/chat/group/operation/editeGroupCustomer",d.addAdmin="/chat/group/operation/addAdmin",d.deleteAdmin="/chat/group/operation/deleteAdmin",d.pin="/chat/group/operation/pin",d.muteGroup="/chat/group/operation/muteGroup",d.muteMember="/chat/group/operation/muteMember",d.kickGroupMember="/chat/group/operation/kickGroupMember",d.muteMembers="/chat/group/operation/muteMembers",d.DissolveGroup="/chat/group/dissolve",d.GetAllConversationList="/chat/conversation/conversationList",d.GetChannels="/chat/conversation/getChannels",d.MarkConversationMessageAsRead="/chat/conversation/lastRead",d.PinConversation="/chat/conversation/pinChat",d.MuteConversation="/chat/conversation/mute",d.UpdateLatestMessage="/chat/group/updateLatestMessage",d.GetLatestGroupChats="/chat/group/latestGroupChats",d.CheckLatestMessages="/chat/group/checkLatestMessages",d.CreateTextMessage="/chat/message/push",d.PushMessageToMember="/chat/message/push2Member",d.PushPrivateMessage="/chat/message/pushPrivateMessage",d.PushLiveMessage="/chat/message/liveGroupPush",d.GetHistoryMessageList="/chat/message/pull",d.GetLiveMessageList="/chat/message/liveGroupPull",d.GetAnonymousLiveMessageList="/chat/message/anonymousLiveGroupPull",d.PrePushCustomerMessage="/chat/message/prePushCustomerMessage",d.UploadFile="/chat/img/upload",d.UploadCredential="/chat/img/uploadCredential",d.GetContactByType="/chat/contact/contactByType",d.EditContactTag="/chat/contact/editeContactTag",d.GetContactTag="/chat/contact/getContactTag",d.AllocationContactTag="/chat/contact/allocationContactTag",d.AddGroupMembers="/chat/group/operation/addGroupMembers",d.GetFileByType="/chat/message/getFileByType",d.PinChat="/chat/member/pinChat",e.CbEvents=void 0,(l=e.CbEvents||(e.CbEvents={})).OnConnected="OnConnected",l.OnDisconnected="OnDisconnected",l.onMaxRetriesReached="onMaxRetriesReached",l.OnReconnecting="OnReconnecting",l.OnReconnected="OnReconnected",l.OnReconnectFailed="OnReconnectFailed",l.OnNetworkChange="OnNetworkChange",l.OnReceiveMessage="OnReceiveMessage",l.OnReceiveProtoMessage="OnReceiveProtoMessage",l.OnReceiveMessages="OnReceiveMessages",l.OnReceiveSubscribeMessage="OnReceiveSubscribeMessage",l.OnReceiveSystemMessage="OnReceiveSystemMessage",l.OnReceivePreMessage="OnReceivePreMessage",l.OnMessagesListLoaded="OnMessagesListLoaded",l.OnActiveConversationSync="OnActiveConversationSync",l.OnMessageSent="OnMessageSent",l.OnMessageFailed="OnMessageFailed",l.OnMessageRevoked="OnMessageRevoked",l.OnMessageDeleted="OnMessageDeleted",l.OnMessageRead="OnMessageRead",l.OnTypingStatusUpdate="OnTypingStatusUpdate",l.OnUserStatusChange="OnUserStatusChange",l.OnKickedOffline="OnKickedOffline",l.OnUserTokenInvalid="OnUserTokenInvalid",l.OnUserTokenExpired="OnUserTokenExpired",l.OnForceOffline="OnForceOffline",l.OnUserInfoUpdated="OnUserInfoUpdated",l.OnGroupCreated="OnGroupCreated",l.OnGroupInfoUpdated="OnGroupInfoUpdated",l.OnGroupDissolved="OnGroupDissolved",l.OnJoinGroup="OnJoinGroup",l.OnLeaveGroup="OnLeaveGroup",l.OnGroupMemberJoined="OnGroupMemberJoined",l.OnGroupMemberLeft="OnGroupMemberLeft",l.OnGroupMemberKicked="OnGroupMemberKicked",l.OnGroupOwnerChanged="OnGroupOwnerChanged",l.OnGroupAdminAdded="OnGroupAdminAdded",l.OnGroupAdminRemoved="OnGroupAdminRemoved",l.OnGroupMemberMuted="OnGroupMemberMuted",l.OnGroupMemberUnmuted="OnGroupMemberUnmuted",l.OnGroupAllMemberMuted="OnGroupAllMemberMuted",l.OnGroupAllMemberUnmuted="OnGroupAllMemberUnmuted",l.OnConversationCreated="OnConversationCreated",l.OnConversationDeleted="OnConversationDeleted",l.OnConversationListUpdated="OnConversationListUpdated",l.OnConversationUpdated="OnConversationUpdated",l.OnUnreadCountChanged="OnUnreadCountChanged",l.OnConversationPinned="OnConversationPinned",l.OnConversationUnpinned="OnConversationUnpinned",l.OnConversationMuted="OnConversationMuted",l.OnConversationUnmuted="OnConversationUnmuted",l.OnPongConn="OnPongConn",l.OnPongReConn="OnPongReConn",l.OnPongIdle="OnPongIdle",l.OnError="OnError",l.OnWarning="OnWarning",l.OnLog="OnLog";var g,h,p,m,v,f,C=/*#__PURE__*/function(){function t(){var t;this.events=((t={})[e.CbEvents.OnReceiveMessage]=[],t[e.CbEvents.OnReceiveSystemMessage]=[],t[e.CbEvents.OnReceiveMessages]=[],t[e.CbEvents.OnConversationListUpdated]=[],t[e.CbEvents.OnMessagesListLoaded]=[],t[e.CbEvents.OnActiveConversationSync]=[],t[e.CbEvents.OnConnected]=[],t[e.CbEvents.OnDisconnected]=[],t[e.CbEvents.OnReconnected]=[],t)}var n=t.prototype;return n.emit=function(e,t){var n=this.events[e];return n&&n.forEach(function(e){return e(t)}),this},n.on=function(e,t){var n;return this.events[e]||(this.events[e]=[]),null==(n=this.events[e])||n.push(t),this},n.off=function(e,t){var n=this.events[e];if(n){var o=n.indexOf(t);o>-1&&(n.splice(o,1),0===n.length&&delete this.events[e])}return this},t}();e.GroupType=void 0,(g=e.GroupType||(e.GroupType={}))[g.PrivateChat=0]="PrivateChat",g[g.PrivateGroup=1]="PrivateGroup",g[g.PublicGroup=2]="PublicGroup",g[g.CustomerService=3]="CustomerService",g[g.LiveGroup=4]="LiveGroup",g[g.ChanneRoom=5]="ChanneRoom",e.MessageType=void 0,(h=e.MessageType||(e.MessageType={}))[h.TEXT=0]="TEXT",h[h.IMAGE=1]="IMAGE",h[h.FILE=2]="FILE",h[h.AUDIO=3]="AUDIO",h[h.VIDEO=4]="VIDEO",h[h.LINK=5]="LINK",h[h.GIF=6]="GIF",h[h.OPTION=7]="OPTION",h[h.EMOJI=8]="EMOJI",h[h.CUSTOM=100]="CUSTOM",e.SseEventType=void 0,(p=e.SseEventType||(e.SseEventType={}))[p.EVENT_PONG_CONN=0]="EVENT_PONG_CONN",p[p.EVENT_PONG_RE_CONN=1]="EVENT_PONG_RE_CONN",p[p.EVENT_PONG_IDLE=2]="EVENT_PONG_IDLE",p[p.EVENT_MESSAGE_PUSH=3]="EVENT_MESSAGE_PUSH",p[p.EVENT_SYSTEM_MESSAGE_PUSH=4]="EVENT_SYSTEM_MESSAGE_PUSH",p[p.EVENT_LIVE_SYSTEM_MESSAGE_PUSH=5]="EVENT_LIVE_SYSTEM_MESSAGE_PUSH",p[p.EVENT_PRE_MESSAGE_PUSH=6]="EVENT_PRE_MESSAGE_PUSH",p[p.EVENT_SUBSCRIBE_MESSAGE_PUSH=7]="EVENT_SUBSCRIBE_MESSAGE_PUSH",e.GroupMemberEventType=void 0,(m=e.GroupMemberEventType||(e.GroupMemberEventType={}))[m.JOIN=0]="JOIN",m[m.LEFT=1]="LEFT",m[m.LAST_READ_UPDATE=2]="LAST_READ_UPDATE",m[m.PERMISSION_UPDATE=3]="PERMISSION_UPDATE",m[m.IDENTITY_UPDATE=4]="IDENTITY_UPDATE",m[m.PING_UPDATE=5]="PING_UPDATE",e.SystemMessageType=void 0,(v=e.SystemMessageType||(e.SystemMessageType={}))[v.GroupMemberPermissionChange=3]="GroupMemberPermissionChange",v[v.GroupPermissionChange=4]="GroupPermissionChange",e.ConnectionProtocol=void 0,(f=e.ConnectionProtocol||(e.ConnectionProtocol={})).SSE="sse",f.WEBSOCKET="websocket";var b="undefined"!=typeof uni,S="undefined"!=typeof window,E="simsdk_",T={CONVERSATIONS:E+"conversations",GROUP_MESSAGES:E+"group_messages",USER_INFO:E+"user_info",META_INFO:E+"meta"},M={MAX_CONVERSATIONS:100,MAX_GROUP_MESSAGES:200,STORAGE_CHUNK_SIZE:512e3,CACHE_TTL:6048e5,EXPIRY_CHECK_INTERVAL:18e5},y=/*#__PURE__*/function(){function e(e){var t=void 0===e?{}:e,n=t.persistEnabled,o=void 0===n||n,i=t.debug,s=void 0!==i&&i,a=t.config,c=void 0===a?{}:a;this.conversationCache=[],this.groupMessageCache={},this.accessTimeRecord={},this.pinnedConversationOrder=new Map,this.userInfo={},this.currentUsername=void 0,this.activeConversation=void 0,this.metaInfo={},this.persistEnabled=void 0,this.debug=void 0,this.config=void 0,this.cleanupTimer=void 0,this.persistEnabled=o,this.debug=s,this.config=r({},M,c)}var t=e.prototype;return t.initialize=function(e){this.currentUsername&&this.currentUsername!==e&&(this.debug&&console.log("User switched from "+this.currentUsername+" to "+e+", clearing cache"),this.clear()),this.currentUsername=e,this.userInfo.username=e,this.persistEnabled&&this.loadFromStorage(),this.setupCleanupInterval(),this.debug&&(console.log("Cache initialized for user:",e),console.log("Loaded conversations:",this.conversationCache.length),console.log("Loaded group messages for groups:",Object.keys(this.groupMessageCache).length))},t.clear=function(){this.conversationCache=[],this.groupMessageCache={},this.accessTimeRecord={},this.pinnedConversationOrder.clear(),this.persistEnabled&&this.clearCurrentUserStorage(),this.debug&&console.log("Cache cleared")},t.clearCurrentUserStorage=function(){try{if(!this.currentUsername)return void this.clearStorage();var e=this.getUserStorageKey(T.CONVERSATIONS);localStorage.removeItem(e);var t=this.getUserStorageKey(T.USER_INFO);localStorage.removeItem(t);for(var n,r=o(Object.keys(localStorage).filter(function(e){return e.startsWith(T.GROUP_MESSAGES+".")}));!(n=r()).done;)localStorage.removeItem(n.value)}catch(e){console.error("Failed to clear current user storage:",e)}},t.getConversations=function(){return[].concat(this.conversationCache)},t.clearConversationUnread=function(e){var t=this.conversationCache.find(function(t){return t.id===e});t&&(t.unreadCount=0,this.persistEnabled&&this.saveConversationsToStorage())},t.updateConversationLastRead=function(e,t){var n=this.conversationCache.find(function(t){return t.id===e});n&&(n.lastRead=t,n.unreadCount=0,this.persistEnabled&&this.saveConversationsToStorage())},t.clearAllConversationUnread=function(){this.conversationCache.forEach(function(e){e.unreadCount>0&&(e.unreadCount=0)}),this.persistEnabled&&this.saveConversationsToStorage()},t.getActiveConversation=function(){return this.activeConversation},t.setConversations=function(e,t){var n=this;if(void 0===t&&(t=!1),this.conversationCache=e.length>this.config.MAX_CONVERSATIONS?e.slice(0,this.config.MAX_CONVERSATIONS):[].concat(e),t)this.pinnedConversationOrder.clear(),this.conversationCache.forEach(function(e,t){e.pin&&n.pinnedConversationOrder.set(e.id,t)});else{var o=-1;this.pinnedConversationOrder.forEach(function(e){e>o&&(o=e)}),this.conversationCache.forEach(function(e,t){e.pin&&!n.pinnedConversationOrder.has(e.id)&&n.pinnedConversationOrder.set(e.id,o+t+1)})}this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()},t.updateConversation=function(e){var t=this.conversationCache.findIndex(function(t){return t.id===e.id});t>=0?this.conversationCache[t]=r({},e):(this.conversationCache.push(r({},e)),this.conversationCache.length>this.config.MAX_CONVERSATIONS&&this.enforceConversationLimit()),this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()},t.updateConversationPinStatus=function(e,t){var n=this.conversationCache.findIndex(function(t){return t.id===e});if(-1!==n){var o=this.conversationCache[n],r=!0===o.pin;if(o.pin=t,t&&!r){var i=-1;this.pinnedConversationOrder.forEach(function(e){e>i&&(i=e)}),this.pinnedConversationOrder.set(e,i+1)}else!t&&r&&this.pinnedConversationOrder.delete(e);this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage()}},t.updateConversationWithMessage=function(e,t){var n,o=e.groupId;if(!o)return!1;var r=this.conversationCache.findIndex(function(e){return e.id===o});if(-1===r)return!1;var i=this.conversationCache[r],s=(null==(n=i.latest)?void 0:n.msgId)||0;return this.activeConversation&&this.activeConversation.id===o?(i.unreadCount=0,i.lastRead=e.msgId):t!==e.username&&(i.unreadCount+=e.msgId>s?e.msgId-s:1),i.latest=e,this.sortConversations(),this.persistEnabled&&this.saveConversationsToStorage(),!0},t.getGroupMessages=function(e){return this.recordAccess(e),!this.groupMessageCache[e]&&this.persistEnabled&&this.loadGroupMessagesFromStorage(e),this.groupMessageCache[e]||[]},t.addGroupMessage=function(e){if(e.groupId){this.recordAccess(e.groupId),this.groupMessageCache[e.groupId]||(this.groupMessageCache[e.groupId]=[]);var t=this.groupMessageCache[e.groupId].findIndex(function(t){return t.msgId===e.msgId});t>=0?this.groupMessageCache[e.groupId][t]=e:this.groupMessageCache[e.groupId].push(e),this.sortGroupMessages(e.groupId),this.limitGroupMessageCache(e.groupId),this.enforceMemoryLimits(),this.persistEnabled&&this.saveGroupMessagesToStorage(e.groupId)}},t.addGroupMessages=function(e){for(var t,n=this,r={},i=o(e);!(t=i()).done;){var s=t.value;s.groupId&&(r[s.groupId]||(r[s.groupId]=[]),r[s.groupId].push(s))}for(var a=0,c=Object.entries(r);a<c.length;a++){var u=c[a],d=u[0],l=u[1];this.recordAccess(Number(d)),this.groupMessageCache[d]||(this.groupMessageCache[d]=[]);for(var g,h=function(){var e=g.value,t=n.groupMessageCache[d].findIndex(function(t){return t.msgId===e.msgId});t>=0?n.groupMessageCache[d][t]=e:n.groupMessageCache[d].push(e)},p=o(l);!(g=p()).done;)h();this.sortGroupMessages(Number(d)),this.limitGroupMessageCache(Number(d)),this.persistEnabled&&this.saveGroupMessagesToStorage(Number(d))}this.enforceMemoryLimits()},t.sortConversations=function(){var e=this;this.conversationCache.sort(function(t,n){var o,r,i,s,a=!0===t.pin,c=!0===n.pin;if(a&&!c)return-1;if(!a&&c)return 1;if(a&&c)return(null!=(i=e.pinnedConversationOrder.get(t.id))?i:0)-(null!=(s=e.pinnedConversationOrder.get(n.id))?s:0);var u=(null==(o=t.latest)?void 0:o.createTime)||0;return((null==(r=n.latest)?void 0:r.createTime)||0)-u})},t.sortGroupMessages=function(e){this.groupMessageCache[e]&&this.groupMessageCache[e].sort(function(e,t){return(t.createTime||0)-(e.createTime||0)})},t.limitGroupMessageCache=function(e){this.groupMessageCache[e]&&this.groupMessageCache[e].length>this.config.MAX_GROUP_MESSAGES&&(this.groupMessageCache[e]=this.groupMessageCache[e].slice(0,this.config.MAX_GROUP_MESSAGES))},t.recordAccess=function(e){this.accessTimeRecord[e]=Date.now()},t.enforceConversationLimit=function(){this.conversationCache.length<=this.config.MAX_CONVERSATIONS||(this.sortConversations(),this.conversationCache=this.conversationCache.slice(0,this.config.MAX_CONVERSATIONS))},t.enforceMemoryLimits=function(){var e=this,t=Object.keys(this.groupMessageCache).length;if(t>10){var n=Object.keys(this.groupMessageCache).map(function(t){return{groupId:t,lastAccess:e.accessTimeRecord[t]||0}});n.sort(function(e,t){return e.lastAccess-t.lastAccess});for(var o=Math.ceil(.3*t),r=0;r<o&&r<n.length;r++){var i=n[r].groupId;this.persistEnabled&&(delete this.groupMessageCache[i],this.debug&&console.log("Released memory for inactive group: "+i))}}},t.setupCleanupInterval=function(){var e=this;this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=window.setInterval(function(){e.cleanupExpiredData()},this.config.EXPIRY_CHECK_INTERVAL)},t.cleanupExpiredData=function(){var e=Date.now();this.metaInfo.lastCleanup=e,this.debug&&console.log("Running cache cleanup");for(var t=0,n=Object.entries(this.accessTimeRecord);t<n.length;t++){var o=n[t],r=o[0];e-o[1]>this.config.CACHE_TTL&&(delete this.accessTimeRecord[r],this.groupMessageCache[r]&&delete this.groupMessageCache[r])}this.persistEnabled&&this.saveMetaInfoToStorage()},t.getUserStorageKey=function(e){return this.currentUsername?e+"_"+this.currentUsername:e},t.loadFromStorage=function(){var e=this;try{var t=localStorage.getItem(T.META_INFO);t&&(this.metaInfo=JSON.parse(t));var n=this.getUserStorageKey(T.CONVERSATIONS),o=localStorage.getItem(n);this.conversationCache=o?JSON.parse(o):[],Object.keys(localStorage).filter(function(e){return e.startsWith(T.GROUP_MESSAGES+".")}).forEach(function(t){var n=t.split(".")[1];n&&!isNaN(Number(n))&&(e.accessTimeRecord[n]=0)});var r=this.getUserStorageKey(T.USER_INFO),i=localStorage.getItem(r);this.userInfo=i?JSON.parse(i):{username:this.currentUsername}}catch(e){console.error("Failed to load cache from storage:",e),this.clearStorage()}},t.loadGroupMessagesFromStorage=function(e){try{for(var t=[],n=0,o=!0;o;){var r=localStorage.getItem(T.GROUP_MESSAGES+"."+e+(n>0?"."+n:""));if(r){var i=JSON.parse(r);t=t.concat(i),n++}else o=!1}t.length>0&&(this.groupMessageCache[e]=t,this.sortGroupMessages(e),this.limitGroupMessageCache(e),this.debug&&console.log("Loaded "+t.length+" messages for group "+e+" from storage"))}catch(t){console.error("Failed to load group messages for "+e+" from storage:",t)}},t.saveConversationsToStorage=function(){try{var e=this.getUserStorageKey(T.CONVERSATIONS);localStorage.setItem(e,JSON.stringify(this.conversationCache))}catch(e){console.error("Failed to save conversations to storage:",e),this.handleStorageError()}},t.saveGroupMessagesToStorage=function(e){try{if(void 0!==e){var t=this.groupMessageCache[e];if(!t||0===t.length)return;var n=JSON.stringify(t);if(n.length>this.config.STORAGE_CHUNK_SIZE){this.clearGroupMessageStorage(e);for(var o=t.length,r=Math.max(1,Math.floor(this.config.STORAGE_CHUNK_SIZE/(n.length/o))),i=0;i<o;i+=r){var s=t.slice(i,i+r),a=Math.floor(i/r);localStorage.setItem(T.GROUP_MESSAGES+"."+e+(a>0?"."+a:""),JSON.stringify(s))}}else localStorage.setItem(T.GROUP_MESSAGES+"."+e,n)}else for(var c=0,u=Object.keys(this.groupMessageCache);c<u.length;c++)this.saveGroupMessagesToStorage(Number(u[c]))}catch(e){console.error("Failed to save group messages to storage:",e),this.handleStorageError()}},t.saveMetaInfoToStorage=function(){try{localStorage.setItem(T.META_INFO,JSON.stringify(this.metaInfo))}catch(e){console.error("Failed to save meta info to storage:",e)}},t.handleStorageError=function(){for(var e=this,t=Object.keys(this.accessTimeRecord).map(function(t){return{groupId:t,lastAccess:e.accessTimeRecord[t]||0}}).sort(function(e,t){return e.lastAccess-t.lastAccess}),n=Math.max(1,Math.floor(.2*t.length)),o=0;o<n&&o<t.length;o++)this.clearGroupMessageStorage(Number(t[o].groupId)),this.debug&&console.log("Cleared storage for group "+t[o].groupId+" due to quota exceeded")},t.clearGroupMessageStorage=function(e){for(var t=0,n=!0;n;){var o=T.GROUP_MESSAGES+"."+e+(t>0?"."+t:"");null!==localStorage.getItem(o)?(localStorage.removeItem(o),t++):n=!1}},t.saveUserInfoToStorage=function(){try{var e=this.getUserStorageKey(T.USER_INFO);localStorage.setItem(e,JSON.stringify(this.userInfo))}catch(e){console.error("Failed to save user info to storage:",e)}},t.clearStorage=function(){try{for(var e,t=o(Object.keys(localStorage).filter(function(e){return e.startsWith(E)}));!(e=t()).done;)localStorage.removeItem(e.value)}catch(e){console.error("Failed to clear storage:",e)}},t.destroy=function(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.debug&&console.log("Cache manager destroyed")},t.markConversationAsActive=function(e,t){void 0===t&&(t=!0),this.accessTimeRecord[e]=Date.now();var n,o=this.conversationCache.find(function(t){return t.id===e});return!!o&&(this.activeConversation=r({},o),t&&o.unreadCount>0&&(o.unreadCount=0,null!=(n=o.latest)&&n.msgId&&(o.lastRead=o.latest.msgId),this.persistEnabled&&this.saveConversationsToStorage()),!0)},t.resetActiveConversation=function(){var e,t=!(null==(e=this.activeConversation)||!e.id);return this.activeConversation=void 0,this.debug&&t&&console.log("Active conversation reset"),t},e}(),P=/*#__PURE__*/function(){function e(e){this.url=void 0,this.token=void 0,this.eventSource=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=2e3*Math.random()+3e3,this.connectTimeout=1e4,this.reconnectTimer=null,this.handlers=new Map,this.connected=!1,this.onMessageCallback=void 0,this.onReconnectSuccessCallback=void 0,this.onConnectionClosedCallback=void 0,this.onMaxRetriesReachedCallback=void 0,this.onConnectionChangeCallback=void 0,this.isDestroyed=!1,this.debug=!1,this._openHandler=null,this._errorHandler=null,this._messageHandler=null,this._customHandlers=new Map,this.connectTimeoutRef=null,this.url=e.url,this.token=e.token,this.connectTimeout=e.connectTimeout||1e4,this.reconnectTimeout=e.retryInterval||2e3*Math.random()+3e3,this.maxReconnectAttempts=e.maxRetries||5,this.debug=e.debug||!1,this.onMessageCallback=e.onMessage,this.onReconnectSuccessCallback=e.onReconnectSuccess,this.onConnectionClosedCallback=e.onConnectionClosed,this.onMaxRetriesReachedCallback=e.onMaxRetriesReached,this.onConnectionChangeCallback=e.onConnectionChange}var n=e.prototype;return n.debugLog=function(e){var t;this.debug&&(t=console).log.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.debugError=function(e){var t;this.debug&&(t=console).error.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.debugWarn=function(e){var t;this.debug&&(t=console).warn.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.removeAllEventListeners=function(){var e=this;this.eventSource&&(this._openHandler&&this.eventSource.removeEventListener("open",this._openHandler),this._errorHandler&&this.eventSource.removeEventListener("error",this._errorHandler),this._messageHandler&&this.eventSource.removeEventListener("message",this._messageHandler),this.handlers.forEach(function(t,n){var o=e._customHandlers.get(n);o&&e.eventSource&&e.eventSource.removeEventListener(n,o)}))},n.subscribe=function(e,t){var n=this;this.handlers.set(e,t);var o=function(e){try{var o=JSON.parse(e.data);t(o)}catch(e){n.debugError("Error parsing message data:",e)}};this._customHandlers.set(e,o),this.eventSource?this.eventSource.addEventListener(e,o):this.connect()},n.connect=function(){var e=this;return this.connected&&this.eventSource?Promise.reject(new Error("SSE is already connected!")):new Promise(function(n,o){try{e.eventSource=new t.EventSourcePolyfill(e.url,{heartbeatTimeout:36e5,withCredentials:!1,headers:{Authorization:"Bearer "+e.token}}),e._openHandler=function(t){e.debugLog("SSE connection established"),e.connected=!0,e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!0),e.reconnectAttempts>0&&e.onReconnectSuccessCallback&&e.onReconnectSuccessCallback(),e.reconnectAttempts=0,e.reconnectTimeout=5e3,n("SSE connect successful!")},e._errorHandler=function(t){e.debugError("SSE connection error:",t),e.connected=!1,e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!1),401===t.status||t.statusText&&t.statusText.includes("Unauthorized")?(e.cleanup(),e.connectTimeoutRef&&(clearTimeout(e.connectTimeoutRef),e.connectTimeoutRef=null),e.notifyConnectionClosed(!0)):e.handleReconnect(),e.connected||o(new Error("SSE connect error"))},e._messageHandler=function(t){try{e.debugLog("SSE received message:",t.data);var n=JSON.parse(t.data);e.onMessageCallback&&e.onMessageCallback(n)}catch(t){e.debugError("Error parsing message:",t)}},e.eventSource.addEventListener("open",e._openHandler),e.eventSource.addEventListener("error",e._errorHandler),e.eventSource.addEventListener("message",e._messageHandler),e.handlers.forEach(function(t,n){var o=e._customHandlers.get(n);o&&e.eventSource&&e.eventSource.addEventListener(n,o)}),e.connectTimeoutRef=setTimeout(function(){e.connected||(o(new Error("Connection timeout")),e.handleReconnect())},e.connectTimeout);var r=e._openHandler;e._openHandler=function(t){clearTimeout(e.connectTimeoutRef),r(t)}}catch(t){e.debugError("Failed to create EventSource:",t),e.handleReconnect(),o(t)}})},n.notifyConnectionClosed=function(e){void 0===e&&(e=!1),this.onConnectionClosedCallback&&this.onConnectionClosedCallback(e),e?this.debugWarn("SSE connection closed due to authentication error"):this.debugLog("SSE connection closed")},n.handleReconnect=function(){var e=this;if(this.isDestroyed)this.debugLog("SSE is destroyed, skipping reconnection");else if(null===this.reconnectTimer){if(this.reconnectAttempts>=this.maxReconnectAttempts)return this.debugError("Max reconnection attempts reached"),this.destroySse(),void(this.onMaxRetriesReachedCallback&&this.onMaxRetriesReachedCallback());this.debugLog("Attempting to reconnect in "+this.reconnectTimeout/1e3+" seconds..."),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectAttempts++,e.reconnectTimeout=Math.min(2*e.reconnectTimeout,6e4),e.reconnectTimer=null,e.connect().catch(function(){})},this.reconnectTimeout)}},n.cleanup=function(){this.eventSource&&(this.removeAllEventListeners(),this.eventSource.close(),this.eventSource=null),this.connected=!1},n.unsubscribe=function(){this.cleanup(),this.handlers.clear(),this._customHandlers.clear(),null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)},n.destroySse=function(){this.unsubscribe(),this.isDestroyed=!0,this.notifyConnectionClosed()},n.close=function(){this.destroySse(),this.debugLog("SSE 连接已关闭")},n.isConnected=function(){return this.connected},n.send=function(e){var t="当前协议不可用:SSE 是单向通信协议,不支持客户端向服务器发送消息";throw this.debugError(t),new Error(t)},e}(),O=/*#__PURE__*/function(){function e(e){this.url=void 0,this.token=void 0,this.websocket=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=2e3*Math.random()+3e3,this.connectTimeout=1e4,this.reconnectTimer=null,this.handlers=new Map,this.connected=!1,this.onMessageCallback=void 0,this.onReconnectSuccessCallback=void 0,this.onConnectionClosedCallback=void 0,this.onMaxRetriesReachedCallback=void 0,this.onConnectionChangeCallback=void 0,this.connectTimeoutRef=null,this.isDestroyed=!1,this.debug=!1,this.lastPingTime=0,this.pingCheckTimer=null,this.pageVisibilityHandler=null,this.isPageVisible=!0,this.lastVisibleTime=Date.now(),this.PING_TIMEOUT=12e4,this.PING_CHECK_INTERVAL=5e3,this.RECONNECT_DELAY=3e3,this.PAGE_HIDDEN_TOLERANCE=6e4,this.url=e.url,this.token=e.token,this.connectTimeout=e.connectTimeout||1e4,this.reconnectTimeout=e.retryInterval||2e3*Math.random()+3e3,this.maxReconnectAttempts=e.maxRetries||5,this.debug=e.debug||!1,this.onMessageCallback=e.onMessage,this.onReconnectSuccessCallback=e.onReconnectSuccess,this.onConnectionClosedCallback=e.onConnectionClosed,this.onMaxRetriesReachedCallback=e.onMaxRetriesReached,this.onConnectionChangeCallback=e.onConnectionChange,this.initPageVisibilityDetection()}var t=e.prototype;return t.debugLog=function(e){var t;this.debug&&(t=console).log.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.debugError=function(e){var t;this.debug&&(t=console).error.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.debugWarn=function(e){var t;this.debug&&(t=console).warn.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.subscribe=function(e,t){this.handlers.set(e,t),this.websocket?this.addMessageHandler(e,t):this.connect()},t.addMessageHandler=function(e,t){var n=this;this.websocket&&this.websocket.addEventListener("message",function(o){try{var r=JSON.parse(o.data);r.type===e&&t(r)}catch(e){n.debugError("Error parsing WebSocket message data:",e)}})},t.connect=function(){var e=this;return this.connected&&this.websocket?Promise.reject(new Error("WebSocket is already connected!")):new Promise(function(t,n){try{var o=new URL(e.url);o.searchParams.set("token",e.token),e.websocket=new WebSocket(o.toString()),e.websocket.binaryType="arraybuffer",e.connectTimeoutRef=setTimeout(function(){e.connected||(n(new Error("WebSocket connection timeout")),e.handleReconnect())},e.connectTimeout),e.websocket.onopen=function(n){e.debugLog("WebSocket connection established"),e.connected=!0,clearTimeout(e.connectTimeoutRef),e.lastPingTime=Date.now(),e.startPingTimeoutCheck(),e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!0),e.reconnectAttempts>0&&e.onReconnectSuccessCallback&&e.onReconnectSuccessCallback(),e.reconnectAttempts=0,e.reconnectTimeout=5e3,t("WebSocket connect successful!")},e.websocket.onerror=function(t){e.debugError("WebSocket connection error:",t),e.connected=!1,clearTimeout(e.connectTimeoutRef),e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!1),e.handleReconnect(),e.connected||n(new Error("WebSocket connect error"))},e.websocket.onclose=function(t){e.debugLog("WebSocket connection closed:",t.code,t.reason),e.connected=!1,1002===t.code||1003===t.code||t.reason&&t.reason.includes("Unauthorized")?(e.cleanup(),e.notifyConnectionClosed(!0)):(e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),e.handleReconnect())},e.websocket.onmessage=function(t){try{t.data instanceof ArrayBuffer?e.handleBinaryMessage(t.data):e.handleTextMessage(t.data),e.lastPingTime=Date.now()}catch(t){e.debugError("Error handling WebSocket message:",t)}},e.handlers.forEach(function(t,n){e.addMessageHandler(n,t)})}catch(t){e.debugError("Failed to create WebSocket:",t),e.handleReconnect(),n(t)}})},t.notifyConnectionClosed=function(e){void 0===e&&(e=!1),this.onConnectionClosedCallback&&this.onConnectionClosedCallback(e),e?this.debugWarn("WebSocket connection closed due to authentication error"):this.debugLog("WebSocket connection closed")},t.handleReconnect=function(){var e=this;if(this.isDestroyed)this.debugLog("WebSocket is destroyed, skipping reconnection");else if(null===this.reconnectTimer){if(this.reconnectAttempts>=this.maxReconnectAttempts)return this.debugError("Max reconnection attempts reached"),this.destroyWebSocket(),void(this.onMaxRetriesReachedCallback&&this.onMaxRetriesReachedCallback());this.debugLog("Attempting to reconnect in "+this.reconnectTimeout/1e3+" seconds... (attempt "+(this.reconnectAttempts+1)+"/"+this.maxReconnectAttempts+")"),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectAttempts++,e.reconnectTimeout=Math.min(2*e.reconnectTimeout,6e4),e.reconnectTimer=null,e.connect().catch(function(){})},this.reconnectTimeout)}},t.handleBinaryMessage=function(e){var t=new DataView(e);if(!(e.byteLength<1)){var n=t.getUint8(0);if(125===n&&e.byteLength>=9){var o=t.getBigInt64(1,!1);return this.debugLog("收到服务端心跳 ping:",o.toString()),this.lastPingTime=Date.now(),void this.sendPong(o)}this.debugLog("收到二进制消息,类型:",n,"长度:",e.byteLength)}},t.handleTextMessage=function(e){try{this.debugLog("WebSocket received text message:",e);var t=JSON.parse(e);if("pong"===t.type||2===t.ev)return this.connected=!0,void(this.lastPingTime=Date.now());this.onMessageCallback&&this.onMessageCallback(t)}catch(e){this.debugError("Error parsing WebSocket text message:",e)}},t.sendPong=function(e){if(this.websocket&&this.websocket.readyState===WebSocket.OPEN)try{var t=new ArrayBuffer(9),n=new DataView(t);n.setUint8(0,126),n.setBigInt64(1,e,!1),this.websocket.send(t),this.debugLog("已回复心跳 pong, timestamp:",e.toString())}catch(e){this.debugError("Failed to send pong:",e)}else this.debugWarn("WebSocket is not open, cannot send pong")},t.initPageVisibilityDetection=function(){var e=this;"undefined"!=typeof document&&(this.isPageVisible=!document.hidden,this.lastVisibleTime=Date.now(),this.pageVisibilityHandler=function(){var t=e.isPageVisible;if(e.isPageVisible=!document.hidden,t&&!e.isPageVisible)e.lastVisibleTime=Date.now(),e.debugLog("Page became hidden, pausing ping timeout check");else if(!t&&e.isPageVisible){var n=Date.now()-e.lastVisibleTime;e.debugLog("Page became visible after "+n+"ms"),e.websocket&&e.websocket.readyState===WebSocket.OPEN&&n>e.PAGE_HIDDEN_TOLERANCE&&(e.debugLog("Page was hidden for a long time, adjusting ping time"),e.lastPingTime=Date.now()-(e.PING_TIMEOUT-e.PAGE_HIDDEN_TOLERANCE))}},document.addEventListener("visibilitychange",this.pageVisibilityHandler))},t.startPingTimeoutCheck=function(){var e=this;this.stopPingTimeoutCheck(),this.pingCheckTimer=window.setInterval(function(){if(!e.isDestroyed&&e.websocket)if(e.isPageVisible){if(e.websocket.readyState!==WebSocket.OPEN)return e.debugWarn("WebSocket state is "+e.websocket.readyState+", connection may be broken"),e.connected=!1,e.stopPingTimeoutCheck(),e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),void e.delayedReconnect();var t=Date.now()-e.lastPingTime;t>e.PING_TIMEOUT?(e.debugWarn("Ping timeout: "+t+"ms since last ping, connection may be broken"),e.connected=!1,e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),e.delayedReconnect()):e.debugLog("Last ping received "+t+"ms ago")}else e.debugLog("Page is hidden, skipping ping timeout check");else e.stopPingTimeoutCheck()},this.PING_CHECK_INTERVAL)},t.stopPingTimeoutCheck=function(){null!==this.pingCheckTimer&&(clearInterval(this.pingCheckTimer),this.pingCheckTimer=null)},t.delayedReconnect=function(){var e=this;null===this.reconnectTimer&&(this.debugLog("Delaying reconnect for "+this.RECONNECT_DELAY/1e3+" seconds to prevent reconnect storm..."),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectTimer=null,e.handleReconnect()},this.RECONNECT_DELAY))},t.cleanup=function(){this.stopPingTimeoutCheck(),this.websocket&&(this.websocket.close(),this.websocket=null),this.connected=!1},t.cleanupPageVisibilityDetection=function(){this.pageVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.pageVisibilityHandler),this.pageVisibilityHandler=null)},t.unsubscribe=function(){this.cleanup(),this.handlers.clear(),null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.cleanupPageVisibilityDetection()},t.destroyWebSocket=function(){this.unsubscribe(),this.isDestroyed=!0,this.cleanupPageVisibilityDetection(),this.notifyConnectionClosed()},t.close=function(){this.destroyWebSocket(),this.debugLog("WebSocket 连接已关闭")},t.isConnected=function(){var e;return this.connected&&(null==(e=this.websocket)?void 0:e.readyState)===WebSocket.OPEN},t.send=function(e){if(!this.websocket||!this.isConnected())return this.debugWarn("WebSocket is not connected, cannot send message"),!1;try{if("string"==typeof e)this.websocket.send(e),this.debugLog("WebSocket message sent (string):",e);else if(e instanceof ArrayBuffer||e instanceof Blob)this.websocket.send(e),this.debugLog("WebSocket message sent (binary):","ArrayBuffer/Blob ("+(e instanceof ArrayBuffer?e.byteLength:e.size)+" bytes)");else if(e instanceof Uint8Array||e instanceof Int8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Uint32Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof DataView)this.websocket.send(e),this.debugLog("WebSocket message sent (binary):","ArrayBufferView ("+e.byteLength+" bytes)");else{var t=JSON.stringify(e);this.websocket.send(t),this.debugLog("WebSocket message sent (JSON):",t)}return!0}catch(e){return this.debugError("Failed to send WebSocket message:",e),!1}},e}(),R=["protocol"],G=/*#__PURE__*/function(){function t(){}return t.createClient=function(t){var n=t.protocol,o=function(e,t){if(null==e)return{};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o]}return n}(t,R);switch(n){case e.ConnectionProtocol.SSE:return new P(o);case e.ConnectionProtocol.WEBSOCKET:return new O(o);default:throw new Error("Unsupported connection protocol: "+n)}},t}(),k=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.login=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.Login,method:"POST"}))}catch(e){return Promise.reject(e)}},n.logout=function(){try{return Promise.resolve(this.sdk.sendRequest({data:{},url:e.RequestApi.Logout,method:"POST"}))}catch(e){return Promise.reject(e)}},n.getChatMember=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({data:{chatId:t,parent:n},url:e.RequestApi.GetChatMember,method:"GET"}))}catch(e){return Promise.reject(e)}},t}(),A=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.sendMessage=function(e,t){try{var n=this;return Promise.resolve(function(o,r){try{var i=Promise.resolve(n.sdk.sendRequest({data:e,url:t,method:"POST"}))}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(e){throw console.error("Failed to send message",e),e}))}catch(e){return Promise.reject(e)}},n.getMessageApi=function(t,n){return n===e.GroupType.PrivateChat?e.RequestApi.PushPrivateMessage:n===e.GroupType.LiveGroup?e.RequestApi.PushLiveMessage:null!=t&&t.receiverName?e.RequestApi.PushMessageToMember:e.RequestApi.CreateTextMessage},n.createMessage=function(t,n,o,i,s){void 0===i&&(i={});var a={groupType:o};o===e.GroupType.PublicGroup||o===e.GroupType.PrivateGroup||o===e.GroupType.LiveGroup?a.groupId=n:a.receiverName=n;var c=r({},a,i,{msgType:t},s);return this.sendMessage(c,this.getMessageApi(a,o))},n.createTextMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.TEXT,n,o,r,{text:t}))}catch(e){return Promise.reject(e)}},n.createImageMessage=function(t,n,o,r,i){void 0===i&&(i={});try{return Promise.resolve(this.createMessage(e.MessageType.IMAGE,o,r,i,{link:t,snapshot:n}))}catch(e){return Promise.reject(e)}},n.createFileMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.FILE,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createAudioMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.AUDIO,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createVideoMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.VIDEO,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createLinkMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.LINK,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createGifMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.GIF,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createOptionMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.OPTION,n,o,r,{text:t}))}catch(e){return Promise.reject(e)}},n.createEmojiMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.EMOJI,n,o,r,{text:t}))}catch(e){return Promise.reject(e)}},n.createCustomMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.CUSTOM,n,o,r,{text:t}))}catch(e){return Promise.reject(e)}},n.getHistoryMessageList=function(t){var n=t.groupId,o=t.lastId,r=t.type,i=t.size,s=void 0===i?100:i;try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.GetHistoryMessageList,method:"POST",data:{groupId:n,lastId:o,type:r,size:s}}))}catch(e){return Promise.reject(e)}},n.getLiveMessageList=function(t){var n=t.groupId;try{var o;return Promise.resolve(this.sdk.sendRequest({data:{groupId:n},url:null!=(o=this.sdk.getConfig)&&o.anonLogin?e.RequestApi.GetAnonymousLiveMessageList:e.RequestApi.GetLiveMessageList,method:"POST"}))}catch(e){return Promise.reject(e)}},n.prePushCustomerMessage=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.PrePushCustomerMessage,method:"POST"}))}catch(e){return Promise.reject(e)}},t}(),I=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.getConversations=function(t){try{var n=this;return Promise.resolve(n.sdk.sendRequest({data:t,url:e.RequestApi.GetAllConversationList,method:"GET"})).then(function(e){return e.data.records=e.data.records.map(n.normalizeConversation),e})}catch(e){return Promise.reject(e)}},n.getChannels=function(t){try{var n=this;return Promise.resolve(n.sdk.sendRequest({data:t,url:e.RequestApi.GetChannels,method:"GET"})).then(function(e){return e.data.records=e.data.records.map(n.normalizeConversation),e})}catch(e){return Promise.reject(e)}},n.markConversationRead=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.MarkConversationMessageAsRead,method:"GET"}))}catch(e){return Promise.reject(e)}},n.markLastRead=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,msgId:n},url:e.RequestApi.MarkConversationMessageAsRead,method:"GET"}))}catch(e){return Promise.reject(e)}},n.pinConversation=function(t,n){void 0===n&&(n=1);try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,isTop:n},url:e.RequestApi.PinConversation,method:"GET"}))}catch(e){return Promise.reject(e)}},n.muteConversation=function(t,n){void 0===n&&(n=1);try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,mute:n},url:e.RequestApi.MuteConversation,method:"GET"}))}catch(e){return Promise.reject(e)}},n.normalizeConversation=function(e){var t,n,o,i,s,a,c,u,d;return r({},e,{id:e.id,name:e.name||"",groupType:e.groupType||0,avatar:e.avatar||"",status:null!=(t=e.status)?t:1,latest:null!=(n=e.latest)?n:{},unreadCount:null!=(o=e.unreadCount)?o:0,lastRead:e.lastRead,draftText:null!=(i=e.draftText)?i:"",custom:null!=(s=e.custom)?s:"",groupMemberId:null!=(a=e.groupMemberId)?a:"",pin:null!=(c=e.pin)&&c,supportId:e.supportId||"",supportNick:e.supportNick||"",identity:null!=(u=e.identity)?u:1,mute:null!=(d=e.mute)&&d})},t}(),L=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.getGroupInfo=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.GetGroupInfo,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getGroupMember=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.GetGroupMember,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getGroupMembers=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.GetGroupMembers,method:"GET"}))}catch(e){return Promise.reject(e)}},n.joinGroup=function(t){try{var n;return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:null!=(n=this.sdk.getConfig)&&n.anonLogin?e.RequestApi.AnonymousJoinGroup:e.RequestApi.JoinGroup,method:"GET"}))}catch(e){return Promise.reject(e)}},n.leftGroup=function(t){try{var n;return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:null!=(n=this.sdk.getConfig)&&n.anonLogin?e.RequestApi.AnonymousLeftGroup:e.RequestApi.LeftGroup,method:"GET"}))}catch(e){return Promise.reject(e)}},n.checkGroupBlock=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.CheckGroupBlock,method:"GET"}))}catch(e){return Promise.reject(e)}},n.updateLatestMessage=function(t){try{var n=Object.fromEntries(t.entries());return Promise.resolve(this.sdk.sendRequest({data:{latestMessage:n},url:e.RequestApi.UpdateLatestMessage,method:"POST"}))}catch(e){return Promise.reject(e)}},n.getGroupLatestMessage=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groups:t},url:e.RequestApi.GetLatestGroupChats,method:"POST"}))}catch(e){return Promise.reject(e)}},n.checkGroupLatestMessage=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{ttl:t},url:e.RequestApi.CheckLatestMessages,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getMyGroupPermission=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.GetMyGroupPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getGroupPermission=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.GetGroupPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getGroupMemberPermission=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,targetMemberId:n},url:e.RequestApi.GetGroupMemberPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},n.updateGroupPermission=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.UpdateGroupPermission,method:"POST"}))}catch(e){return Promise.reject(e)}},n.updateGroupMemberPermission=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.UpdateGroupMemberPermission,method:"POST"}))}catch(e){return Promise.reject(e)}},n.kickGroupMember=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.kickGroupMember,method:"POST"}))}catch(e){return Promise.reject(e)}},n.muteMembers=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.muteMembers,method:"POST"}))}catch(e){return Promise.reject(e)}},n.editGroupName=function(t,n,o){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.editeGroupName,method:"GET",data:{groupId:t,name:n,avatar:o}}))}catch(e){return Promise.reject(e)}},n.editNotification=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.editeNotification,method:"GET",data:{groupId:t,notification:n}}))}catch(e){return Promise.reject(e)}},n.editGroupCustomer=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.editeGroupCustomer,method:"GET",data:{groupId:t,customer:n}}))}catch(e){return Promise.reject(e)}},n.addAdmin=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.addAdmin,method:"GET",data:{groupId:t,username:n}}))}catch(e){return Promise.reject(e)}},n.deleteAdmin=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.deleteAdmin,method:"GET",data:{groupId:t,username:n}}))}catch(e){return Promise.reject(e)}},n.dissolveGroup=function(t){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.DissolveGroup,method:"GET",data:{groupId:t}}))}catch(e){return Promise.reject(e)}},n.pin=function(t,n,o){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.pin,method:"GET",data:{groupId:t,messageId:n,type:o}}))}catch(e){return Promise.reject(e)}},n.muteGroup=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.muteGroup,method:"GET",data:{groupId:t,type:n}}))}catch(e){return Promise.reject(e)}},n.muteMember=function(t,n,o){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.muteMember,method:"GET",data:{groupId:t,username:n,type:o}}))}catch(e){return Promise.reject(e)}},n.addGroupMembers=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.AddGroupMembers,method:"POST"}))}catch(e){return Promise.reject(e)}},n.getFileByType=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.GetFileByType,method:"GET"}))}catch(e){return Promise.reject(e)}},n.pinChat=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,type:n},url:e.RequestApi.PinChat,method:"GET"}))}catch(e){return Promise.reject(e)}},t}(),U=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.getContactByType=function(t,n){try{var o={contactType:t};return void 0!==n&&(o.groupId=n),Promise.resolve(this.sdk.sendRequest({data:o,url:e.RequestApi.GetContactByType,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getMemberContacts=function(t){try{return Promise.resolve(this.getContactByType(e.ContactType.MEMBER,t))}catch(e){return Promise.reject(e)}},n.getColleagueContacts=function(t){try{return Promise.resolve(this.getContactByType(e.ContactType.COLLEAGUE,t))}catch(e){return Promise.reject(e)}},n.getGroupContacts=function(t){try{return Promise.resolve(this.getContactByType(e.ContactType.GROUP,t))}catch(e){return Promise.reject(e)}},n.editContactTag=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.EditContactTag,method:"POST"}))}catch(e){return Promise.reject(e)}},n.getContactTag=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{contactType:t},url:e.RequestApi.GetContactTag,method:"GET"}))}catch(e){return Promise.reject(e)}},n.allocationContactTag=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.AllocationContactTag,method:"POST"}))}catch(e){return Promise.reject(e)}},n.allocationMemberTag=function(t,n,o){void 0===o&&(o=0);try{return Promise.resolve(this.allocationContactTag({contactType:e.ContactType.MEMBER,tag:t,groupIds:n,type:o}))}catch(e){return Promise.reject(e)}},n.allocationColleagueTag=function(t,n,o){void 0===o&&(o=0);try{return Promise.resolve(this.allocationContactTag({contactType:e.ContactType.COLLEAGUE,tag:t,groupIds:n,type:o}))}catch(e){return Promise.reject(e)}},n.allocationGroupTag=function(t,n,o){void 0===o&&(o=0);try{return Promise.resolve(this.allocationContactTag({contactType:e.ContactType.GROUP,tag:t,groupIds:n,type:o}))}catch(e){return Promise.reject(e)}},t}(),N=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.services={},this.sdk=e}var n=t.prototype;return n.get=function(e){return this.services[e]||(this.services[e]=this.createService(e)),this.services[e]},n.createService=function(t){switch(t){case e.ServiceName.USER:return new k(this.sdk);case e.ServiceName.MESSAGE:return new A(this.sdk);case e.ServiceName.CONVERSATION:return new I(this.sdk);case e.ServiceName.GROUP:return new L(this.sdk);case e.ServiceName.CONTACT:return new U(this.sdk);default:throw new Error("Unknown service: "+t)}},n.reset=function(){this.services={}},t}();function _(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var w=[e.RequestApi.Logout,e.CbEvents.OnKickedOffline,e.CbEvents.OnUserTokenInvalid,e.CbEvents.OnUserTokenExpired];e.SIMSDK=/*#__PURE__*/function(t){function n(n){var o;return void 0===n&&(n=!1),(o=t.call(this)||this).config={debug:!1,isLive:!1,useProtobuf:!1,protocol:e.ConnectionProtocol.SSE},o.internalState={isConnected:!1,isLoggedIn:!1,reconnectAttempts:0,lastActivity:Date.now()},o.cacheManager=void 0,o.connectionClient=void 0,o.serviceManager=void 0,o.lastUnauthorizedTime=0,o.UNAUTHORIZED_THROTTLE_MS=3e3,o.conversationUpdateTimer=null,o.CONVERSATION_UPDATE_THROTTLE_MS=500,o.pendingConversationUpdate=!1,o.lastConversationUpdateTime=0,o.isPageVisible=!0,o.pageVisibilityHandler=null,o.PAGE_HIDDEN_STOP_DELAY_MS=3e3,o.pageHiddenTimer=null,o.isActuallyHidden=!1,o.PAGE_VISIBLE_STABLE_MS=1e3,o.pageVisibleStableTimer=null,o.configure=function(e){void 0!==e.debug&&(o.config.debug=e.debug),e.isLive&&(o.config.isLive=e.isLive),e.apiAddr&&(o.config.apiAddr=e.apiAddr),e.wsAddr&&(o.config.wsAddr=e.wsAddr),e.ossApiAddr&&(o.config.ossApiAddr=e.ossApiAddr),e.appKey&&(o.config.appKey=e.appKey),e.token&&(o.config.token=e.token),e.connectTimeout&&(o.config.connectTimeout=e.connectTimeout),e.maxRetries&&(o.config.maxRetries=e.maxRetries),e.useProtobuf&&(o.config.useProtobuf=e.useProtobuf),e.protocol&&(o.config.protocol=e.protocol)},o.sendRequest=function(e){try{o.internalState.lastActivity=Date.now(),o.config.debug&&o.logRequest(e);var t=o.config.apiAddr+e.url,n=e.data;if("GET"===e.method&&n){var r=new URLSearchParams;Object.entries(n).forEach(function(e){var t=e[1];null!=t&&r.append(e[0],String(t))});var i=r.toString();i&&(t+=(t.includes("?")?"&":"?")+i),n=void 0}return Promise.resolve(_(function(){return Promise.resolve(function(e){try{var t,n=function(e){if(t)return e;throw new Error("Unsupported platform")},o=function(){if(b){var n=new Promise(function(t,n){uni.request({url:e.url,method:e.method||"GET",header:e.headers,data:e.data,success:function(e){401!==e.statusCode?t(e.data):n({status:401,message:"Unauthorized"})},fail:function(e){return n(e)}})});return t=1,n}return function(){if(S)return Promise.resolve(fetch(e.url,{method:e.method||"GET",headers:e.headers,body:e.data?JSON.stringify(e.data):null})).then(function(e){if(401===e.status)throw{status:401,message:"Unauthorized"};return Promise.resolve(e.json()).then(function(e){return t=1,e})})}()}();return Promise.resolve(o&&o.then?o.then(n):n(o))}catch(e){return Promise.reject(e)}}({url:t,method:e.method,headers:{"Content-Type":"application/json",Authorization:o.config.token?"Bearer "+o.config.token:""},data:n}))},function(e){throw 401!==(null==e?void 0:e.status)&&401!==(null==e?void 0:e.statusCode)||o.handleUnauthorizedWithThrottle(t),e}))}catch(e){return Promise.reject(e)}},o.handleUnauthorizedWithThrottle=function(e){var t=Date.now();t-o.lastUnauthorizedTime<o.UNAUTHORIZED_THROTTLE_MS?console.warn("401错误被节流限制,跳过处理:"+e):(o.lastUnauthorizedTime=t,o.handleUnauthorized(e))},o.handleUnauthorized=function(e){console.warn("未授权请求(401):",e),o.handleConnectionClosed(!0)},o.createRequestFunction=function(e,t){return function(n){return o.sendRequest({data:n,url:e,method:t})}},o.createRequestFunctionWithoutParams=function(e,t){return function(){return o.sendRequest({data:void 0,method:t,url:e})}},o.handleMessage=function(e){o.config.debug&&console.log("[SDK] handleMessage response",e),o.isProtobufFormat(e)?o.handleProtobufMessage(e):o.handleJsonMessage(e)},o.handleJsonMessage=function(t){switch(o.config.debug&&console.log("handleMessage response",t),t.ev){case e.SseEventType.EVENT_MESSAGE_PUSH:var n=t.dt;Array.isArray(n)?(n.forEach(function(e){o.updateMessageCache(e)}),o.emit(e.CbEvents.OnReceiveMessages,n)):console.warn("[SDK] Expected response.dt to be an array, but got:",n);break;case e.SseEventType.EVENT_PONG_IDLE:o.internalState.isConnected=!0;break;case e.SseEventType.EVENT_SYSTEM_MESSAGE_PUSH:o.emit(e.CbEvents.OnReceiveSystemMessage,t.dt);break;case e.SseEventType.EVENT_PRE_MESSAGE_PUSH:o.emit(e.CbEvents.OnReceivePreMessage,t.dt);break;case e.SseEventType.EVENT_SUBSCRIBE_MESSAGE_PUSH:o.emit(e.CbEvents.OnReceiveSubscribeMessage,t.dt);break;default:r=t.ev,Object.values(e.CbEvents).includes(r)?(o.emit(t.ev,t.dt),w.includes(t.ev)&&(o.internalState.isLoggedIn=!1,o.internalState.isConnected=!1,o.connectionClient&&(o.connectionClient.close(),o.connectionClient=void 0))):o.config.debug&&console.warn("[SDK] Unknown SSE event type:",t.ev)}var r},o.handleReconnectSuccess=function(){o.config.username&&(o.internalState.isConnected=!0,o.internalState.reconnectAttempts=0,o.config.debug&&console.log("SSE reconnection successful"),o.emit(e.CbEvents.OnReconnected))},o.handleConnectionClosed=function(t){o.internalState.isConnected=!1,o.config.debug&&console.log("SSE connection closed"),o.emit(e.CbEvents.OnDisconnected,t)},o.handleMaxRetriesReached=function(){o.config.debug&&console.log("SSE connection max reconnection attempts reached"),o.emit(e.CbEvents.onMaxRetriesReached)},o.handleConnectionChange=function(t){o.config.debug&&console.log("Connection status changed:",t),o.emit(t?e.CbEvents.OnConnected:e.CbEvents.OnDisconnected)},o.login=function(t){try{var n,i,s=function(r){return n?r:(o.connectionClient=G.createClient({url:o.config.wsAddr+"/"+(t.anonLogin?"anonymousConn":"conn")+"?username="+t.username+"&token="+t.token+"&appKey="+o.config.appKey+"&random="+i,protocol:o.config.protocol||e.ConnectionProtocol.WEBSOCKET,debug:o.config.debug,onMessage:o.handleMessage,onReconnectSuccess:o.handleReconnectSuccess,onConnectionClosed:o.handleConnectionClosed,onMaxRetriesReached:o.handleMaxRetriesReached,onConnectionChange:o.handleConnectionChange,token:t.token,connectTimeout:o.config.connectTimeout,maxRetries:o.config.maxRetries}),_(function(){return Promise.resolve(o.connectionClient.connect()).then(function(e){return o.internalState.isLoggedIn=!0,o.internalState.isConnected=!0,o.config.isLive||o.initializeConversationCache(),e})},function(e){return o.internalState.isLoggedIn=!1,o.internalState.isConnected=!1,Promise.reject(e.message)}))};if(o.connectionClient&&(null==o.connectionClient.close||o.connectionClient.close(),o.connectionClient=void 0,o.internalState.isLoggedIn=!1,o.internalState.isConnected=!1),!o.config.apiAddr)return Promise.reject("No apiAddr configured. Please call configure() before login().");if(!o.config.ossApiAddr)return Promise.reject("No ossApiAddr configured. Please call configure() before login().");if(!o.config.appKey)return Promise.reject("No appKey configured. Please call configure() before login().");if(!o.config.token)return Promise.reject("No token configured. Please call configure() before login().");if(o.config.username=t.username,o.config.anonLogin=t.anonLogin||!1,t.protocol&&(o.config.protocol=t.protocol),t.protocol==e.ConnectionProtocol.WEBSOCKET&&!o.config.wsAddr)return Promise.reject("WebSocket address (wsAddr) is not configured. Please call configure() before login().");if(o.config.debug&&(console.log("login params",t),console.log("apiAddr",o.config.apiAddr)),!o.config.isLive||!t.anonLogin){o.cacheManager.initialize(t.username),o.cacheManager.resetActiveConversation();var a=o.cacheManager.getConversations();a.length>0&&o.emit(e.CbEvents.OnConversationListUpdated,a)}var c=function(){if(!t.anonLogin)return Promise.resolve(o.user.login(r({},t,{appKey:o.config.appKey}))).then(function(e){var t=e.code,o=e.data;if(0!=t){var r=Promise.resolve("Login failed, Server error, error code is "+t);return n=1,r}i=o})}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},o.logout=function(){try{return o.connectionClient&&(o.connectionClient.close(),o.connectionClient=void 0),Promise.resolve(o.user.logout()).then(function(e){return o.internalState.isLoggedIn=!1,o.internalState.isConnected=!1,o.config.username=void 0,o.config.token=void 0,o.cacheManager.clear(),e})}catch(e){return Promise.reject(e)}},o.getChatMember=function(e,t){return o.user.getChatMember(e,t)},o.getConversations=function(t){try{return Promise.resolve(_(function(){var n=t.pageNo||1,r=t.pageSize||50;return n<1?(console.warn("[SDK] Invalid pageNo, must be >= 1"),{code:-1,msg:"Invalid pageNo, must be >= 1",data:{records:[],current:1,pages:0}}):r<1||r>100?(console.warn("[SDK] Invalid pageSize, must be between 1 and 100"),{code:-1,msg:"Invalid pageSize, must be between 1 and 100",data:{records:[],current:1,pages:0}}):Promise.resolve(o.conversation.getConversations({pageNo:n,pageSize:r})).then(function(t){var r=t.data;if(0===t.code&&r){var i=o.cacheManager.getConversations();if(1===n)o.cacheManager.setConversations([].concat(r.records),!0);else{var s=r.records||[],a=new Map;i.forEach(function(e){a.set(e.id,e)});var c=[],u=[];s.forEach(function(e){a.has(e.id)?c.push(e):u.push(e)});var d=[];i.forEach(function(e){c.find(function(t){return t.id===e.id})||d.push(e)}),d.push.apply(d,c.concat(u)),o.cacheManager.setConversations(d,!1)}o.emit(e.CbEvents.OnConversationListUpdated,o.cacheManager.getConversations())}else{var l=o.cacheManager.getConversations();l.length>0&&o.emit(e.CbEvents.OnConversationListUpdated,l)}return t})},function(n){console.error("[SDK] Failed to get conversations:",n);var r=o.cacheManager.getConversations();return r.length>0&&o.emit(e.CbEvents.OnConversationListUpdated,r),{code:-1,msg:n instanceof Error?n.message:"Failed to get conversations",data:{records:r,current:t.pageNo||1,pages:0}}}))}catch(e){return Promise.reject(e)}},o.internalUploadFile=function(t,n){try{return Promise.resolve(_(function(){var r=""+o.config.apiAddr+e.RequestApi.UploadCredential+"?groupId="+n+"&filename="+encodeURIComponent(t.name);return Promise.resolve(fetch(r,{method:"GET",headers:{Authorization:o.config.token?"Bearer "+o.config.token:""}})).then(function(e){if(!e.ok)throw new Error("Get upload credential failed: "+e.status);return Promise.resolve(e.json()).then(function(e){var n=(null==e?void 0:e.data)||{};if(null==e||!e.success||null==n||!n.uploadUrl||null==n||!n.accessUrl)throw new Error((null==e?void 0:e.msg)||"Invalid upload credential response");var o=n.accessUrl;return Promise.resolve(fetch(n.uploadUrl,{method:"PUT",headers:{"Content-Type":t.type||"application/octet-stream"},body:t})).then(function(e){var r;if(!e.ok)throw new Error("Upload to OSS failed with status: "+e.status);var i=null!=(r=n.thumbnailUrl)?r:t.type.startsWith("image/")?o+(o.includes("?")?"&":"?")+"x-oss-process=image/resize,m_lfit,w_200,h_200":"";return{originalUrl:o,thumbnailUrl:i}})})})},function(e){return console.error("[Upload Error]",e),{error:e instanceof Error?e:new Error("Unknown upload error")}}))}catch(e){return Promise.reject(e)}},o.uploadFile=function(t,n){var r=t.file;try{return Promise.resolve(o.internalUploadFile(r,n)).then(function(t){var n,o=t.originalUrl,r=t.thumbnailUrl,i=t.error;return{data:{originalUrl:void 0===o?"":o,thumbnailUrl:void 0===r?"":r},msg:null!=(n=null==i?void 0:i.message)?n:"",code:i?e.ErrorCode.UnknownError:0}})}catch(e){return Promise.reject(e)}},o.sendTextMessage=function(e,t,n,r){return o.message.createTextMessage(e,t,n,r)},o.sendImageMessage=function(e,t,n,r,i){return o.message.createImageMessage(e,t,n,r,i)},o.sendFileMessage=function(e,t,n,r){return o.message.createFileMessage(e,t,n,r)},o.sendAudioMessage=function(e,t,n,r){return o.message.createAudioMessage(e,t,n,r)},o.sendVideoMessage=function(e,t,n,r){return o.message.createVideoMessage(e,t,n,r)},o.sendLinkMessage=function(e,t,n,r){return o.message.createLinkMessage(e,t,n,r)},o.sendGifMessage=function(e,t,n,r){return o.message.createGifMessage(e,t,n,r)},o.sendOptionMessage=function(e,t,n,r){return o.message.createOptionMessage(e,t,n,r)},o.sendEmojiMessage=function(e,t,n,r){return o.message.createEmojiMessage(e,t,n,r)},o.sendCustomMessage=function(e,t,n,r){return o.message.createCustomMessage(e,t,n,r)},o.getHistoryMessageList=function(e){try{return Promise.resolve(o.message.getHistoryMessageList(e))}catch(e){return Promise.reject(e)}},o.getLiveMessageList=function(e){return o.message.getLiveMessageList(e)},o.prePushCustomerMessage=function(e){return o.message.prePushCustomerMessage(e)},o.getGroupInfo=function(e){return o.group.getGroupInfo(e)},o.getGroupMembers=function(e){return o.group.getGroupMembers(e)},o.joinGroup=function(e){return o.group.joinGroup(e)},o.leftGroup=function(e){return o.group.leftGroup(e)},o.checkGroupBlock=function(e){return o.group.checkGroupBlock(e)},o.getMyGroupPermission=function(e){return o.group.getMyGroupPermission(e)},o.getGroupPermission=function(e){return o.group.getGroupPermission(e)},o.getGroupMember=function(e){return o.group.getGroupMember(e)},o.getGroupMemberPermission=function(e,t){return o.group.getGroupMemberPermission(e,t)},o.updateGroupPermission=function(e){return o.group.updateGroupPermission(e)},o.kickGroupMember=function(e){return o.group.kickGroupMember(e)},o.muteMembers=function(e){return o.group.muteMembers(e)},o.updateGroupMemberPermission=function(e){return o.group.updateGroupMemberPermission(e)},o.editGroupName=function(t,n,r){try{return Promise.resolve(o.group.editGroupName(t,n,r)).then(function(i){if(0===i.code){var s=o.cacheManager.getConversations().find(function(e){return e.id===t});if(s){s.name=n,s.avatar=r,o.cacheManager.updateConversation(s);var a=o.cacheManager.getConversations();o.emit(e.CbEvents.OnConversationListUpdated,a)}}return i})}catch(e){return Promise.reject(e)}},o.editNotification=function(e,t){return o.group.editNotification(e,t)},o.editGroupCustomer=function(e,t){return o.group.editGroupCustomer(e,t)},o.addAdmin=function(e,t){return o.group.addAdmin(e,t)},o.deleteAdmin=function(e,t){return o.group.deleteAdmin(e,t)},o.pin=function(e,t,n){return o.group.pin(e,t,n)},o.muteGroup=function(e,t){return o.group.muteGroup(e,t)},o.muteMember=function(e,t,n){return o.group.muteMember(e,t,n)},o.addGroupMembers=function(e){return o.group.addGroupMembers(e)},o.getFileByType=function(e){return o.group.getFileByType(e)},o.pinChat=function(e,t){return o.group.pinChat(e,t)},o.dissolveGroup=function(e){return o.group.dissolveGroup(e)},o.markConversationRead=function(t){try{return Promise.resolve(o.conversation.markConversationRead(t)).then(function(n){if(0===n.code&&t.groupId){t.id?o.cacheManager.updateConversationLastRead(t.groupId,t.id):o.cacheManager.clearConversationUnread(t.groupId);var r=o.cacheManager.getConversations();o.emit(e.CbEvents.OnConversationListUpdated,r)}return n})}catch(e){return Promise.reject(e)}},o.markLastRead=function(t,n){try{return Promise.resolve(o.conversation.markLastRead(t,n)).then(function(r){if(0===r.code){o.cacheManager.updateConversationLastRead(t,n);var i=o.cacheManager.getConversations();o.emit(e.CbEvents.OnConversationListUpdated,i)}return r})}catch(e){return Promise.reject(e)}},o.markLastReadLocal=function(t,n){o.cacheManager.updateConversationLastRead(t,n);var r=o.cacheManager.getConversations();o.emit(e.CbEvents.OnConversationListUpdated,r)},o.pinConversation=function(t,n){void 0===n&&(n=1);try{return Promise.resolve(o.conversation.pinConversation(t,n)).then(function(r){if(0===r.code){o.cacheManager.updateConversationPinStatus(t,1===n);var i=o.cacheManager.getConversations();o.emit(e.CbEvents.OnConversationListUpdated,i)}return r})}catch(e){return Promise.reject(e)}},o.muteConversation=function(e,t){return void 0===t&&(t=1),o.conversation.muteConversation(e,t)},o.getChannels=function(e){return o.conversation.getChannels(e)},o.clearConversationUnread=function(t){o.cacheManager.clearConversationUnread(t);var n=o.cacheManager.getConversations();o.emit(e.CbEvents.OnConversationListUpdated,n)},o.clearAllConversationUnread=function(){o.cacheManager.clearAllConversationUnread();var t=o.cacheManager.getConversations();o.emit(e.CbEvents.OnConversationListUpdated,t)},o.getContactByType=function(e,t){return o.contact.getContactByType(e,t)},o.getMemberContacts=function(e){return o.contact.getMemberContacts(e)},o.getColleagueContacts=function(e){return o.contact.getColleagueContacts(e)},o.getGroupContacts=function(e){return o.contact.getGroupContacts(e)},o.editContactTag=function(e){return o.contact.editContactTag(e)},o.getContactTag=function(e){return o.contact.getContactTag(e)},o.allocationContactTag=function(e){return o.contact.allocationContactTag(e)},o.allocationMemberTag=function(e,t,n){return void 0===n&&(n=0),o.contact.allocationMemberTag(e,t,n)},o.allocationColleagueTag=function(e,t,n){return void 0===n&&(n=0),o.contact.allocationColleagueTag(e,t,n)},o.allocationGroupTag=function(e,t,n){return void 0===n&&(n=0),o.contact.allocationGroupTag(e,t,n)},o.config.debug=n,n&&(console.log("🚀 SIM SDK Web v1.1.0 (本地开发版本)"),console.log("📦 支持协议: SSE, WebSocket")),o.cacheManager=new y({persistEnabled:!0,debug:n}),o.serviceManager=new N(o),o.initPageVisibilityDetection(),o}var o,a;a=t,(o=n).prototype=Object.create(a.prototype),o.prototype.constructor=o,i(o,a);var c,u,d=n.prototype;return d.initPageVisibilityDetection=function(){var e=this;"undefined"!=typeof document&&(this.isPageVisible=!document.hidden,this.isActuallyHidden=!this.isPageVisible,this.pageVisibilityHandler=function(){var t=e.isPageVisible;e.isPageVisible=!document.hidden,e.config.debug&&console.log("[SDK] Page visibility changed: "+(e.isPageVisible?"visible":"hidden")),t&&!e.isPageVisible?e.handlePageHidden():!t&&e.isPageVisible&&e.handlePageVisible()},document.addEventListener("visibilitychange",this.pageVisibilityHandler))},d.handlePageHidden=function(){var e=this;null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null),null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),this.pageHiddenTimer=window.setTimeout(function(){e.isPageVisible||(e.isActuallyHidden=!0,e.config.debug&&console.log("[SDK] Page is actually hidden, stopping conversation updates")),e.pageHiddenTimer=null},this.PAGE_HIDDEN_STOP_DELAY_MS)},d.handlePageVisible=function(){var e=this;null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),this.isActuallyHidden=!1,null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null),this.pageVisibleStableTimer=window.setTimeout(function(){e.isPageVisible&&e.pendingConversationUpdate&&(e.config.debug&&console.log("[SDK] Page is stable visible, triggering conversation update"),e.flushConversationUpdate()),e.pageVisibleStableTimer=null},this.PAGE_VISIBLE_STABLE_MS)},d.cleanupPageVisibilityDetection=function(){this.pageVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.pageVisibilityHandler),this.pageVisibilityHandler=null),null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null)},d.destroy=function(){this.connectionClient&&(this.connectionClient.close(),this.connectionClient=void 0),this.cacheManager.destroy(),this.cleanupPageVisibilityDetection(),null!==this.conversationUpdateTimer&&(clearTimeout(this.conversationUpdateTimer),this.conversationUpdateTimer=null),this.internalState={isConnected:!1,isLoggedIn:!1,reconnectAttempts:0,lastActivity:Date.now()},this.config.debug&&console.log("[SDK] Resources destroyed")},d.getService=function(e){return this.serviceManager.get(e)},d.isConnected=function(){return this.config.debug&&console.log("[SDK] Connection status: "+(this.internalState.isConnected?"connected":"disconnected")),this.internalState.isConnected},d.isLoggedIn=function(){return this.config.debug&&console.log("[SDK] Login status: "+(this.internalState.isLoggedIn?"logged in":"not logged in")),this.internalState.isLoggedIn},d.logRequest=function(e){var t=Math.random().toString(36).substring(2,8),n={GET:"#4CAF50",POST:"#2196F3",PUT:"#FF9800",DELETE:"#F44336"}[e.method]||"#9C27B0",o={GET:"🔍",POST:"📝",PUT:"🔄",DELETE:"🗑️"}[e.method]||"📡";console.log("%c "+(new Date).toISOString().substring(11,19)+" %c SDK %c "+o+" "+e.method+" %c "+e.url+" %c #"+t,"color: #888; font-size: 11px; padding: 2px 0;","background: #7CAEFF; color: white; font-weight: bold; font-size: 12px; border-radius: 4px; padding: 2px 6px; margin: 0 4px;","background: "+n+"; color: white; font-weight: bold; font-size: 12px; border-radius: 4px; padding: 2px 6px; margin: 0 4px;","color: #0066cc; font-weight: bold;","color: #888; font-style: italic;"),e.data&&Object.keys(e.data).length>0&&(console.log("%c─── 📦 Request Payload ───────────────────────────────","color: #999; font-style: italic;"),console.log("%c%s","color: #333; background: #f8f8f8; padding: 8px; border-radius: 4px; border-left: 4px solid #7CAEFF; font-family: monospace; line-height: 1.5;",JSON.stringify(e.data,null,2)),console.log("%c─────────────────────────────────────────────────────","color: #999;"))},d.handlePongMessage=function(e){e&&e.timestamp&&(this.config.debug&&console.log("[SDK] Received pong message with timestamp:",e.timestamp),this.internalState.isConnected=!0,this.internalState.lastActivity=Date.now())},d.isProtobufFormat=function(e){return this.config.useProtobuf||"string"==typeof e&&this.isBase64String(e)||e instanceof Uint8Array},d.isBase64String=function(e){try{return btoa(atob(e))===e}catch(e){return!1}},d.handleProtobufMessage=function(t){this.emit(e.CbEvents.OnReceiveProtoMessage,t)},d.initializeConversationCache=function(){try{var t=this,n=_(function(){return Promise.resolve(t.conversation.getConversations({pageNo:1,pageSize:50})).then(function(n){var o=n.code,r=n.data;if(t.config.debug&&console.log("[SDK] Initialize conversation cache:",o,r),0===o&&r&&r.records){t.cacheManager.setConversations(r.records,!0);var i=t.cacheManager.getConversations();t.emit(e.CbEvents.OnConversationListUpdated,i),t.config.debug&&console.log("[SDK] Conversation cache initialized with",r.records.length,"conversations")}})},function(e){console.error("[SDK] Failed to initialize conversation cache:",e)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},d.onMessage=function(t){var n=this;return this.on(e.CbEvents.OnReceiveMessage,t),function(){return n.off(e.CbEvents.OnReceiveMessage,t)}},d.onMessages=function(t){var n=this;return this.on(e.CbEvents.OnReceiveMessages,t),function(){return n.off(e.CbEvents.OnReceiveMessages,t)}},d.onConnectionChange=function(t){var n=this,o=function(){return t(!0)},r=function(){return t(!1)};return this.on(e.CbEvents.OnConnected,o),this.on(e.CbEvents.OnDisconnected,r),function(){n.off(e.CbEvents.OnConnected,o),n.off(e.CbEvents.OnDisconnected,r)}},d.onKickedOffline=function(t){var n=this;return this.on(e.CbEvents.OnKickedOffline,t),function(){return n.off(e.CbEvents.OnKickedOffline,t)}},d.updateMessageCache=function(e){e.groupId&&this.cacheManager.addGroupMessage(e),this.cacheManager.updateConversationWithMessage(e,this.config.username)&&this.scheduleConversationUpdate()},d.scheduleConversationUpdate=function(){var e=this;if(this.pendingConversationUpdate=!0,this.isActuallyHidden)this.config.debug&&console.log("[SDK] Page is actually hidden, deferring conversation update");else{var t=Date.now()-this.lastConversationUpdateTime;if(t<this.CONVERSATION_UPDATE_THROTTLE_MS){if(null!==this.conversationUpdateTimer)return;this.conversationUpdateTimer=window.setTimeout(function(){e.flushConversationUpdate()},this.CONVERSATION_UPDATE_THROTTLE_MS-t)}else this.flushConversationUpdate()}},d.flushConversationUpdate=function(){null!==this.conversationUpdateTimer&&(clearTimeout(this.conversationUpdateTimer),this.conversationUpdateTimer=null),this.pendingConversationUpdate=!1,this.lastConversationUpdateTime=Date.now();var t=this.cacheManager.getConversations();this.emit(e.CbEvents.OnConversationListUpdated,t),this.config.debug&&console.log("[SDK] Conversation list updated, count:",t.length)},d.getCachedGroupMessages=function(e){return this.cacheManager.getGroupMessages(e)},c=n,(u=[{key:"message",get:function(){return this.getService(e.ServiceName.MESSAGE)}},{key:"conversation",get:function(){return this.getService(e.ServiceName.CONVERSATION)}},{key:"group",get:function(){return this.getService(e.ServiceName.GROUP)}},{key:"user",get:function(){return this.getService(e.ServiceName.USER)}},{key:"contact",get:function(){return this.getService(e.ServiceName.CONTACT)}},{key:"username",get:function(){return this.config.username}},{key:"getConfig",get:function(){return this.config}},{key:"getConnectionClient",get:function(){return this.connectionClient}},{key:"uuid",get:function(){return(36*Math.random()).toString(36).slice(2)+(new Date).getTime().toString()}}])&&function(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,s(o.key),o)}}(c.prototype,u),Object.defineProperty(c,"prototype",{writable:!1}),c}(C)});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("event-source-polyfill"),require("protobufjs")):"function"==typeof define&&define.amd?define(["exports","event-source-polyfill","protobufjs"],t):t((e||self).simSdkWeb={},e.eventSourcePolyfill,e.protobufjs)}(this,function(e,t,n){function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r,s,i,a,c,u=/*#__PURE__*/o(n);function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function l(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return d(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?d(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function g(){return g=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},g.apply(null,arguments)}function h(e,t){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},h(e,t)}function p(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}e.ServiceName=void 0,(r=e.ServiceName||(e.ServiceName={})).MESSAGE="message",r.CONVERSATION="conversation",r.GROUP="group",r.USER="user",r.CONTACT="contact",e.ContactType=void 0,(s=e.ContactType||(e.ContactType={}))[s.MEMBER=0]="MEMBER",s[s.COLLEAGUE=1]="COLLEAGUE",s[s.GROUP=2]="GROUP",e.ErrorCode=void 0,(i=e.ErrorCode||(e.ErrorCode={}))[i.UnknownError=10005]="UnknownError",e.RequestApi=void 0,(a=e.RequestApi||(e.RequestApi={})).Login="/chat/member/login",a.Logout="/chat/member/logout",a.GetChatMember="/chat/member/getChatMember",a.GetGroupInfo="/chat/group/groupInfo",a.GetGroupMembers="/chat/group/groupMembers",a.JoinGroup="/chat/group/joinGroup",a.LeftGroup="/chat/group/leftGroup",a.AnonymousJoinGroup="/chat/group/anonymousJoinGroup",a.AnonymousLeftGroup="/chat/group/anonymousLeftGroup",a.CheckGroupBlock="/chat/group/checkBlock",a.GetMyGroupPermission="/chat/group/permission/getPermission",a.GetGroupPermission="/chat/group/permission/groupPermission",a.GetGroupMember="/chat/group/groupMember",a.GetGroupMemberPermission="/chat/group/permission/groupMemberPermission",a.UpdateGroupPermission="/chat/group/permission/updateGroupPermission",a.UpdateGroupMemberPermission="/chat/group/permission/updateGroupMemberPermission",a.editeGroupName="/chat/group/operation/editeGroupName",a.editeNotification="/chat/group/operation/editeNotification",a.editeGroupCustomer="/chat/group/operation/editeGroupCustomer",a.addAdmin="/chat/group/operation/addAdmin",a.deleteAdmin="/chat/group/operation/deleteAdmin",a.pin="/chat/group/operation/pin",a.muteGroup="/chat/group/operation/muteGroup",a.muteMember="/chat/group/operation/muteMember",a.kickGroupMember="/chat/group/operation/kickGroupMember",a.muteMembers="/chat/group/operation/muteMembers",a.DissolveGroup="/chat/group/dissolve",a.GetAllConversationList="/chat/conversation/conversationList",a.GetChannels="/chat/conversation/getChannels",a.MarkConversationMessageAsRead="/chat/conversation/lastRead",a.PinConversation="/chat/conversation/pinChat",a.MuteConversation="/chat/conversation/mute",a.UpdateLatestMessage="/chat/group/updateLatestMessage",a.GetLatestGroupChats="/chat/group/latestGroupChats",a.CheckLatestMessages="/chat/group/checkLatestMessages",a.CreateTextMessage="/chat/message/push",a.PushMessageToMember="/chat/message/push2Member",a.PushPrivateMessage="/chat/message/pushPrivateMessage",a.PushLiveMessage="/chat/message/liveGroupPush",a.GetHistoryMessageList="/chat/message/pull",a.GetLiveMessageList="/chat/message/liveGroupPull",a.GetAnonymousLiveMessageList="/chat/message/anonymousLiveGroupPull",a.PrePushCustomerMessage="/chat/message/prePushCustomerMessage",a.UploadFile="/chat/img/upload",a.UploadCredential="/chat/img/uploadCredential",a.GetContactByType="/chat/contact/contactByType",a.EditContactTag="/chat/contact/editeContactTag",a.GetContactTag="/chat/contact/getContactTag",a.AllocationContactTag="/chat/contact/allocationContactTag",a.AddGroupMembers="/chat/group/operation/addGroupMembers",a.GetFileByType="/chat/message/getFileByType",a.PinChat="/chat/member/pinChat",e.CbEvents=void 0,(c=e.CbEvents||(e.CbEvents={})).OnConnected="OnConnected",c.OnDisconnected="OnDisconnected",c.onMaxRetriesReached="onMaxRetriesReached",c.OnReconnecting="OnReconnecting",c.OnReconnected="OnReconnected",c.OnReconnectFailed="OnReconnectFailed",c.OnNetworkChange="OnNetworkChange",c.OnReceiveMessage="OnReceiveMessage",c.OnReceiveProtoMessage="OnReceiveProtoMessage",c.OnReceiveMessages="OnReceiveMessages",c.OnReceiveSubscribeMessage="OnReceiveSubscribeMessage",c.OnReceiveSystemMessage="OnReceiveSystemMessage",c.OnReceivePreMessage="OnReceivePreMessage",c.OnMessagesListLoaded="OnMessagesListLoaded",c.OnActiveConversationSync="OnActiveConversationSync",c.OnMessageSent="OnMessageSent",c.OnMessageFailed="OnMessageFailed",c.OnMessageRevoked="OnMessageRevoked",c.OnMessageDeleted="OnMessageDeleted",c.OnMessageRead="OnMessageRead",c.OnTypingStatusUpdate="OnTypingStatusUpdate",c.OnUserStatusChange="OnUserStatusChange",c.OnKickedOffline="OnKickedOffline",c.OnUserTokenInvalid="OnUserTokenInvalid",c.OnUserTokenExpired="OnUserTokenExpired",c.OnForceOffline="OnForceOffline",c.OnUserInfoUpdated="OnUserInfoUpdated",c.OnGroupCreated="OnGroupCreated",c.OnGroupInfoUpdated="OnGroupInfoUpdated",c.OnGroupDissolved="OnGroupDissolved",c.OnJoinGroup="OnJoinGroup",c.OnLeaveGroup="OnLeaveGroup",c.OnGroupMemberJoined="OnGroupMemberJoined",c.OnGroupMemberLeft="OnGroupMemberLeft",c.OnGroupMemberKicked="OnGroupMemberKicked",c.OnGroupOwnerChanged="OnGroupOwnerChanged",c.OnGroupAdminAdded="OnGroupAdminAdded",c.OnGroupAdminRemoved="OnGroupAdminRemoved",c.OnGroupMemberMuted="OnGroupMemberMuted",c.OnGroupMemberUnmuted="OnGroupMemberUnmuted",c.OnGroupAllMemberMuted="OnGroupAllMemberMuted",c.OnGroupAllMemberUnmuted="OnGroupAllMemberUnmuted",c.OnConversationCreated="OnConversationCreated",c.OnConversationDeleted="OnConversationDeleted",c.OnConversationListUpdated="OnConversationListUpdated",c.OnConversationUpdated="OnConversationUpdated",c.OnUnreadCountChanged="OnUnreadCountChanged",c.OnConversationPinned="OnConversationPinned",c.OnConversationUnpinned="OnConversationUnpinned",c.OnConversationMuted="OnConversationMuted",c.OnConversationUnmuted="OnConversationUnmuted",c.OnPongConn="OnPongConn",c.OnPongReConn="OnPongReConn",c.OnPongIdle="OnPongIdle",c.OnError="OnError",c.OnWarning="OnWarning",c.OnLog="OnLog";var v,m,f,C,y,S,E,b=/*#__PURE__*/function(){function t(){var t;this.events=((t={})[e.CbEvents.OnReceiveMessage]=[],t[e.CbEvents.OnReceiveSystemMessage]=[],t[e.CbEvents.OnReceiveMessages]=[],t[e.CbEvents.OnConversationListUpdated]=[],t[e.CbEvents.OnMessagesListLoaded]=[],t[e.CbEvents.OnActiveConversationSync]=[],t[e.CbEvents.OnConnected]=[],t[e.CbEvents.OnDisconnected]=[],t[e.CbEvents.OnReconnected]=[],t)}var n=t.prototype;return n.emit=function(e,t){var n=this.events[e];return n&&n.forEach(function(e){return e(t)}),this},n.on=function(e,t){var n;return this.events[e]||(this.events[e]=[]),null==(n=this.events[e])||n.push(t),this},n.off=function(e,t){var n=this.events[e];if(n){var o=n.indexOf(t);o>-1&&(n.splice(o,1),0===n.length&&delete this.events[e])}return this},t}();e.GroupType=void 0,(v=e.GroupType||(e.GroupType={}))[v.PrivateChat=0]="PrivateChat",v[v.PrivateGroup=1]="PrivateGroup",v[v.PublicGroup=2]="PublicGroup",v[v.CustomerService=3]="CustomerService",v[v.LiveGroup=4]="LiveGroup",v[v.ChanneRoom=5]="ChanneRoom",e.MessageType=void 0,(m=e.MessageType||(e.MessageType={}))[m.TEXT=0]="TEXT",m[m.IMAGE=1]="IMAGE",m[m.FILE=2]="FILE",m[m.AUDIO=3]="AUDIO",m[m.VIDEO=4]="VIDEO",m[m.LINK=5]="LINK",m[m.GIF=6]="GIF",m[m.OPTION=7]="OPTION",m[m.EMOJI=8]="EMOJI",m[m.CUSTOM=100]="CUSTOM",e.SseEventType=void 0,(f=e.SseEventType||(e.SseEventType={}))[f.EVENT_PONG_CONN=0]="EVENT_PONG_CONN",f[f.EVENT_PONG_RE_CONN=1]="EVENT_PONG_RE_CONN",f[f.EVENT_PONG_IDLE=2]="EVENT_PONG_IDLE",f[f.EVENT_MESSAGE_PUSH=3]="EVENT_MESSAGE_PUSH",f[f.EVENT_SYSTEM_MESSAGE_PUSH=4]="EVENT_SYSTEM_MESSAGE_PUSH",f[f.EVENT_LIVE_SYSTEM_MESSAGE_PUSH=5]="EVENT_LIVE_SYSTEM_MESSAGE_PUSH",f[f.EVENT_PRE_MESSAGE_PUSH=6]="EVENT_PRE_MESSAGE_PUSH",f[f.EVENT_SUBSCRIBE_MESSAGE_PUSH=7]="EVENT_SUBSCRIBE_MESSAGE_PUSH",e.GroupMemberEventType=void 0,(C=e.GroupMemberEventType||(e.GroupMemberEventType={}))[C.JOIN=0]="JOIN",C[C.LEFT=1]="LEFT",C[C.LAST_READ_UPDATE=2]="LAST_READ_UPDATE",C[C.PERMISSION_UPDATE=3]="PERMISSION_UPDATE",C[C.IDENTITY_UPDATE=4]="IDENTITY_UPDATE",C[C.PING_UPDATE=5]="PING_UPDATE",e.SystemMessageType=void 0,(y=e.SystemMessageType||(e.SystemMessageType={}))[y.GroupMemberPermissionChange=3]="GroupMemberPermissionChange",y[y.GroupPermissionChange=4]="GroupPermissionChange",e.ConnectionProtocol=void 0,(S=e.ConnectionProtocol||(e.ConnectionProtocol={})).SSE="sse",S.WEBSOCKET="websocket",e.ConversationQueryType=void 0,(E=e.ConversationQueryType||(e.ConversationQueryType={}))[E.NonCustomer=0]="NonCustomer",E[E.CustomerService=3]="CustomerService";var T="undefined"!=typeof uni,M="undefined"!=typeof window,P="simsdk_",O={CONVERSATIONS:P+"conversations",GROUP_MESSAGES:P+"group_messages",USER_INFO:P+"user_info",META_INFO:P+"meta"},G={MAX_CONVERSATIONS:100,MAX_GROUP_MESSAGES:200,STORAGE_CHUNK_SIZE:512e3,CACHE_TTL:6048e5,EXPIRY_CHECK_INTERVAL:18e5},R=/*#__PURE__*/function(){function e(e){var t=void 0===e?{}:e,n=t.persistEnabled,o=void 0===n||n,r=t.debug,s=void 0!==r&&r,i=t.config,a=void 0===i?{}:i;this.conversationCacheByQueryType={},this.conversationIdToQueryType={},this.groupMessageCache={},this.accessTimeRecord={},this.pinnedConversationOrder=new Map,this.userInfo={},this.currentUsername=void 0,this.activeConversation=void 0,this.metaInfo={},this.persistEnabled=void 0,this.debug=void 0,this.config=void 0,this.cleanupTimer=void 0,this.persistEnabled=o,this.debug=s,this.config=g({},G,a)}var t=e.prototype;return t.initialize=function(e){var t=this;this.currentUsername&&this.currentUsername!==e&&(this.debug&&console.log("User switched from "+this.currentUsername+" to "+e+", clearing cache"),this.clear()),this.currentUsername=e,this.userInfo.username=e,this.persistEnabled&&this.loadFromStorage(),this.setupCleanupInterval(),this.debug&&(console.log("Cache initialized for user:",e),console.log("Loaded conversations by queryType:",Object.keys(this.conversationCacheByQueryType).reduce(function(e,n){return e+t.conversationCacheByQueryType[n].length},0)),console.log("Loaded group messages for groups:",Object.keys(this.groupMessageCache).length))},t.getQueryTypeKey=function(e){return String(null!=e?e:3)},t.getConversationBucket=function(e){var t=this.getQueryTypeKey(e);return this.conversationCacheByQueryType[t]||(this.conversationCacheByQueryType[t]=[]),this.conversationCacheByQueryType[t]},t.clear=function(){this.conversationCacheByQueryType={},this.conversationIdToQueryType={},this.groupMessageCache={},this.accessTimeRecord={},this.pinnedConversationOrder.clear(),this.persistEnabled&&this.clearCurrentUserStorage(),this.debug&&console.log("Cache cleared")},t.clearCurrentUserStorage=function(){try{if(!this.currentUsername)return void this.clearStorage();var e=this.getUserStorageKey(O.CONVERSATIONS);Object.keys(localStorage).filter(function(t){return t===e||t.startsWith(e+".")}).forEach(function(e){return localStorage.removeItem(e)});var t=this.getUserStorageKey(O.USER_INFO);localStorage.removeItem(t);for(var n,o=l(Object.keys(localStorage).filter(function(e){return e.startsWith(O.GROUP_MESSAGES+".")}));!(n=o()).done;)localStorage.removeItem(n.value)}catch(e){console.error("Failed to clear current user storage:",e)}},t.getConversations=function(e){var t=this.getConversationBucket(e);return[].concat(t)},t.clearConversationUnread=function(e){var t=this.conversationIdToQueryType[e],n=void 0!==t?this.getConversationBucket(t):null,o=n?n.find(function(t){return t.id===e}):null;o&&(o.unreadCount=0,this.persistEnabled&&this.saveConversationsToStorage())},t.updateConversationLastRead=function(e,t){var n=this.conversationIdToQueryType[e],o=void 0!==n?this.getConversationBucket(n):null,r=o?o.find(function(t){return t.id===e}):null;r&&(r.lastRead=t,r.unreadCount=0,this.persistEnabled&&this.saveConversationsToStorage())},t.clearAllConversationUnread=function(){var e=this;Object.keys(this.conversationCacheByQueryType).forEach(function(t){e.conversationCacheByQueryType[t].forEach(function(e){e.unreadCount>0&&(e.unreadCount=0)})}),this.persistEnabled&&this.saveConversationsToStorage()},t.getActiveConversation=function(){return this.activeConversation},t.setConversations=function(e,t,n){var o=this;void 0===t&&(t=!1);var r,s=this.getQueryTypeKey(n),i=null!=n?n:3;if((r=e.length>this.config.MAX_CONVERSATIONS?e.slice(0,this.config.MAX_CONVERSATIONS):[].concat(e)).forEach(function(e){o.conversationIdToQueryType[e.id]=i}),this.conversationCacheByQueryType[s]=r,t)this.pinnedConversationOrder.clear(),r.forEach(function(e,t){e.pin&&o.pinnedConversationOrder.set(e.id,t)});else{var a=-1;this.pinnedConversationOrder.forEach(function(e){e>a&&(a=e)}),r.forEach(function(e,t){e.pin&&!o.pinnedConversationOrder.has(e.id)&&o.pinnedConversationOrder.set(e.id,a+t+1)})}this.sortConversations(i),this.persistEnabled&&this.saveConversationsToStorage()},t.updateConversation=function(e){var t=this.conversationIdToQueryType[e.id];void 0===t&&(this.conversationIdToQueryType[e.id]=t=3===e.groupType?3:0);var n=this.getConversationBucket(t),o=n.findIndex(function(t){return t.id===e.id});o>=0?n[o]=g({},e):(n.push(g({},e)),n.length>this.config.MAX_CONVERSATIONS&&this.enforceConversationLimit(t)),this.sortConversations(t),this.persistEnabled&&this.saveConversationsToStorage()},t.updateConversationPinStatus=function(e,t){var n=this.conversationIdToQueryType[e],o=void 0!==n?this.getConversationBucket(n):null,r=o?o.findIndex(function(t){return t.id===e}):-1;if(-1!==r){var s=o[r],i=!0===s.pin;if(s.pin=t,t&&!i){var a=-1;this.pinnedConversationOrder.forEach(function(e){e>a&&(a=e)}),this.pinnedConversationOrder.set(e,a+1)}else!t&&i&&this.pinnedConversationOrder.delete(e);this.sortConversations(n),this.persistEnabled&&this.saveConversationsToStorage()}},t.updateConversationWithMessage=function(e,t){var n,o=e.groupId;if(!o)return!1;var r=3===e.groupType?3:0,s=this.getConversationBucket(r),i=s.findIndex(function(e){return e.id===o});if(-1===i)return!1;var a=s[i],c=(null==(n=a.latest)?void 0:n.msgId)||0;return this.activeConversation&&this.activeConversation.id===o?(a.unreadCount=0,a.lastRead=e.msgId):t!==e.username&&(a.unreadCount+=e.msgId>c?e.msgId-c:1),a.latest=e,this.sortConversations(r),this.persistEnabled&&this.saveConversationsToStorage(),!0},t.getGroupMessages=function(e){return this.recordAccess(e),!this.groupMessageCache[e]&&this.persistEnabled&&this.loadGroupMessagesFromStorage(e),this.groupMessageCache[e]||[]},t.addGroupMessage=function(e){if(e.groupId){this.recordAccess(e.groupId),this.groupMessageCache[e.groupId]||(this.groupMessageCache[e.groupId]=[]);var t=this.groupMessageCache[e.groupId].findIndex(function(t){return t.msgId===e.msgId});t>=0?this.groupMessageCache[e.groupId][t]=e:this.groupMessageCache[e.groupId].push(e),this.sortGroupMessages(e.groupId),this.limitGroupMessageCache(e.groupId),this.enforceMemoryLimits(),this.persistEnabled&&this.saveGroupMessagesToStorage(e.groupId)}},t.addGroupMessages=function(e){for(var t,n=this,o={},r=l(e);!(t=r()).done;){var s=t.value;s.groupId&&(o[s.groupId]||(o[s.groupId]=[]),o[s.groupId].push(s))}for(var i=0,a=Object.entries(o);i<a.length;i++){var c=a[i],u=c[0],d=c[1];this.recordAccess(Number(u)),this.groupMessageCache[u]||(this.groupMessageCache[u]=[]);for(var g,h=function(){var e=g.value,t=n.groupMessageCache[u].findIndex(function(t){return t.msgId===e.msgId});t>=0?n.groupMessageCache[u][t]=e:n.groupMessageCache[u].push(e)},p=l(d);!(g=p()).done;)h();this.sortGroupMessages(Number(u)),this.limitGroupMessageCache(Number(u)),this.persistEnabled&&this.saveGroupMessagesToStorage(Number(u))}this.enforceMemoryLimits()},t.sortConversations=function(e){var t=this;(void 0!==e?[this.getQueryTypeKey(e)]:Object.keys(this.conversationCacheByQueryType)).forEach(function(e){var n=t.conversationCacheByQueryType[e];n&&n.sort(function(e,n){var o,r,s,i,a=!0===e.pin,c=!0===n.pin;if(a&&!c)return-1;if(!a&&c)return 1;if(a&&c)return(null!=(s=t.pinnedConversationOrder.get(e.id))?s:0)-(null!=(i=t.pinnedConversationOrder.get(n.id))?i:0);var u=(null==(o=e.latest)?void 0:o.createTime)||0;return((null==(r=n.latest)?void 0:r.createTime)||0)-u})})},t.sortGroupMessages=function(e){this.groupMessageCache[e]&&this.groupMessageCache[e].sort(function(e,t){return(t.createTime||0)-(e.createTime||0)})},t.limitGroupMessageCache=function(e){this.groupMessageCache[e]&&this.groupMessageCache[e].length>this.config.MAX_GROUP_MESSAGES&&(this.groupMessageCache[e]=this.groupMessageCache[e].slice(0,this.config.MAX_GROUP_MESSAGES))},t.recordAccess=function(e){this.accessTimeRecord[e]=Date.now()},t.enforceConversationLimit=function(e){var t=this;if(!(this.getConversationBucket(e).length<=this.config.MAX_CONVERSATIONS)){this.sortConversations(e);var n=this.getQueryTypeKey(e),o=this.conversationCacheByQueryType[n].slice(0,this.config.MAX_CONVERSATIONS);this.conversationCacheByQueryType[n]=o;var r=new Set(o.map(function(e){return e.id}));o.forEach(function(n){t.conversationIdToQueryType[n.id]=e}),Object.keys(this.conversationIdToQueryType).forEach(function(n){var o=Number(n);t.conversationIdToQueryType[o]!==e||r.has(o)||delete t.conversationIdToQueryType[o]})}},t.enforceMemoryLimits=function(){var e=this,t=Object.keys(this.groupMessageCache).length;if(t>10){var n=Object.keys(this.groupMessageCache).map(function(t){return{groupId:t,lastAccess:e.accessTimeRecord[t]||0}});n.sort(function(e,t){return e.lastAccess-t.lastAccess});for(var o=Math.ceil(.3*t),r=0;r<o&&r<n.length;r++){var s=n[r].groupId;this.persistEnabled&&(delete this.groupMessageCache[s],this.debug&&console.log("Released memory for inactive group: "+s))}}},t.setupCleanupInterval=function(){var e=this;this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=window.setInterval(function(){e.cleanupExpiredData()},this.config.EXPIRY_CHECK_INTERVAL)},t.cleanupExpiredData=function(){var e=Date.now();this.metaInfo.lastCleanup=e,this.debug&&console.log("Running cache cleanup");for(var t=0,n=Object.entries(this.accessTimeRecord);t<n.length;t++){var o=n[t],r=o[0];e-o[1]>this.config.CACHE_TTL&&(delete this.accessTimeRecord[r],this.groupMessageCache[r]&&delete this.groupMessageCache[r])}this.persistEnabled&&this.saveMetaInfoToStorage()},t.getUserStorageKey=function(e){return this.currentUsername?e+"_"+this.currentUsername:e},t.loadFromStorage=function(){var e=this;try{var t=localStorage.getItem(O.META_INFO);t&&(this.metaInfo=JSON.parse(t));var n=this.getUserStorageKey(O.CONVERSATIONS);this.conversationCacheByQueryType={},this.conversationIdToQueryType={};var o=localStorage.getItem(n);if(o)try{var r=JSON.parse(o);Array.isArray(r)&&(this.conversationCacheByQueryType[String(3)]=r,r.forEach(function(t){e.conversationIdToQueryType[t.id]=3}))}catch(e){this.conversationCacheByQueryType[String(3)]=[]}[0,3].forEach(function(t){var o=localStorage.getItem(n+"."+t);if(o)try{var r=JSON.parse(o);Array.isArray(r)&&(e.conversationCacheByQueryType[String(t)]=r,r.forEach(function(n){e.conversationIdToQueryType[n.id]=t}))}catch(n){e.conversationCacheByQueryType[String(t)]=[]}}),0===Object.keys(this.conversationCacheByQueryType).length&&(this.conversationCacheByQueryType[String(3)]=[]),Object.keys(localStorage).filter(function(e){return e.startsWith(O.GROUP_MESSAGES+".")}).forEach(function(t){var n=t.split(".")[1];n&&!isNaN(Number(n))&&(e.accessTimeRecord[n]=0)});var s=this.getUserStorageKey(O.USER_INFO),i=localStorage.getItem(s);this.userInfo=i?JSON.parse(i):{username:this.currentUsername}}catch(e){console.error("Failed to load cache from storage:",e),this.clearStorage()}},t.loadGroupMessagesFromStorage=function(e){try{for(var t=[],n=0,o=!0;o;){var r=localStorage.getItem(O.GROUP_MESSAGES+"."+e+(n>0?"."+n:""));if(r){var s=JSON.parse(r);t=t.concat(s),n++}else o=!1}t.length>0&&(this.groupMessageCache[e]=t,this.sortGroupMessages(e),this.limitGroupMessageCache(e),this.debug&&console.log("Loaded "+t.length+" messages for group "+e+" from storage"))}catch(t){console.error("Failed to load group messages for "+e+" from storage:",t)}},t.saveConversationsToStorage=function(){var e=this;try{Object.keys(this.conversationCacheByQueryType).forEach(function(t){var n=e.getUserStorageKey(O.CONVERSATIONS)+"."+t;localStorage.setItem(n,JSON.stringify(e.conversationCacheByQueryType[t]))})}catch(e){console.error("Failed to save conversations to storage:",e),this.handleStorageError()}},t.saveGroupMessagesToStorage=function(e){try{if(void 0!==e){var t=this.groupMessageCache[e];if(!t||0===t.length)return;var n=JSON.stringify(t);if(n.length>this.config.STORAGE_CHUNK_SIZE){this.clearGroupMessageStorage(e);for(var o=t.length,r=Math.max(1,Math.floor(this.config.STORAGE_CHUNK_SIZE/(n.length/o))),s=0;s<o;s+=r){var i=t.slice(s,s+r),a=Math.floor(s/r);localStorage.setItem(O.GROUP_MESSAGES+"."+e+(a>0?"."+a:""),JSON.stringify(i))}}else localStorage.setItem(O.GROUP_MESSAGES+"."+e,n)}else for(var c=0,u=Object.keys(this.groupMessageCache);c<u.length;c++)this.saveGroupMessagesToStorage(Number(u[c]))}catch(e){console.error("Failed to save group messages to storage:",e),this.handleStorageError()}},t.saveMetaInfoToStorage=function(){try{localStorage.setItem(O.META_INFO,JSON.stringify(this.metaInfo))}catch(e){console.error("Failed to save meta info to storage:",e)}},t.handleStorageError=function(){for(var e=this,t=Object.keys(this.accessTimeRecord).map(function(t){return{groupId:t,lastAccess:e.accessTimeRecord[t]||0}}).sort(function(e,t){return e.lastAccess-t.lastAccess}),n=Math.max(1,Math.floor(.2*t.length)),o=0;o<n&&o<t.length;o++)this.clearGroupMessageStorage(Number(t[o].groupId)),this.debug&&console.log("Cleared storage for group "+t[o].groupId+" due to quota exceeded")},t.clearGroupMessageStorage=function(e){for(var t=0,n=!0;n;){var o=O.GROUP_MESSAGES+"."+e+(t>0?"."+t:"");null!==localStorage.getItem(o)?(localStorage.removeItem(o),t++):n=!1}},t.saveUserInfoToStorage=function(){try{var e=this.getUserStorageKey(O.USER_INFO);localStorage.setItem(e,JSON.stringify(this.userInfo))}catch(e){console.error("Failed to save user info to storage:",e)}},t.clearStorage=function(){try{for(var e,t=l(Object.keys(localStorage).filter(function(e){return e.startsWith(P)}));!(e=t()).done;)localStorage.removeItem(e.value)}catch(e){console.error("Failed to clear storage:",e)}},t.destroy=function(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.debug&&console.log("Cache manager destroyed")},t.markConversationAsActive=function(e,t){void 0===t&&(t=!0),this.accessTimeRecord[e]=Date.now();var n,o=this.conversationIdToQueryType[e],r=void 0!==o?this.getConversationBucket(o):null,s=r?r.find(function(t){return t.id===e}):void 0;return!!s&&(this.activeConversation=g({},s),t&&s.unreadCount>0&&(s.unreadCount=0,null!=(n=s.latest)&&n.msgId&&(s.lastRead=s.latest.msgId),this.persistEnabled&&this.saveConversationsToStorage()),!0)},t.resetActiveConversation=function(){var e,t=!(null==(e=this.activeConversation)||!e.id);return this.activeConversation=void 0,this.debug&&t&&console.log("Active conversation reset"),t},e}(),A=/*#__PURE__*/function(){function e(e){this.url=void 0,this.token=void 0,this.eventSource=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=2e3*Math.random()+3e3,this.connectTimeout=1e4,this.reconnectTimer=null,this.handlers=new Map,this.connected=!1,this.onMessageCallback=void 0,this.onReconnectSuccessCallback=void 0,this.onConnectionClosedCallback=void 0,this.onMaxRetriesReachedCallback=void 0,this.onConnectionChangeCallback=void 0,this.isDestroyed=!1,this.debug=!1,this._openHandler=null,this._errorHandler=null,this._messageHandler=null,this._customHandlers=new Map,this.connectTimeoutRef=null,this.url=e.url,this.token=e.token,this.connectTimeout=e.connectTimeout||1e4,this.reconnectTimeout=e.retryInterval||2e3*Math.random()+3e3,this.maxReconnectAttempts=e.maxRetries||5,this.debug=e.debug||!1,this.onMessageCallback=e.onMessage,this.onReconnectSuccessCallback=e.onReconnectSuccess,this.onConnectionClosedCallback=e.onConnectionClosed,this.onMaxRetriesReachedCallback=e.onMaxRetriesReached,this.onConnectionChangeCallback=e.onConnectionChange}var n=e.prototype;return n.debugLog=function(e){var t;this.debug&&(t=console).log.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.debugError=function(e){var t;this.debug&&(t=console).error.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.debugWarn=function(e){var t;this.debug&&(t=console).warn.apply(t,["[SSE] "+e].concat([].slice.call(arguments,1)))},n.removeAllEventListeners=function(){var e=this;this.eventSource&&(this._openHandler&&this.eventSource.removeEventListener("open",this._openHandler),this._errorHandler&&this.eventSource.removeEventListener("error",this._errorHandler),this._messageHandler&&this.eventSource.removeEventListener("message",this._messageHandler),this.handlers.forEach(function(t,n){var o=e._customHandlers.get(n);o&&e.eventSource&&e.eventSource.removeEventListener(n,o)}))},n.subscribe=function(e,t){var n=this;this.handlers.set(e,t);var o=function(e){try{var o=JSON.parse(e.data);t(o)}catch(e){n.debugError("Error parsing message data:",e)}};this._customHandlers.set(e,o),this.eventSource?this.eventSource.addEventListener(e,o):this.connect()},n.connect=function(){var e=this;return this.connected&&this.eventSource?Promise.reject(new Error("SSE is already connected!")):new Promise(function(n,o){try{e.eventSource=new t.EventSourcePolyfill(e.url,{heartbeatTimeout:36e5,withCredentials:!1,headers:{Authorization:"Bearer "+e.token}}),e._openHandler=function(t){e.debugLog("SSE connection established"),e.connected=!0,e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!0),e.reconnectAttempts>0&&e.onReconnectSuccessCallback&&e.onReconnectSuccessCallback(),e.reconnectAttempts=0,e.reconnectTimeout=5e3,n("SSE connect successful!")},e._errorHandler=function(t){e.debugError("SSE connection error:",t),e.connected=!1,e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!1),401===t.status||t.statusText&&t.statusText.includes("Unauthorized")?(e.cleanup(),e.connectTimeoutRef&&(clearTimeout(e.connectTimeoutRef),e.connectTimeoutRef=null),e.notifyConnectionClosed(!0)):e.handleReconnect(),e.connected||o(new Error("SSE connect error"))},e._messageHandler=function(t){try{e.debugLog("SSE received message:",t.data);var n=JSON.parse(t.data);e.onMessageCallback&&e.onMessageCallback(n)}catch(t){e.debugError("Error parsing message:",t)}},e.eventSource.addEventListener("open",e._openHandler),e.eventSource.addEventListener("error",e._errorHandler),e.eventSource.addEventListener("message",e._messageHandler),e.handlers.forEach(function(t,n){var o=e._customHandlers.get(n);o&&e.eventSource&&e.eventSource.addEventListener(n,o)}),e.connectTimeoutRef=setTimeout(function(){e.connected||(o(new Error("Connection timeout")),e.handleReconnect())},e.connectTimeout);var r=e._openHandler;e._openHandler=function(t){clearTimeout(e.connectTimeoutRef),r(t)}}catch(t){e.debugError("Failed to create EventSource:",t),e.handleReconnect(),o(t)}})},n.notifyConnectionClosed=function(e){void 0===e&&(e=!1),this.onConnectionClosedCallback&&this.onConnectionClosedCallback(e),e?this.debugWarn("SSE connection closed due to authentication error"):this.debugLog("SSE connection closed")},n.handleReconnect=function(){var e=this;if(this.isDestroyed)this.debugLog("SSE is destroyed, skipping reconnection");else if(null===this.reconnectTimer){if(this.reconnectAttempts>=this.maxReconnectAttempts)return this.debugError("Max reconnection attempts reached"),this.destroySse(),void(this.onMaxRetriesReachedCallback&&this.onMaxRetriesReachedCallback());this.debugLog("Attempting to reconnect in "+this.reconnectTimeout/1e3+" seconds..."),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectAttempts++,e.reconnectTimeout=Math.min(2*e.reconnectTimeout,6e4),e.reconnectTimer=null,e.connect().catch(function(){})},this.reconnectTimeout)}},n.cleanup=function(){this.eventSource&&(this.removeAllEventListeners(),this.eventSource.close(),this.eventSource=null),this.connected=!1},n.unsubscribe=function(){this.cleanup(),this.handlers.clear(),this._customHandlers.clear(),null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)},n.destroySse=function(){this.unsubscribe(),this.isDestroyed=!0,this.notifyConnectionClosed()},n.close=function(){this.destroySse(),this.debugLog("SSE 连接已关闭")},n.isConnected=function(){return this.connected},n.send=function(e){var t="当前协议不可用:SSE 是单向通信协议,不支持客户端向服务器发送消息";throw this.debugError(t),new Error(t)},e}(),k=/*#__PURE__*/function(){function e(e){this.url=void 0,this.token=void 0,this.websocket=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=2e3*Math.random()+3e3,this.connectTimeout=1e4,this.reconnectTimer=null,this.handlers=new Map,this.connected=!1,this.onMessageCallback=void 0,this.onReconnectSuccessCallback=void 0,this.onConnectionClosedCallback=void 0,this.onMaxRetriesReachedCallback=void 0,this.onConnectionChangeCallback=void 0,this.connectTimeoutRef=null,this.isDestroyed=!1,this.debug=!1,this.lastPingTime=0,this.pingCheckTimer=null,this.pageVisibilityHandler=null,this.isPageVisible=!0,this.lastVisibleTime=Date.now(),this.PING_TIMEOUT=12e4,this.PING_CHECK_INTERVAL=5e3,this.RECONNECT_DELAY=3e3,this.PAGE_HIDDEN_TOLERANCE=6e4,this.url=e.url,this.token=e.token,this.connectTimeout=e.connectTimeout||1e4,this.reconnectTimeout=e.retryInterval||2e3*Math.random()+3e3,this.maxReconnectAttempts=e.maxRetries||5,this.debug=e.debug||!1,this.onMessageCallback=e.onMessage,this.onReconnectSuccessCallback=e.onReconnectSuccess,this.onConnectionClosedCallback=e.onConnectionClosed,this.onMaxRetriesReachedCallback=e.onMaxRetriesReached,this.onConnectionChangeCallback=e.onConnectionChange,this.initPageVisibilityDetection()}var t=e.prototype;return t.debugLog=function(e){var t;this.debug&&(t=console).log.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.debugError=function(e){var t;this.debug&&(t=console).error.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.debugWarn=function(e){var t;this.debug&&(t=console).warn.apply(t,["[WebSocket] "+e].concat([].slice.call(arguments,1)))},t.subscribe=function(e,t){this.handlers.set(e,t),this.websocket?this.addMessageHandler(e,t):this.connect()},t.addMessageHandler=function(e,t){var n=this;this.websocket&&this.websocket.addEventListener("message",function(o){try{var r=JSON.parse(o.data);r.type===e&&t(r)}catch(e){n.debugError("Error parsing WebSocket message data:",e)}})},t.connect=function(){var e=this;return this.connected&&this.websocket?Promise.reject(new Error("WebSocket is already connected!")):new Promise(function(t,n){try{var o=new URL(e.url);o.searchParams.set("token",e.token),e.websocket=new WebSocket(o.toString()),e.websocket.binaryType="arraybuffer",e.connectTimeoutRef=setTimeout(function(){e.connected||(n(new Error("WebSocket connection timeout")),e.handleReconnect())},e.connectTimeout),e.websocket.onopen=function(n){e.debugLog("WebSocket connection established"),e.connected=!0,clearTimeout(e.connectTimeoutRef),e.lastPingTime=Date.now(),e.startPingTimeoutCheck(),e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!0),e.reconnectAttempts>0&&e.onReconnectSuccessCallback&&e.onReconnectSuccessCallback(),e.reconnectAttempts=0,e.reconnectTimeout=5e3,t("WebSocket connect successful!")},e.websocket.onerror=function(t){e.debugError("WebSocket connection error:",t),e.connected=!1,clearTimeout(e.connectTimeoutRef),e.onConnectionChangeCallback&&e.onConnectionChangeCallback(!1),e.handleReconnect(),e.connected||n(new Error("WebSocket connect error"))},e.websocket.onclose=function(t){e.debugLog("WebSocket connection closed:",t.code,t.reason),e.connected=!1,1002===t.code||1003===t.code||t.reason&&t.reason.includes("Unauthorized")?(e.cleanup(),e.notifyConnectionClosed(!0)):(e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),e.handleReconnect())},e.websocket.onmessage=function(t){try{t.data instanceof ArrayBuffer?e.handleBinaryMessage(t.data):e.handleTextMessage(t.data),e.lastPingTime=Date.now()}catch(t){e.debugError("Error handling WebSocket message:",t)}},e.handlers.forEach(function(t,n){e.addMessageHandler(n,t)})}catch(t){e.debugError("Failed to create WebSocket:",t),e.handleReconnect(),n(t)}})},t.notifyConnectionClosed=function(e){void 0===e&&(e=!1),this.onConnectionClosedCallback&&this.onConnectionClosedCallback(e),e?this.debugWarn("WebSocket connection closed due to authentication error"):this.debugLog("WebSocket connection closed")},t.handleReconnect=function(){var e=this;if(this.isDestroyed)this.debugLog("WebSocket is destroyed, skipping reconnection");else if(null===this.reconnectTimer){if(this.reconnectAttempts>=this.maxReconnectAttempts)return this.debugError("Max reconnection attempts reached"),this.destroyWebSocket(),void(this.onMaxRetriesReachedCallback&&this.onMaxRetriesReachedCallback());this.debugLog("Attempting to reconnect in "+this.reconnectTimeout/1e3+" seconds... (attempt "+(this.reconnectAttempts+1)+"/"+this.maxReconnectAttempts+")"),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectAttempts++,e.reconnectTimeout=Math.min(2*e.reconnectTimeout,6e4),e.reconnectTimer=null,e.connect().catch(function(){})},this.reconnectTimeout)}},t.handleBinaryMessage=function(e){var t=new DataView(e);if(!(e.byteLength<1)){var n=t.getUint8(0);if(125===n&&e.byteLength>=9){var o=t.getBigInt64(1,!1);return this.debugLog("收到服务端心跳 ping:",o.toString()),this.lastPingTime=Date.now(),void this.sendPong(o)}this.onMessageCallback?this.onMessageCallback(new Uint8Array(e)):this.debugLog("收到二进制消息,类型:","0x"+n.toString(16),"长度:",e.byteLength)}},t.handleTextMessage=function(e){try{this.debugLog("WebSocket received text message:",e);var t=JSON.parse(e);if("pong"===t.type||2===t.ev)return this.connected=!0,void(this.lastPingTime=Date.now());this.onMessageCallback&&this.onMessageCallback(t)}catch(e){this.debugError("Error parsing WebSocket text message:",e)}},t.sendPong=function(e){if(this.websocket&&this.websocket.readyState===WebSocket.OPEN)try{var t=new ArrayBuffer(9),n=new DataView(t);n.setUint8(0,126),n.setBigInt64(1,e,!1),this.websocket.send(t),this.debugLog("已回复心跳 pong, timestamp:",e.toString())}catch(e){this.debugError("Failed to send pong:",e)}else this.debugWarn("WebSocket is not open, cannot send pong")},t.initPageVisibilityDetection=function(){var e=this;"undefined"!=typeof document&&(this.isPageVisible=!document.hidden,this.lastVisibleTime=Date.now(),this.pageVisibilityHandler=function(){var t=e.isPageVisible;if(e.isPageVisible=!document.hidden,t&&!e.isPageVisible)e.lastVisibleTime=Date.now(),e.debugLog("Page became hidden, pausing ping timeout check");else if(!t&&e.isPageVisible){var n=Date.now()-e.lastVisibleTime;e.debugLog("Page became visible after "+n+"ms"),e.websocket&&e.websocket.readyState===WebSocket.OPEN&&n>e.PAGE_HIDDEN_TOLERANCE&&(e.debugLog("Page was hidden for a long time, adjusting ping time"),e.lastPingTime=Date.now()-(e.PING_TIMEOUT-e.PAGE_HIDDEN_TOLERANCE))}},document.addEventListener("visibilitychange",this.pageVisibilityHandler))},t.startPingTimeoutCheck=function(){var e=this;this.stopPingTimeoutCheck(),this.pingCheckTimer=window.setInterval(function(){if(!e.isDestroyed&&e.websocket)if(e.isPageVisible){if(e.websocket.readyState!==WebSocket.OPEN)return e.debugWarn("WebSocket state is "+e.websocket.readyState+", connection may be broken"),e.connected=!1,e.stopPingTimeoutCheck(),e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),void e.delayedReconnect();var t=Date.now()-e.lastPingTime;t>e.PING_TIMEOUT?(e.debugWarn("Ping timeout: "+t+"ms since last ping, connection may be broken"),e.connected=!1,e.onConnectionClosedCallback&&e.onConnectionClosedCallback(!1),e.delayedReconnect()):e.debugLog("Last ping received "+t+"ms ago")}else e.debugLog("Page is hidden, skipping ping timeout check");else e.stopPingTimeoutCheck()},this.PING_CHECK_INTERVAL)},t.stopPingTimeoutCheck=function(){null!==this.pingCheckTimer&&(clearInterval(this.pingCheckTimer),this.pingCheckTimer=null)},t.delayedReconnect=function(){var e=this;null===this.reconnectTimer&&(this.debugLog("Delaying reconnect for "+this.RECONNECT_DELAY/1e3+" seconds to prevent reconnect storm..."),this.cleanup(),this.reconnectTimer=window.setTimeout(function(){e.reconnectTimer=null,e.handleReconnect()},this.RECONNECT_DELAY))},t.cleanup=function(){this.stopPingTimeoutCheck(),this.websocket&&(this.websocket.close(),this.websocket=null),this.connected=!1},t.cleanupPageVisibilityDetection=function(){this.pageVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.pageVisibilityHandler),this.pageVisibilityHandler=null)},t.unsubscribe=function(){this.cleanup(),this.handlers.clear(),null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.cleanupPageVisibilityDetection()},t.destroyWebSocket=function(){this.unsubscribe(),this.isDestroyed=!0,this.cleanupPageVisibilityDetection(),this.notifyConnectionClosed()},t.close=function(){this.destroyWebSocket(),this.debugLog("WebSocket 连接已关闭")},t.isConnected=function(){var e;return this.connected&&(null==(e=this.websocket)?void 0:e.readyState)===WebSocket.OPEN},t.send=function(e){if(!this.websocket||!this.isConnected())return this.debugWarn("WebSocket is not connected, cannot send message"),!1;try{if("string"==typeof e)this.websocket.send(e),this.debugLog("WebSocket message sent (string):",e);else if(e instanceof ArrayBuffer||e instanceof Blob)this.websocket.send(e),this.debugLog("WebSocket message sent (binary):","ArrayBuffer/Blob ("+(e instanceof ArrayBuffer?e.byteLength:e.size)+" bytes)");else if(e instanceof Uint8Array||e instanceof Int8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Uint32Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof DataView)this.websocket.send(e),this.debugLog("WebSocket message sent (binary):","ArrayBufferView ("+e.byteLength+" bytes)");else{var t=JSON.stringify(e);this.websocket.send(t),this.debugLog("WebSocket message sent (JSON):",t)}return!0}catch(e){return this.debugError("Failed to send WebSocket message:",e),!1}},e}(),I=["protocol"],_=/*#__PURE__*/function(){function t(){}return t.createClient=function(t){var n=t.protocol,o=function(e,t){if(null==e)return{};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o]}return n}(t,I);switch(n){case e.ConnectionProtocol.SSE:return new A(o);case e.ConnectionProtocol.WEBSOCKET:return new k(o);default:throw new Error("Unsupported connection protocol: "+n)}},t}(),N=null,U=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.login=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.Login,method:"POST"}))}catch(e){return Promise.reject(e)}},n.logout=function(){try{return Promise.resolve(this.sdk.sendRequest({data:{},url:e.RequestApi.Logout,method:"POST"}))}catch(e){return Promise.reject(e)}},n.getChatMember=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({data:{chatId:t,parent:n},url:e.RequestApi.GetChatMember,method:"GET"}))}catch(e){return Promise.reject(e)}},t}(),L=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.sendMessage=function(e,t){try{var n=this;return Promise.resolve(function(o,r){try{var s=Promise.resolve(n.sdk.sendRequest({data:e,url:t,method:"POST"}))}catch(e){return r(e)}return s&&s.then?s.then(void 0,r):s}(0,function(e){throw console.error("Failed to send message",e),e}))}catch(e){return Promise.reject(e)}},n.getMessageApi=function(t,n){return n===e.GroupType.PrivateChat?e.RequestApi.PushPrivateMessage:n===e.GroupType.LiveGroup?e.RequestApi.PushLiveMessage:null!=t&&t.receiverName?e.RequestApi.PushMessageToMember:e.RequestApi.CreateTextMessage},n.createMessage=function(t,n,o,r,s){void 0===r&&(r={});var i={groupType:o};o===e.GroupType.PublicGroup||o===e.GroupType.PrivateGroup||o===e.GroupType.LiveGroup?i.groupId=n:i.receiverName=n;var a=g({},i,r,{msgType:t},s);return this.sendMessage(a,this.getMessageApi(i,o))},n.createTextMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.TEXT,n,o,r,{text:t}))}catch(e){return Promise.reject(e)}},n.createImageMessage=function(t,n,o,r,s){void 0===s&&(s={});try{return Promise.resolve(this.createMessage(e.MessageType.IMAGE,o,r,s,{link:t,snapshot:n}))}catch(e){return Promise.reject(e)}},n.createFileMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.FILE,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createAudioMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.AUDIO,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createVideoMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.VIDEO,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createLinkMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.LINK,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createGifMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.GIF,n,o,r,{link:t}))}catch(e){return Promise.reject(e)}},n.createOptionMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.OPTION,n,o,r,{text:t}))}catch(e){return Promise.reject(e)}},n.createEmojiMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.EMOJI,n,o,r,{text:t}))}catch(e){return Promise.reject(e)}},n.createCustomMessage=function(t,n,o,r){void 0===r&&(r={});try{return Promise.resolve(this.createMessage(e.MessageType.CUSTOM,n,o,r,{text:t}))}catch(e){return Promise.reject(e)}},n.getHistoryMessageList=function(t){var n=t.groupId,o=t.lastId,r=t.type,s=t.size,i=void 0===s?100:s;try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.GetHistoryMessageList,method:"POST",data:{groupId:n,lastId:o,type:r,size:i}}))}catch(e){return Promise.reject(e)}},n.getLiveMessageList=function(t){var n=t.groupId;try{var o;return Promise.resolve(this.sdk.sendRequest({data:{groupId:n},url:null!=(o=this.sdk.getConfig)&&o.anonLogin?e.RequestApi.GetAnonymousLiveMessageList:e.RequestApi.GetLiveMessageList,method:"POST"}))}catch(e){return Promise.reject(e)}},n.prePushCustomerMessage=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.PrePushCustomerMessage,method:"POST"}))}catch(e){return Promise.reject(e)}},t}(),w=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.getConversations=function(t){try{var n=this;return Promise.resolve(n.sdk.sendRequest({data:t,url:e.RequestApi.GetAllConversationList,method:"GET"})).then(function(e){return e.data.records=e.data.records.map(n.normalizeConversation),e})}catch(e){return Promise.reject(e)}},n.getChannels=function(t){try{var n=this;return Promise.resolve(n.sdk.sendRequest({data:t,url:e.RequestApi.GetChannels,method:"GET"})).then(function(e){return e.data.records=e.data.records.map(n.normalizeConversation),e})}catch(e){return Promise.reject(e)}},n.markConversationRead=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.MarkConversationMessageAsRead,method:"GET"}))}catch(e){return Promise.reject(e)}},n.markLastRead=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,msgId:n},url:e.RequestApi.MarkConversationMessageAsRead,method:"GET"}))}catch(e){return Promise.reject(e)}},n.pinConversation=function(t,n){void 0===n&&(n=1);try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,isTop:n},url:e.RequestApi.PinConversation,method:"GET"}))}catch(e){return Promise.reject(e)}},n.muteConversation=function(t,n){void 0===n&&(n=1);try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,mute:n},url:e.RequestApi.MuteConversation,method:"GET"}))}catch(e){return Promise.reject(e)}},n.normalizeConversation=function(e){var t,n,o,r,s,i,a,c,u;return g({},e,{id:e.id,name:e.name||"",groupType:e.groupType||0,avatar:e.avatar||"",status:null!=(t=e.status)?t:1,latest:null!=(n=e.latest)?n:{},unreadCount:null!=(o=e.unreadCount)?o:0,lastRead:e.lastRead,draftText:null!=(r=e.draftText)?r:"",custom:null!=(s=e.custom)?s:"",groupMemberId:null!=(i=e.groupMemberId)?i:"",pin:null!=(a=e.pin)&&a,supportId:e.supportId||"",supportNick:e.supportNick||"",identity:null!=(c=e.identity)?c:1,mute:null!=(u=e.mute)&&u})},t}(),D=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.getGroupInfo=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.GetGroupInfo,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getGroupMember=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.GetGroupMember,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getGroupMembers=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.GetGroupMembers,method:"GET"}))}catch(e){return Promise.reject(e)}},n.joinGroup=function(t){try{var n;return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:null!=(n=this.sdk.getConfig)&&n.anonLogin?e.RequestApi.AnonymousJoinGroup:e.RequestApi.JoinGroup,method:"GET"}))}catch(e){return Promise.reject(e)}},n.leftGroup=function(t){try{var n;return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:null!=(n=this.sdk.getConfig)&&n.anonLogin?e.RequestApi.AnonymousLeftGroup:e.RequestApi.LeftGroup,method:"GET"}))}catch(e){return Promise.reject(e)}},n.checkGroupBlock=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.CheckGroupBlock,method:"GET"}))}catch(e){return Promise.reject(e)}},n.updateLatestMessage=function(t){try{var n=Object.fromEntries(t.entries());return Promise.resolve(this.sdk.sendRequest({data:{latestMessage:n},url:e.RequestApi.UpdateLatestMessage,method:"POST"}))}catch(e){return Promise.reject(e)}},n.getGroupLatestMessage=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groups:t},url:e.RequestApi.GetLatestGroupChats,method:"POST"}))}catch(e){return Promise.reject(e)}},n.checkGroupLatestMessage=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{ttl:t},url:e.RequestApi.CheckLatestMessages,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getMyGroupPermission=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.GetMyGroupPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getGroupPermission=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t},url:e.RequestApi.GetGroupPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getGroupMemberPermission=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,targetMemberId:n},url:e.RequestApi.GetGroupMemberPermission,method:"GET"}))}catch(e){return Promise.reject(e)}},n.updateGroupPermission=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.UpdateGroupPermission,method:"POST"}))}catch(e){return Promise.reject(e)}},n.updateGroupMemberPermission=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.UpdateGroupMemberPermission,method:"POST"}))}catch(e){return Promise.reject(e)}},n.kickGroupMember=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.kickGroupMember,method:"POST"}))}catch(e){return Promise.reject(e)}},n.muteMembers=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.muteMembers,method:"POST"}))}catch(e){return Promise.reject(e)}},n.editGroupName=function(t,n,o){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.editeGroupName,method:"GET",data:{groupId:t,name:n,avatar:o}}))}catch(e){return Promise.reject(e)}},n.editNotification=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.editeNotification,method:"GET",data:{groupId:t,notification:n}}))}catch(e){return Promise.reject(e)}},n.editGroupCustomer=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.editeGroupCustomer,method:"GET",data:{groupId:t,customer:n}}))}catch(e){return Promise.reject(e)}},n.addAdmin=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.addAdmin,method:"GET",data:{groupId:t,username:n}}))}catch(e){return Promise.reject(e)}},n.deleteAdmin=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.deleteAdmin,method:"GET",data:{groupId:t,username:n}}))}catch(e){return Promise.reject(e)}},n.dissolveGroup=function(t){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.DissolveGroup,method:"GET",data:{groupId:t}}))}catch(e){return Promise.reject(e)}},n.pin=function(t,n,o){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.pin,method:"GET",data:{groupId:t,messageId:n,type:o}}))}catch(e){return Promise.reject(e)}},n.muteGroup=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.muteGroup,method:"GET",data:{groupId:t,type:n}}))}catch(e){return Promise.reject(e)}},n.muteMember=function(t,n,o){try{return Promise.resolve(this.sdk.sendRequest({url:e.RequestApi.muteMember,method:"GET",data:{groupId:t,username:n,type:o}}))}catch(e){return Promise.reject(e)}},n.addGroupMembers=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.AddGroupMembers,method:"POST"}))}catch(e){return Promise.reject(e)}},n.getFileByType=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.GetFileByType,method:"GET"}))}catch(e){return Promise.reject(e)}},n.pinChat=function(t,n){try{return Promise.resolve(this.sdk.sendRequest({data:{groupId:t,type:n},url:e.RequestApi.PinChat,method:"GET"}))}catch(e){return Promise.reject(e)}},t}(),V=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.sdk=e}var n=t.prototype;return n.getContactByType=function(t,n){try{var o={contactType:t};return void 0!==n&&(o.groupId=n),Promise.resolve(this.sdk.sendRequest({data:o,url:e.RequestApi.GetContactByType,method:"GET"}))}catch(e){return Promise.reject(e)}},n.getMemberContacts=function(t){try{return Promise.resolve(this.getContactByType(e.ContactType.MEMBER,t))}catch(e){return Promise.reject(e)}},n.getColleagueContacts=function(t){try{return Promise.resolve(this.getContactByType(e.ContactType.COLLEAGUE,t))}catch(e){return Promise.reject(e)}},n.getGroupContacts=function(t){try{return Promise.resolve(this.getContactByType(e.ContactType.GROUP,t))}catch(e){return Promise.reject(e)}},n.editContactTag=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.EditContactTag,method:"POST"}))}catch(e){return Promise.reject(e)}},n.getContactTag=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:{contactType:t},url:e.RequestApi.GetContactTag,method:"GET"}))}catch(e){return Promise.reject(e)}},n.allocationContactTag=function(t){try{return Promise.resolve(this.sdk.sendRequest({data:t,url:e.RequestApi.AllocationContactTag,method:"POST"}))}catch(e){return Promise.reject(e)}},n.allocationMemberTag=function(t,n,o){void 0===o&&(o=0);try{return Promise.resolve(this.allocationContactTag({contactType:e.ContactType.MEMBER,tag:t,groupIds:n,type:o}))}catch(e){return Promise.reject(e)}},n.allocationColleagueTag=function(t,n,o){void 0===o&&(o=0);try{return Promise.resolve(this.allocationContactTag({contactType:e.ContactType.COLLEAGUE,tag:t,groupIds:n,type:o}))}catch(e){return Promise.reject(e)}},n.allocationGroupTag=function(t,n,o){void 0===o&&(o=0);try{return Promise.resolve(this.allocationContactTag({contactType:e.ContactType.GROUP,tag:t,groupIds:n,type:o}))}catch(e){return Promise.reject(e)}},t}(),j=/*#__PURE__*/function(){function t(e){this.sdk=void 0,this.services={},this.sdk=e}var n=t.prototype;return n.get=function(e){return this.services[e]||(this.services[e]=this.createService(e)),this.services[e]},n.createService=function(t){switch(t){case e.ServiceName.USER:return new U(this.sdk);case e.ServiceName.MESSAGE:return new L(this.sdk);case e.ServiceName.CONVERSATION:return new w(this.sdk);case e.ServiceName.GROUP:return new D(this.sdk);case e.ServiceName.CONTACT:return new V(this.sdk);default:throw new Error("Unknown service: "+t)}},n.reset=function(){this.services={}},t}();function q(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var B=[e.RequestApi.Logout,e.CbEvents.OnKickedOffline,e.CbEvents.OnUserTokenInvalid,e.CbEvents.OnUserTokenExpired],H=/*#__PURE__*/function(t){function n(o){var r;return void 0===o&&(o=!1),(r=t.call(this)||this).config={debug:!1,isLive:!1,useProtobuf:!1,protocol:e.ConnectionProtocol.SSE},r.internalState={isConnected:!1,isLoggedIn:!1,reconnectAttempts:0,lastActivity:Date.now()},r.cacheManager=void 0,r.connectionClient=void 0,r.serviceManager=void 0,r.lastUnauthorizedTime=0,r.UNAUTHORIZED_THROTTLE_MS=3e3,r.conversationUpdateTimer=null,r.CONVERSATION_UPDATE_THROTTLE_MS=500,r.pendingConversationUpdate=!1,r.lastConversationUpdateTime=0,r.isPageVisible=!0,r.pageVisibilityHandler=null,r.PAGE_HIDDEN_STOP_DELAY_MS=3e3,r.pageHiddenTimer=null,r.isActuallyHidden=!1,r.PAGE_VISIBLE_STABLE_MS=1e3,r.pageVisibleStableTimer=null,r.configure=function(e){void 0!==e.debug&&(r.config.debug=e.debug),e.isLive&&(r.config.isLive=e.isLive),e.apiAddr&&(r.config.apiAddr=e.apiAddr),e.wsAddr&&(r.config.wsAddr=e.wsAddr),e.ossApiAddr&&(r.config.ossApiAddr=e.ossApiAddr),e.appKey&&(r.config.appKey=e.appKey),e.token&&(r.config.token=e.token),e.connectTimeout&&(r.config.connectTimeout=e.connectTimeout),e.maxRetries&&(r.config.maxRetries=e.maxRetries),e.useProtobuf&&(r.config.useProtobuf=e.useProtobuf),e.protocol&&(r.config.protocol=e.protocol)},r.sendRequest=function(e){try{r.internalState.lastActivity=Date.now(),r.config.debug&&r.logRequest(e);var t=r.config.apiAddr+e.url,n=e.data;if("GET"===e.method&&n){var o=new URLSearchParams;Object.entries(n).forEach(function(e){var t=e[1];null!=t&&o.append(e[0],String(t))});var s=o.toString();s&&(t+=(t.includes("?")?"&":"?")+s),n=void 0}return Promise.resolve(q(function(){return Promise.resolve(function(e){try{var t,n=function(e){if(t)return e;throw new Error("Unsupported platform")},o=function(){if(T){var n=new Promise(function(t,n){uni.request({url:e.url,method:e.method||"GET",header:e.headers,data:e.data,success:function(e){401!==e.statusCode?t(e.data):n({status:401,message:"Unauthorized"})},fail:function(e){return n(e)}})});return t=1,n}return function(){if(M)return Promise.resolve(fetch(e.url,{method:e.method||"GET",headers:e.headers,body:e.data?JSON.stringify(e.data):null})).then(function(e){if(401===e.status)throw{status:401,message:"Unauthorized"};return Promise.resolve(e.json()).then(function(e){return t=1,e})})}()}();return Promise.resolve(o&&o.then?o.then(n):n(o))}catch(e){return Promise.reject(e)}}({url:t,method:e.method,headers:{"Content-Type":"application/json",Authorization:r.config.token?"Bearer "+r.config.token:""},data:n}))},function(e){throw 401!==(null==e?void 0:e.status)&&401!==(null==e?void 0:e.statusCode)||r.handleUnauthorizedWithThrottle(t),e}))}catch(e){return Promise.reject(e)}},r.handleUnauthorizedWithThrottle=function(e){var t=Date.now();t-r.lastUnauthorizedTime<r.UNAUTHORIZED_THROTTLE_MS?console.warn("401错误被节流限制,跳过处理:"+e):(r.lastUnauthorizedTime=t,r.handleUnauthorized(e))},r.handleUnauthorized=function(e){console.warn("未授权请求(401):",e),r.handleConnectionClosed(!0)},r.createRequestFunction=function(e,t){return function(n){return r.sendRequest({data:n,url:e,method:t})}},r.createRequestFunctionWithoutParams=function(e,t){return function(){return r.sendRequest({data:void 0,method:t,url:e})}},r.handleMessage=function(e){if(r.config.debug&&console.log("[SDK] handleMessage response",e),r.isBinaryMessage(e)){var t=r.normalizeToBinaryBuffer(e);if(!t||t.length<1)r.config.debug&&console.warn("[SDK] [Proto] 二进制消息长度不足,已忽略");else{var o=t[0];switch(o){case n.BINARY_MSG_TYPE.BYTE_MESSAGE:r.handleProtobufMessage(t).catch(function(e){console.error("[SDK] handleProtobufMessage error",e)});break;case n.BINARY_MSG_TYPE.HEARTBEAT_PONG:r.internalState.isConnected=!0,r.config.debug&&console.log("[SDK] [Proto] 收到 PONG(0x7E),已更新 isConnected");break;case n.BINARY_MSG_TYPE.HEARTBEAT_PING:r.config.debug&&console.log("[SDK] [Proto] 收到 PING(0x7D),应由连接层回复 PONG");break;default:r.config.debug&&console.warn("[SDK] [Proto] 未知二进制类型,已忽略",{messageType:"0x"+o.toString(16),length:t.length})}}}else r.handleJsonMessage(e)},r.handleJsonMessage=function(t){switch(r.config.debug&&console.log("handleMessage response",t),t.ev){case e.SseEventType.EVENT_MESSAGE_PUSH:var n=t.dt;Array.isArray(n)?(n.forEach(function(e){r.updateMessageCache(e)}),r.emit(e.CbEvents.OnReceiveMessages,n)):console.warn("[SDK] Expected response.dt to be an array, but got:",n);break;case e.SseEventType.EVENT_PONG_IDLE:r.internalState.isConnected=!0;break;case e.SseEventType.EVENT_SYSTEM_MESSAGE_PUSH:r.emit(e.CbEvents.OnReceiveSystemMessage,t.dt);break;case e.SseEventType.EVENT_PRE_MESSAGE_PUSH:r.emit(e.CbEvents.OnReceivePreMessage,t.dt);break;case e.SseEventType.EVENT_SUBSCRIBE_MESSAGE_PUSH:r.emit(e.CbEvents.OnReceiveSubscribeMessage,t.dt);break;default:o=t.ev,Object.values(e.CbEvents).includes(o)?(r.emit(t.ev,t.dt),B.includes(t.ev)&&(r.internalState.isLoggedIn=!1,r.internalState.isConnected=!1,r.connectionClient&&(r.connectionClient.close(),r.connectionClient=void 0))):r.config.debug&&console.warn("[SDK] Unknown SSE event type:",t.ev)}var o},r.handleReconnectSuccess=function(){r.config.username&&(r.internalState.isConnected=!0,r.internalState.reconnectAttempts=0,r.config.debug&&console.log("SSE reconnection successful"),r.emit(e.CbEvents.OnReconnected))},r.handleConnectionClosed=function(t){r.internalState.isConnected=!1,r.config.debug&&console.log("SSE connection closed"),r.emit(e.CbEvents.OnDisconnected,t)},r.handleMaxRetriesReached=function(){r.config.debug&&console.log("SSE connection max reconnection attempts reached"),r.emit(e.CbEvents.onMaxRetriesReached)},r.handleConnectionChange=function(t){r.config.debug&&console.log("Connection status changed:",t),r.emit(t?e.CbEvents.OnConnected:e.CbEvents.OnDisconnected)},r.login=function(t){try{var n,o,s=function(s){return n?s:(r.connectionClient=_.createClient({url:r.config.wsAddr+"/"+(t.anonLogin?"anonymousConn":"conn")+"?username="+t.username+"&token="+t.token+"&appKey="+r.config.appKey+"&random="+o,protocol:r.config.protocol||e.ConnectionProtocol.WEBSOCKET,debug:r.config.debug,onMessage:r.handleMessage,onReconnectSuccess:r.handleReconnectSuccess,onConnectionClosed:r.handleConnectionClosed,onMaxRetriesReached:r.handleMaxRetriesReached,onConnectionChange:r.handleConnectionChange,token:t.token,connectTimeout:r.config.connectTimeout,maxRetries:r.config.maxRetries}),q(function(){return Promise.resolve(r.connectionClient.connect()).then(function(e){return r.internalState.isLoggedIn=!0,r.internalState.isConnected=!0,r.config.isLive||r.initializeConversationCache(),e})},function(e){return r.internalState.isLoggedIn=!1,r.internalState.isConnected=!1,Promise.reject(e.message)}))};if(r.connectionClient&&(null==r.connectionClient.close||r.connectionClient.close(),r.connectionClient=void 0,r.internalState.isLoggedIn=!1,r.internalState.isConnected=!1),!r.config.apiAddr)return Promise.reject("No apiAddr configured. Please call configure() before login().");if(!r.config.ossApiAddr)return Promise.reject("No ossApiAddr configured. Please call configure() before login().");if(!r.config.appKey)return Promise.reject("No appKey configured. Please call configure() before login().");if(!r.config.token)return Promise.reject("No token configured. Please call configure() before login().");if(r.config.username=t.username,r.config.anonLogin=t.anonLogin||!1,t.protocol&&(r.config.protocol=t.protocol),t.protocol==e.ConnectionProtocol.WEBSOCKET&&!r.config.wsAddr)return Promise.reject("WebSocket address (wsAddr) is not configured. Please call configure() before login().");if(r.config.debug&&(console.log("login params",t),console.log("apiAddr",r.config.apiAddr)),!r.config.isLive||!t.anonLogin){r.cacheManager.initialize(t.username),r.cacheManager.resetActiveConversation();var i=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService);i.length>0&&r.emit(e.CbEvents.OnConversationListUpdated,i)}var a=function(){if(!t.anonLogin)return Promise.resolve(r.user.login(g({},t,{appKey:r.config.appKey}))).then(function(e){var t=e.code,r=e.data;if(0!=t){var s=Promise.resolve("Login failed, Server error, error code is "+t);return n=1,s}o=r})}();return Promise.resolve(a&&a.then?a.then(s):s(a))}catch(e){return Promise.reject(e)}},r.logout=function(){try{return r.connectionClient&&(r.connectionClient.close(),r.connectionClient=void 0),Promise.resolve(r.user.logout()).then(function(e){return r.internalState.isLoggedIn=!1,r.internalState.isConnected=!1,r.config.username=void 0,r.config.token=void 0,r.cacheManager.clear(),e})}catch(e){return Promise.reject(e)}},r.getChatMember=function(e,t){return r.user.getChatMember(e,t)},r.getConversations=function(t){try{return Promise.resolve(q(function(){var n,o,s=t.pageNo||1,i=null!=(n=t.pageSize)?n:50,a=null!=(o=t.queryType)?o:e.ConversationQueryType.CustomerService;if(s<1)return console.warn("[SDK] Invalid pageNo, must be >= 1"),{code:-1,msg:"Invalid pageNo, must be >= 1",data:{records:[],current:1,pages:0}};if(i<1||i>100)return console.warn("[SDK] Invalid pageSize, must be between 1 and 100"),{code:-1,msg:"Invalid pageSize, must be between 1 and 100",data:{records:[],current:1,pages:0}};if(a===e.ConversationQueryType.CustomerService&&s>=2&&null==t.score)return console.warn("[SDK] queryType=3 时第二页起必须传入 score 参数"),{code:-1,msg:"score is required for pageNo >= 2 when queryType is 3",data:{records:[],current:s,pages:0}};var c={pageNo:s,pageSize:i,queryType:a};return s>=2&&null!=t.score&&(c.score=t.score),Promise.resolve(r.conversation.getConversations(c)).then(function(t){var n=t.data;if(0===t.code&&n){var o=r.cacheManager.getConversations(a);if(1===s)r.cacheManager.setConversations([].concat(n.records),!0,a);else{var i=n.records||[],c=new Map;o.forEach(function(e){return c.set(e.id,e)});var u=[],d=[];i.forEach(function(e){c.has(e.id)?u.push(e):d.push(e)});var l=[];o.forEach(function(e){u.find(function(t){return t.id===e.id})||l.push(e)}),l.push.apply(l,u.concat(d)),r.cacheManager.setConversations(l,!1,a)}r.emit(e.CbEvents.OnConversationListUpdated,r.cacheManager.getConversations(a))}else{var g=r.cacheManager.getConversations(a);g.length>0&&r.emit(e.CbEvents.OnConversationListUpdated,g)}return t})},function(n){var o;console.error("[SDK] Failed to get conversations",n);var s=null!=(o=t.queryType)?o:e.ConversationQueryType.CustomerService,i=r.cacheManager.getConversations(s);return i.length>0&&r.emit(e.CbEvents.OnConversationListUpdated,i),{code:-1,msg:n instanceof Error?n.message:"Failed to get conversations",data:{records:i,current:t.pageNo||1,pages:0}}}))}catch(e){return Promise.reject(e)}},r.internalUploadFile=function(t,n){try{return Promise.resolve(q(function(){var o=""+r.config.apiAddr+e.RequestApi.UploadCredential+"?groupId="+n+"&filename="+encodeURIComponent(t.name);return Promise.resolve(fetch(o,{method:"GET",headers:{Authorization:r.config.token?"Bearer "+r.config.token:""}})).then(function(e){if(!e.ok)throw new Error("Get upload credential failed: "+e.status);return Promise.resolve(e.json()).then(function(e){var n=(null==e?void 0:e.data)||{};if(null==e||!e.success||null==n||!n.uploadUrl||null==n||!n.accessUrl)throw new Error((null==e?void 0:e.msg)||"Invalid upload credential response");var o=n.accessUrl;return Promise.resolve(fetch(n.uploadUrl,{method:"PUT",headers:{"Content-Type":t.type||"application/octet-stream"},body:t})).then(function(e){var r;if(!e.ok)throw new Error("Upload to OSS failed with status: "+e.status);var s=null!=(r=n.thumbnailUrl)?r:t.type.startsWith("image/")?o+(o.includes("?")?"&":"?")+"x-oss-process=image/resize,m_lfit,w_200,h_200":"";return{originalUrl:o,thumbnailUrl:s}})})})},function(e){return console.error("[Upload Error]",e),{error:e instanceof Error?e:new Error("Unknown upload error")}}))}catch(e){return Promise.reject(e)}},r.uploadFile=function(t,n){var o=t.file;try{return Promise.resolve(r.internalUploadFile(o,n)).then(function(t){var n,o=t.originalUrl,r=t.thumbnailUrl,s=t.error;return{data:{originalUrl:void 0===o?"":o,thumbnailUrl:void 0===r?"":r},msg:null!=(n=null==s?void 0:s.message)?n:"",code:s?e.ErrorCode.UnknownError:0}})}catch(e){return Promise.reject(e)}},r.sendTextMessage=function(e,t,n,o){return r.message.createTextMessage(e,t,n,o)},r.sendImageMessage=function(e,t,n,o,s){return r.message.createImageMessage(e,t,n,o,s)},r.sendFileMessage=function(e,t,n,o){return r.message.createFileMessage(e,t,n,o)},r.sendAudioMessage=function(e,t,n,o){return r.message.createAudioMessage(e,t,n,o)},r.sendVideoMessage=function(e,t,n,o){return r.message.createVideoMessage(e,t,n,o)},r.sendLinkMessage=function(e,t,n,o){return r.message.createLinkMessage(e,t,n,o)},r.sendGifMessage=function(e,t,n,o){return r.message.createGifMessage(e,t,n,o)},r.sendOptionMessage=function(e,t,n,o){return r.message.createOptionMessage(e,t,n,o)},r.sendEmojiMessage=function(e,t,n,o){return r.message.createEmojiMessage(e,t,n,o)},r.sendCustomMessage=function(e,t,n,o){return r.message.createCustomMessage(e,t,n,o)},r.getHistoryMessageList=function(e){try{return Promise.resolve(r.message.getHistoryMessageList(e))}catch(e){return Promise.reject(e)}},r.getLiveMessageList=function(e){return r.message.getLiveMessageList(e)},r.prePushCustomerMessage=function(e){return r.message.prePushCustomerMessage(e)},r.getGroupInfo=function(e){return r.group.getGroupInfo(e)},r.getGroupMembers=function(e){return r.group.getGroupMembers(e)},r.joinGroup=function(e){return r.group.joinGroup(e)},r.leftGroup=function(e){return r.group.leftGroup(e)},r.checkGroupBlock=function(e){return r.group.checkGroupBlock(e)},r.getMyGroupPermission=function(e){return r.group.getMyGroupPermission(e)},r.getGroupPermission=function(e){return r.group.getGroupPermission(e)},r.getGroupMember=function(e){return r.group.getGroupMember(e)},r.getGroupMemberPermission=function(e,t){return r.group.getGroupMemberPermission(e,t)},r.updateGroupPermission=function(e){return r.group.updateGroupPermission(e)},r.kickGroupMember=function(e){return r.group.kickGroupMember(e)},r.muteMembers=function(e){return r.group.muteMembers(e)},r.updateGroupMemberPermission=function(e){return r.group.updateGroupMemberPermission(e)},r.editGroupName=function(t,n,o){try{return Promise.resolve(r.group.editGroupName(t,n,o)).then(function(s){if(0===s.code){var i=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService).find(function(e){return e.id===t});if(i){i.name=n,i.avatar=o,r.cacheManager.updateConversation(i);var a=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService);r.emit(e.CbEvents.OnConversationListUpdated,a)}}return s})}catch(e){return Promise.reject(e)}},r.editNotification=function(e,t){return r.group.editNotification(e,t)},r.editGroupCustomer=function(e,t){return r.group.editGroupCustomer(e,t)},r.addAdmin=function(e,t){return r.group.addAdmin(e,t)},r.deleteAdmin=function(e,t){return r.group.deleteAdmin(e,t)},r.pin=function(e,t,n){return r.group.pin(e,t,n)},r.muteGroup=function(e,t){return r.group.muteGroup(e,t)},r.muteMember=function(e,t,n){return r.group.muteMember(e,t,n)},r.addGroupMembers=function(e){return r.group.addGroupMembers(e)},r.getFileByType=function(e){return r.group.getFileByType(e)},r.pinChat=function(e,t){return r.group.pinChat(e,t)},r.dissolveGroup=function(e){return r.group.dissolveGroup(e)},r.markConversationRead=function(t){try{return Promise.resolve(r.conversation.markConversationRead(t)).then(function(n){if(0===n.code&&t.groupId){t.id?r.cacheManager.updateConversationLastRead(t.groupId,t.id):r.cacheManager.clearConversationUnread(t.groupId);var o=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService);r.emit(e.CbEvents.OnConversationListUpdated,o)}return n})}catch(e){return Promise.reject(e)}},r.markLastRead=function(t,n){try{return Promise.resolve(r.conversation.markLastRead(t,n)).then(function(o){if(0===o.code){r.cacheManager.updateConversationLastRead(t,n);var s=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService);r.emit(e.CbEvents.OnConversationListUpdated,s)}return o})}catch(e){return Promise.reject(e)}},r.markLastReadLocal=function(t,n){r.cacheManager.updateConversationLastRead(t,n);var o=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService);r.emit(e.CbEvents.OnConversationListUpdated,o)},r.pinConversation=function(t,n){void 0===n&&(n=1);try{return Promise.resolve(r.conversation.pinConversation(t,n)).then(function(o){if(0===o.code){r.cacheManager.updateConversationPinStatus(t,1===n);var s=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService);r.emit(e.CbEvents.OnConversationListUpdated,s)}return o})}catch(e){return Promise.reject(e)}},r.muteConversation=function(e,t){return void 0===t&&(t=1),r.conversation.muteConversation(e,t)},r.getChannels=function(e){return r.conversation.getChannels(e)},r.clearConversationUnread=function(t){r.cacheManager.clearConversationUnread(t);var n=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService);r.emit(e.CbEvents.OnConversationListUpdated,n)},r.clearAllConversationUnread=function(){r.cacheManager.clearAllConversationUnread();var t=r.cacheManager.getConversations(e.ConversationQueryType.CustomerService);r.emit(e.CbEvents.OnConversationListUpdated,t)},r.getContactByType=function(e,t){return r.contact.getContactByType(e,t)},r.getMemberContacts=function(e){return r.contact.getMemberContacts(e)},r.getColleagueContacts=function(e){return r.contact.getColleagueContacts(e)},r.getGroupContacts=function(e){return r.contact.getGroupContacts(e)},r.editContactTag=function(e){return r.contact.editContactTag(e)},r.getContactTag=function(e){return r.contact.getContactTag(e)},r.allocationContactTag=function(e){return r.contact.allocationContactTag(e)},r.allocationMemberTag=function(e,t,n){return void 0===n&&(n=0),r.contact.allocationMemberTag(e,t,n)},r.allocationColleagueTag=function(e,t,n){return void 0===n&&(n=0),r.contact.allocationColleagueTag(e,t,n)},r.allocationGroupTag=function(e,t,n){return void 0===n&&(n=0),r.contact.allocationGroupTag(e,t,n)},r.config.debug=o,o&&(console.log("🚀 SIM SDK Web v1.1.0 (本地开发版本)"),console.log("📦 支持协议: SSE, WebSocket")),r.cacheManager=new R({persistEnabled:!0,debug:o}),r.serviceManager=new j(r),r.initPageVisibilityDetection(),r}var o,r;r=t,(o=n).prototype=Object.create(r.prototype),o.prototype.constructor=o,h(o,r);var s,i,a=n.prototype;return a.initPageVisibilityDetection=function(){var e=this;"undefined"!=typeof document&&(this.isPageVisible=!document.hidden,this.isActuallyHidden=!this.isPageVisible,this.pageVisibilityHandler=function(){var t=e.isPageVisible;e.isPageVisible=!document.hidden,e.config.debug&&console.log("[SDK] Page visibility changed: "+(e.isPageVisible?"visible":"hidden")),t&&!e.isPageVisible?e.handlePageHidden():!t&&e.isPageVisible&&e.handlePageVisible()},document.addEventListener("visibilitychange",this.pageVisibilityHandler))},a.handlePageHidden=function(){var e=this;null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null),null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),this.pageHiddenTimer=window.setTimeout(function(){e.isPageVisible||(e.isActuallyHidden=!0,e.config.debug&&console.log("[SDK] Page is actually hidden, stopping conversation updates")),e.pageHiddenTimer=null},this.PAGE_HIDDEN_STOP_DELAY_MS)},a.handlePageVisible=function(){var e=this;null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),this.isActuallyHidden=!1,null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null),this.pageVisibleStableTimer=window.setTimeout(function(){e.isPageVisible&&e.pendingConversationUpdate&&(e.config.debug&&console.log("[SDK] Page is stable visible, triggering conversation update"),e.flushConversationUpdate()),e.pageVisibleStableTimer=null},this.PAGE_VISIBLE_STABLE_MS)},a.cleanupPageVisibilityDetection=function(){this.pageVisibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.pageVisibilityHandler),this.pageVisibilityHandler=null),null!==this.pageHiddenTimer&&(clearTimeout(this.pageHiddenTimer),this.pageHiddenTimer=null),null!==this.pageVisibleStableTimer&&(clearTimeout(this.pageVisibleStableTimer),this.pageVisibleStableTimer=null)},a.destroy=function(){this.connectionClient&&(this.connectionClient.close(),this.connectionClient=void 0),this.cacheManager.destroy(),this.cleanupPageVisibilityDetection(),null!==this.conversationUpdateTimer&&(clearTimeout(this.conversationUpdateTimer),this.conversationUpdateTimer=null),this.internalState={isConnected:!1,isLoggedIn:!1,reconnectAttempts:0,lastActivity:Date.now()},this.config.debug&&console.log("[SDK] Resources destroyed")},a.getService=function(e){return this.serviceManager.get(e)},a.isConnected=function(){return this.config.debug&&console.log("[SDK] Connection status: "+(this.internalState.isConnected?"connected":"disconnected")),this.internalState.isConnected},a.isLoggedIn=function(){return this.config.debug&&console.log("[SDK] Login status: "+(this.internalState.isLoggedIn?"logged in":"not logged in")),this.internalState.isLoggedIn},a.logRequest=function(e){var t=Math.random().toString(36).substring(2,8),n={GET:"#4CAF50",POST:"#2196F3",PUT:"#FF9800",DELETE:"#F44336"}[e.method]||"#9C27B0",o={GET:"🔍",POST:"📝",PUT:"🔄",DELETE:"🗑️"}[e.method]||"📡";console.log("%c "+(new Date).toISOString().substring(11,19)+" %c SDK %c "+o+" "+e.method+" %c "+e.url+" %c #"+t,"color: #888; font-size: 11px; padding: 2px 0;","background: #7CAEFF; color: white; font-weight: bold; font-size: 12px; border-radius: 4px; padding: 2px 6px; margin: 0 4px;","background: "+n+"; color: white; font-weight: bold; font-size: 12px; border-radius: 4px; padding: 2px 6px; margin: 0 4px;","color: #0066cc; font-weight: bold;","color: #888; font-style: italic;"),e.data&&Object.keys(e.data).length>0&&(console.log("%c─── 📦 Request Payload ───────────────────────────────","color: #999; font-style: italic;"),console.log("%c%s","color: #333; background: #f8f8f8; padding: 8px; border-radius: 4px; border-left: 4px solid #7CAEFF; font-family: monospace; line-height: 1.5;",JSON.stringify(e.data,null,2)),console.log("%c─────────────────────────────────────────────────────","color: #999;"))},a.handlePongMessage=function(e){e&&e.timestamp&&(this.config.debug&&console.log("[SDK] Received pong message with timestamp:",e.timestamp),this.internalState.isConnected=!0,this.internalState.lastActivity=Date.now())},a.isBinaryMessage=function(e){return e instanceof Uint8Array||"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer||"string"==typeof e&&this.isBase64String(e)},a.normalizeToBinaryBuffer=function(e){if(e instanceof Uint8Array)return e;if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer)return new Uint8Array(e);if("string"==typeof e)try{for(var t=atob(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}catch(e){return null}return null},a.isBase64String=function(e){try{return btoa(atob(e))===e}catch(e){return!1}},a.protoGroupChatToMessageItem=function(e){var t,n,o,r=function(t){var n;return null!=(n=e[t])?n:e[t.replace(/([A-Z])/g,"_$1").toLowerCase()]},s=function(e){return Number(r(e))||0},i=function(e){var t;return String(null!=(t=r(e))?t:"")},a=null!=(t=e.avatar_map)?t:e.avatarMap,c=s("send"),u=null!=(n=null==a||null==(o=a[c])?void 0:o.avatar)?n:"";return{msgId:s("msg_id"),groupId:s("group_id"),groupType:s("group_type"),replyMsgId:s("reply_msg_id"),clientMsgId:i("client_msg_id"),recvId:i("recv_id"),receiverName:i("receiverName")||"",userId:s("userId")||0,send:c,to:s("to")||0,username:i("username"),msgType:s("msg_type"),text:i("text")||void 0,link:i("link")||void 0,snapshot:i("snapshot")||void 0,createTime:s("create_time"),updateTime:s("update_time")||void 0,status:s("status"),avatar:u||void 0}},a.handleProtobufMessage=function(t){try{var n,o,r=function(t){var n,r,i=Number(o.ev),a=null!=(r=((n={})[e.SseEventType.EVENT_PONG_CONN]="EVENT_PONG_CONN",n[e.SseEventType.EVENT_PONG_RE_CONN]="EVENT_PONG_RE_CONN",n[e.SseEventType.EVENT_PONG_IDLE]="EVENT_PONG_IDLE",n[e.SseEventType.EVENT_MESSAGE_PUSH]="EVENT_MESSAGE_PUSH",n[e.SseEventType.EVENT_SYSTEM_MESSAGE_PUSH]="EVENT_SYSTEM_MESSAGE_PUSH",n[e.SseEventType.EVENT_LIVE_SYSTEM_MESSAGE_PUSH]="EVENT_LIVE_SYSTEM_MESSAGE_PUSH",n[e.SseEventType.EVENT_PRE_MESSAGE_PUSH]="EVENT_PRE_MESSAGE_PUSH",n[e.SseEventType.EVENT_SUBSCRIBE_MESSAGE_PUSH]="EVENT_SUBSCRIBE_MESSAGE_PUSH",n)[i])?r:"ev="+i;switch(s.config.debug?console.log("[SDK] [Proto] 解码成功",{ev:i,evName:a,keys:Object.keys(o)}):console.log("[SDK] [Proto] ev=",a),i){case e.SseEventType.EVENT_PONG_IDLE:s.internalState.isConnected=!0,s.config.debug&&console.log("[SDK] [Proto] 心跳 PONG_IDLE,已更新 isConnected");break;case e.SseEventType.EVENT_MESSAGE_PUSH:var c,u,d=null!=(c=o.group_chat_list)?c:o.groupChatList,l=(null!=(u=null==d?void 0:d.items)?u:[]).map(function(e){return s.protoGroupChatToMessageItem(e)});s.config.debug&&console.log("[SDK] [Proto] EVENT_MESSAGE_PUSH",{count:l.length,msgIds:l.map(function(e){return e.msgId}),groupIds:[].concat(new Set(l.map(function(e){return e.groupId})))}),l.forEach(function(e){return s.updateMessageCache(e)}),s.emit(e.CbEvents.OnReceiveMessages,l);break;case e.SseEventType.EVENT_SYSTEM_MESSAGE_PUSH:var g,h=null!=(g=o.sys_message)?g:o.sysMessage;s.config.debug&&console.log("[SDK] [Proto] EVENT_SYSTEM_MESSAGE_PUSH",h),s.emit(e.CbEvents.OnReceiveSystemMessage,h);break;case e.SseEventType.EVENT_PRE_MESSAGE_PUSH:var p,v=null!=(p=o.raw_data)?p:o.rawData,m="string"==typeof v?v?JSON.parse(v):void 0:null!=v?JSON.parse((new TextDecoder).decode(v)):void 0;s.config.debug&&console.log("[SDK] [Proto] EVENT_PRE_MESSAGE_PUSH",m),s.emit(e.CbEvents.OnReceivePreMessage,m);break;case e.SseEventType.EVENT_SUBSCRIBE_MESSAGE_PUSH:var f,C=null!=(f=o.subscribe_message)?f:o.subscribeMessage;s.config.debug&&console.log("[SDK] [Proto] EVENT_SUBSCRIBE_MESSAGE_PUSH",C),s.emit(e.CbEvents.OnReceiveSubscribeMessage,C);break;default:console.warn("[SDK] [Proto] 未知 ev,回退 OnReceiveProtoMessage",{ev:i,evName:a}),s.emit(e.CbEvents.OnReceiveProtoMessage,o)}},s=this,i=t instanceof Uint8Array;if(s.config.debug&&console.log("[SDK] [Proto] 入口",{type:i?"Uint8Array":"Base64",length:i||"string"==typeof t?t.length:0,preview:i&&t.length>0?"0x"+t[0].toString(16):void 0}),i)n=t.length>1?t.slice(1):t,s.config.debug&&console.log("[SDK] [Proto] 跳过首字节后 buffer.length=",n.length);else{var a=atob(t);n=new Uint8Array(a.length);for(var c=0;c<a.length;c++)n[c]=a.charCodeAt(c);n.length>1&&(n=n.slice(1)),s.config.debug&&console.log("[SDK] [Proto] Base64 解码后 buffer.length=",n.length)}var d=q(function(){return Promise.resolve(function(e){return Promise.resolve(function(){try{var e=function(){if(!N)return Promise.resolve(u.default.load("/proto/chat_message.proto")).then(function(e){N=e})}();return Promise.resolve(e&&e.then?e.then(function(){return N}):N)}catch(e){return Promise.reject(e)}}()).then(function(t){var n=t.lookupType("com.chat.proto.SseMessage"),o=n.verify(e);if(o)throw new Error(o);var r=n.decode(e);return n.toObject(r,{longs:Number})})}(n)).then(function(e){o=e})},function(e){throw console.error("[SDK] [Proto] decodeSseMessage 失败",{bufferLength:n.length,error:e}),e});return Promise.resolve(d&&d.then?d.then(r):r())}catch(e){return Promise.reject(e)}},a.initializeConversationCache=function(){try{var t=this,n=q(function(){var n=e.ConversationQueryType.CustomerService;return Promise.resolve(t.conversation.getConversations({pageNo:1,pageSize:50,queryType:n})).then(function(o){var r=o.code,s=o.data;if(t.config.debug&&console.log("[SDK] Initialize conversation cache:",r,s),0===r&&s&&s.records){t.cacheManager.setConversations(s.records,!0,n);var i=t.cacheManager.getConversations(n);t.emit(e.CbEvents.OnConversationListUpdated,i),t.config.debug&&console.log("[SDK] Conversation cache initialized with",s.records.length,"conversations")}})},function(e){console.error("[SDK] Failed to initialize conversation cache:",e)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},a.onMessage=function(t){var n=this;return this.on(e.CbEvents.OnReceiveMessage,t),function(){return n.off(e.CbEvents.OnReceiveMessage,t)}},a.onMessages=function(t){var n=this;return this.on(e.CbEvents.OnReceiveMessages,t),function(){return n.off(e.CbEvents.OnReceiveMessages,t)}},a.onConnectionChange=function(t){var n=this,o=function(){return t(!0)},r=function(){return t(!1)};return this.on(e.CbEvents.OnConnected,o),this.on(e.CbEvents.OnDisconnected,r),function(){n.off(e.CbEvents.OnConnected,o),n.off(e.CbEvents.OnDisconnected,r)}},a.onKickedOffline=function(t){var n=this;return this.on(e.CbEvents.OnKickedOffline,t),function(){return n.off(e.CbEvents.OnKickedOffline,t)}},a.updateMessageCache=function(e){e.groupId&&this.cacheManager.addGroupMessage(e),this.cacheManager.updateConversationWithMessage(e,this.config.username)&&this.scheduleConversationUpdate()},a.scheduleConversationUpdate=function(){var e=this;if(this.pendingConversationUpdate=!0,this.isActuallyHidden)this.config.debug&&console.log("[SDK] Page is actually hidden, deferring conversation update");else{var t=Date.now()-this.lastConversationUpdateTime;if(t<this.CONVERSATION_UPDATE_THROTTLE_MS){if(null!==this.conversationUpdateTimer)return;this.conversationUpdateTimer=window.setTimeout(function(){e.flushConversationUpdate()},this.CONVERSATION_UPDATE_THROTTLE_MS-t)}else this.flushConversationUpdate()}},a.flushConversationUpdate=function(){null!==this.conversationUpdateTimer&&(clearTimeout(this.conversationUpdateTimer),this.conversationUpdateTimer=null),this.pendingConversationUpdate=!1,this.lastConversationUpdateTime=Date.now();var t=this.cacheManager.getConversations(e.ConversationQueryType.CustomerService);this.emit(e.CbEvents.OnConversationListUpdated,t),this.config.debug&&console.log("[SDK] Conversation list updated, count:",t.length)},a.getCachedGroupMessages=function(e){return this.cacheManager.getGroupMessages(e)},s=n,(i=[{key:"message",get:function(){return this.getService(e.ServiceName.MESSAGE)}},{key:"conversation",get:function(){return this.getService(e.ServiceName.CONVERSATION)}},{key:"group",get:function(){return this.getService(e.ServiceName.GROUP)}},{key:"user",get:function(){return this.getService(e.ServiceName.USER)}},{key:"contact",get:function(){return this.getService(e.ServiceName.CONTACT)}},{key:"username",get:function(){return this.config.username}},{key:"getConfig",get:function(){return this.config}},{key:"getConnectionClient",get:function(){return this.connectionClient}},{key:"uuid",get:function(){return(36*Math.random()).toString(36).slice(2)+(new Date).getTime().toString()}}])&&function(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,p(o.key),o)}}(s.prototype,i),Object.defineProperty(s,"prototype",{writable:!1}),s}(b);H.BINARY_MSG_TYPE={BYTE_MESSAGE:1,HEARTBEAT_PING:125,HEARTBEAT_PONG:126},e.SIMSDK=H});
@@ -1,2 +1,10 @@
1
1
  import protobuf from "protobufjs";
2
2
  export declare function loadProtoDefinition(): Promise<protobuf.Root>;
3
+ /**
4
+ * 加载 chat_message.proto(SseMessage / GroupChat 等),用于与 JSON 一致的 emit 解析
5
+ */
6
+ export declare function getChatMessageRoot(): Promise<protobuf.Root>;
7
+ /**
8
+ * 解码 SSE 二进制为 SseMessage 结构(跳过首字节类型 0x01 后为 SseMessage 的 pb 数据)
9
+ */
10
+ export declare function decodeSseMessage(buffer: Uint8Array): Promise<Record<string, unknown>>;
@@ -77,6 +77,10 @@ export type LiveMessageParam = {
77
77
  export type ReqPageParam = {
78
78
  pageNo?: number;
79
79
  pageSize?: number;
80
+ /** 查询时间戳,不传按当前最新时间;传则查 score 之前的数据(游标分页) */
81
+ score?: number;
82
+ /** 会话列表类型:0 非客服(私聊、频道等),3 客服。不传默认 3 */
83
+ queryType?: number;
80
84
  };
81
85
  export type MarkConversationReadParam = {
82
86
  groupId?: number;
@@ -50,3 +50,15 @@ export declare enum ConnectionProtocol {
50
50
  SSE = "sse",// Server-Sent Events
51
51
  WEBSOCKET = "websocket"
52
52
  }
53
+ /**
54
+ * 会话列表查询类型(conversationList 接口 queryType)
55
+ * 0: 非客服聊天(私聊、频道等)
56
+ * 3: 客服聊天
57
+ * 不传时普通用户默认返回全部;客服主/子账号默认返回客服会话(3)
58
+ */
59
+ export declare enum ConversationQueryType {
60
+ /** 非客服:私聊、频道等 */
61
+ NonCustomer = 0,
62
+ /** 客服聊天 */
63
+ CustomerService = 3
64
+ }
@@ -10,7 +10,10 @@ declare const DEFAULT_CONFIG: {
10
10
  * 缓存管理器 - 负责内存缓存和持久化存储的管理
11
11
  */
12
12
  export declare class CacheManager {
13
- private conversationCache;
13
+ /** 按 queryType 分桶的会话列表缓存,key = String(queryType),默认 3 */
14
+ private conversationCacheByQueryType;
15
+ /** 会话 id -> queryType,用于按会话查找所在桶 */
16
+ private conversationIdToQueryType;
14
17
  private groupMessageCache;
15
18
  private accessTimeRecord;
16
19
  private pinnedConversationOrder;
@@ -36,6 +39,8 @@ export declare class CacheManager {
36
39
  * @param username 当前用户名
37
40
  */
38
41
  initialize(username?: string): void;
42
+ private getQueryTypeKey;
43
+ private getConversationBucket;
39
44
  /**
40
45
  * 清除所有缓存
41
46
  */
@@ -46,8 +51,9 @@ export declare class CacheManager {
46
51
  private clearCurrentUserStorage;
47
52
  /**
48
53
  * 获取会话缓存
54
+ * @param queryType 会话列表类型,不传默认 3(客服)
49
55
  */
50
- getConversations(): ConversationItem[];
56
+ getConversations(queryType?: number): ConversationItem[];
51
57
  /**
52
58
  * 清除指定会话的未读数
53
59
  * @param conversationId 会话ID
@@ -71,11 +77,13 @@ export declare class CacheManager {
71
77
  * 设置会话缓存
72
78
  * @param conversations 会话列表
73
79
  * @param resetPinnedOrder 是否重置置顶会话顺序(首次加载或调用 getConversations 时设为 true)
80
+ * @param queryType 会话列表类型,不传默认 3
74
81
  */
75
- setConversations(conversations: ConversationItem[], resetPinnedOrder?: boolean): void;
82
+ setConversations(conversations: ConversationItem[], resetPinnedOrder?: boolean, queryType?: number): void;
76
83
  /**
77
84
  * 添加或更新会话
78
85
  * @param conversation 会话项
86
+ * @param queryType 会话所在桶,不传则从 conversationIdToQueryType 查找
79
87
  */
80
88
  updateConversation(conversation: ConversationItem): void;
81
89
  /**
@@ -107,6 +115,7 @@ export declare class CacheManager {
107
115
  addGroupMessages(messages: MessageItem[]): void;
108
116
  /**
109
117
  * 对会话排序:置顶的会话在最上面(按初始顺序),非置顶的按最新消息时间排序
118
+ * @param queryType 只排序该桶;不传则排序所有桶
110
119
  */
111
120
  private sortConversations;
112
121
  /**
@@ -125,7 +134,7 @@ export declare class CacheManager {
125
134
  */
126
135
  private recordAccess;
127
136
  /**
128
- * 强制限制会话数量
137
+ * 强制限制会话数量(按 queryType 桶)
129
138
  */
130
139
  private enforceConversationLimit;
131
140
  /**
@@ -156,7 +165,7 @@ export declare class CacheManager {
156
165
  */
157
166
  private loadGroupMessagesFromStorage;
158
167
  /**
159
- * 保存会话列表到本地存储
168
+ * 保存会话列表到本地存储(按 queryType 分桶)
160
169
  */
161
170
  private saveConversationsToStorage;
162
171
  /**
@@ -50,7 +50,7 @@ declare class WebSocketClient {
50
50
  private notifyConnectionClosed;
51
51
  private handleReconnect;
52
52
  /**
53
- * 处理二进制消息
53
+ * 处理二进制消息(与 FRONTEND_PROTOBUF_PARSING_GUIDE_WEB.md 一致:0x01=Protobuf,0x7D=PING,0x7E=PONG)
54
54
  * @param buffer ArrayBuffer 数据
55
55
  */
56
56
  private handleBinaryMessage;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sim-sdk-web",
3
- "version": "1.2.7",
3
+ "version": "1.2.9",
4
4
  "description": "Sim SDK for Web - Support SSE and WebSocket protocols",
5
5
  "source": "src/index.ts",
6
6
  "main": "lib/index.js",