@typexim/web-sdk 0.0.8 → 0.0.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/README.md CHANGED
@@ -81,13 +81,26 @@ chat.once(
81
81
  3. getFeedList(不分页,最多100条)
82
82
  4. getFeedDetail
83
83
  5. getFeedMemberList
84
+ 6. setMute(`{ feedId, isMute }`,成功返回 Feed,失败返回 null)
85
+ 7. setPin(`{ feedId, pin }`,成功返回 Feed,失败返回 null)
86
+ 8. setName(`{ feedId, name }`,成功返回 Feed,失败返回 null)
87
+ 9. setSave(`{ feedId, isSave }`,成功返回 Feed,失败返回 null)
88
+ 10. setArchive(`{ feedId, isArchive }`,成功返回 Feed,失败返回 null)
89
+ 11. setMark(`{ feedId, isMark }`,成功返回 Feed,失败返回 null)
84
90
 
85
91
  ### 会话Feed消息
86
92
 
87
93
  1. getFeedMessageList(分页)
88
- 2. createCustomMessage
89
- 3. sendMessageToFeed
94
+ 2. createCustomMessage(可选 reply_msg_id / thread_msg_id / thread_id)
95
+ 3. sendMessageToFeed(custom 发送会转发 reply_msg_id / thread_msg_id / thread_id)
90
96
  4. sendMessageReadReceipt
97
+ 5. removeMessages(透传 twoWay / deleteFeed,deleteFeed 默认 0)
98
+ 6. addReaction
99
+ 7. deleteReaction
100
+
101
+ ### Feed 分组 Folder
102
+
103
+ 1. getFolders(可选 folderIds;folder.id 为 string)
91
104
 
92
105
  ### 聊天室Room
93
106
 
@@ -136,6 +136,10 @@ export type Feed = {
136
136
  last_message_operation_user_id: string;
137
137
  show_real?: Bool;
138
138
  is_mute?: Bool;
139
+ pin?: Bool;
140
+ is_save?: Bool;
141
+ is_archive?: Bool;
142
+ is_mark?: Bool;
139
143
  chat: {
140
144
  id: string;
141
145
  init_user_id: string;
@@ -178,7 +182,39 @@ export type Feed = {
178
182
  export type ReactionUser = Pick<Chatter, 'avatar' | 'name' | 'user_id'>;
179
183
  export type Reaction = {
180
184
  emoji: string;
181
- user_list: ReactionUser;
185
+ user_list: ReactionUser[];
186
+ };
187
+ /**
188
+ * Folder 内显式包含 / 排除 / 置顶对象引用
189
+ */
190
+ export type FeedFolderPeerRef = {
191
+ chat_id?: string;
192
+ thread_id?: string;
193
+ user_id?: string;
194
+ };
195
+ /**
196
+ * Feed 分组(Folder)配置
197
+ */
198
+ export type FeedFolder = {
199
+ /**
200
+ * 文件夹 ID(对外统一为十进制字符串,避免 JS 大整数精度丢失)
201
+ */
202
+ id: string;
203
+ name: string;
204
+ sort_order: number;
205
+ feed_sort_type: number;
206
+ show_tabs: boolean;
207
+ unread_badge: boolean;
208
+ include_types: number[];
209
+ exclude_types: number[];
210
+ include_tags: string[];
211
+ exclude_tags: string[];
212
+ include_peers: FeedFolderPeerRef[];
213
+ exclude_peers: FeedFolderPeerRef[];
214
+ pinned_peers: FeedFolderPeerRef[];
215
+ folder_type: number;
216
+ rule_type: number;
217
+ sync_type: number;
182
218
  };
183
219
  export type Message = {
184
220
  /**
@@ -193,6 +229,18 @@ export type Message = {
193
229
  * 消息串id
194
230
  */
195
231
  thread_id: string;
232
+ /**
233
+ * 被引用消息 id;无引用时为 "0"
234
+ */
235
+ reply_msg_id: string;
236
+ /**
237
+ * 是否为 Thread 根消息:1 是,0 否
238
+ */
239
+ thread_begin: number;
240
+ /**
241
+ * 发送时用于开启 / 复用 Thread 的根消息 id(仅出站可选)
242
+ */
243
+ thread_msg_id?: string;
196
244
  /**
197
245
  * 消息位置
198
246
  */
@@ -1,5 +1,5 @@
1
1
  import { RequestDirection } from '../../enums';
2
- import { Feed, Message } from '../business';
2
+ import { Feed, FeedFolder, Message } from '../business';
3
3
  import { HttpClientResponse } from './common';
4
4
  export type SDKLoginReq = {
5
5
  user_code: string;
@@ -58,7 +58,47 @@ export type SDKCreateCustomMessageReq<T = any> = {
58
58
  * 客户端自定义的消息id,发送成功后content会带
59
59
  */
60
60
  client_msg_id?: string;
61
+ /**
62
+ * 被引用消息 id
63
+ */
64
+ reply_msg_id?: string;
65
+ /**
66
+ * 开启 / 复用 Thread 的根消息 id
67
+ */
68
+ thread_msg_id?: string;
69
+ /**
70
+ * 已有 Thread id;主会话可省略
71
+ */
72
+ thread_id?: string;
73
+ };
74
+ export type SDKRemoveMessagesReq = {
75
+ feedId: string;
76
+ messageIds: string[];
77
+ /**
78
+ * 0:仅自己不可见;1:全局撤回
79
+ */
80
+ twoWay: 0 | 1;
81
+ /**
82
+ * Thread 根消息是否触发整话题删除;省略时 SDK 传 0
83
+ */
84
+ deleteFeed?: 0 | 1;
85
+ };
86
+ export type SDKReactionReq = {
87
+ feedId: string;
88
+ messageId: string;
89
+ reaction: string;
90
+ /**
91
+ * 客户端操作标识,用于关联乐观更新与推送
92
+ */
93
+ reactionOpId?: string;
94
+ };
95
+ export type SDKGetFoldersReq = {
96
+ /**
97
+ * 不传则拉取全量;传入则按 id 批量查询
98
+ */
99
+ folderIds?: string[];
61
100
  };
101
+ export type SDKGetFoldersResp = HttpClientResponse<FeedFolder[]>;
62
102
  export type SDKSendMessageReadReceiptReq = {
63
103
  /**
64
104
  * feed id
@@ -1,7 +1,7 @@
1
1
  import { LogLevel } from '../enums';
2
2
  import { CHAT_SDK_EVENT_MAP } from '../events';
3
3
  import { Chatter, Feed, Message } from '../interfaces';
4
- import { ChatSDKConfig, HttpClientResponse, SDKCreateCustomMessageReq, SDKGetFeedListResp, SDKGetFeedMessageListReq, SDKGetFeedMessageListResp, SDKGetRoomRecentMessageListResp, SDKLoginReq, SDKSendMessageReadReceiptReq, SDKSendMessageToRoomReq } from '../interfaces/sdk';
4
+ import { ChatSDKConfig, HttpClientResponse, SDKCreateCustomMessageReq, SDKGetFeedListResp, SDKGetFeedMessageListReq, SDKGetFeedMessageListResp, SDKGetFoldersResp, SDKGetRoomRecentMessageListResp, SDKLoginReq, SDKReactionReq, SDKRemoveMessagesReq, SDKSendMessageReadReceiptReq, SDKSendMessageToRoomReq } from '../interfaces/sdk';
5
5
  import Base from './Base';
6
6
  export default class ChatSDK extends Base<CHAT_SDK_EVENT_MAP> {
7
7
  private context;
@@ -119,6 +119,22 @@ export default class ChatSDK extends Base<CHAT_SDK_EVENT_MAP> {
119
119
  * @returns
120
120
  */
121
121
  getFeedMessageList(req: SDKGetFeedMessageListReq): Promise<SDKGetFeedMessageListResp>;
122
+ /**
123
+ * 删除 Feed 内选中消息(POST /message/remove)
124
+ */
125
+ removeMessages(req: SDKRemoveMessagesReq): Promise<HttpClientResponse>;
126
+ /**
127
+ * 添加消息表情回应
128
+ */
129
+ addReaction(req: SDKReactionReq): Promise<HttpClientResponse>;
130
+ /**
131
+ * 取消自己的消息表情回应
132
+ */
133
+ deleteReaction(req: SDKReactionReq): Promise<HttpClientResponse>;
134
+ /**
135
+ * 获取当前用户 Folder 配置(GET /folder)
136
+ */
137
+ getFolders(folderIds?: string[]): Promise<SDKGetFoldersResp>;
122
138
  /**
123
139
  * 本地创建一条 Feed 自定义消息
124
140
  * @param req
@@ -151,6 +167,56 @@ export default class ChatSDK extends Base<CHAT_SDK_EVENT_MAP> {
151
167
  feedId: string;
152
168
  isMute: boolean;
153
169
  }): Promise<Feed | null>;
170
+ /**
171
+ * 设置 Feed 是否置顶
172
+ * @param params.feedId Feed id
173
+ * @param params.pin 是否置顶
174
+ * @returns
175
+ */
176
+ setPin(params: {
177
+ feedId: string;
178
+ pin: boolean;
179
+ }): Promise<Feed | null>;
180
+ /**
181
+ * 设置 Feed 名称
182
+ * @param params.feedId Feed id
183
+ * @param params.name 名称
184
+ * @returns
185
+ */
186
+ setName(params: {
187
+ feedId: string;
188
+ name: string;
189
+ }): Promise<Feed | null>;
190
+ /**
191
+ * 设置 Feed 是否收藏
192
+ * @param params.feedId Feed id
193
+ * @param params.isSave 是否收藏
194
+ * @returns
195
+ */
196
+ setSave(params: {
197
+ feedId: string;
198
+ isSave: boolean;
199
+ }): Promise<Feed | null>;
200
+ /**
201
+ * 设置 Feed 是否归档
202
+ * @param params.feedId Feed id
203
+ * @param params.isArchive 是否归档
204
+ * @returns
205
+ */
206
+ setArchive(params: {
207
+ feedId: string;
208
+ isArchive: boolean;
209
+ }): Promise<Feed | null>;
210
+ /**
211
+ * 设置 Feed 是否标记
212
+ * @param params.feedId Feed id
213
+ * @param params.isMark 是否标记
214
+ * @returns
215
+ */
216
+ setMark(params: {
217
+ feedId: string;
218
+ isMark: boolean;
219
+ }): Promise<Feed | null>;
154
220
  /**
155
221
  * 离开直播间
156
222
  * @param {string} room_id 直播间id
@@ -1 +1,11 @@
1
1
  export declare const jsonParse: <T>(content: string) => T | null;
2
+ /**
3
+ * Parse JSON text while quoting numeric `id` fields as strings so uint64
4
+ * values outside Number.MAX_SAFE_INTEGER are not precision-lost by JSON.parse.
5
+ */
6
+ export declare function parseJsonPreservingIdStrings<T = unknown>(raw: string): T;
7
+ /**
8
+ * Normalize a folder id wire value to a decimal string.
9
+ * Prefer values that were already preserved as strings during parse.
10
+ */
11
+ export declare function coerceIdToString(id: unknown): string;
@@ -1 +1 @@
1
- import e from"axios";import t from"crypto-js";var s,i,n,o,r,a,d,l;!function(e){e[e.yes=1]="yes",e[e.no=0]="no"}(s||(s={})),function(e){e[e.CREATE_FEED=0]="CREATE_FEED",e[e.UPDATE_FEED=1]="UPDATE_FEED",e[e.ADD_MESSAGE=2]="ADD_MESSAGE",e[e.UPDATE_MESSAGE=3]="UPDATE_MESSAGE",e[e.UPDATE_USER_DATA=4]="UPDATE_USER_DATA",e[e.USER_LOGIN=5]="USER_LOGIN",e[e.READ_MESSAGE=6]="READ_MESSAGE",e[e.PONG_MESSAGE=8]="PONG_MESSAGE",e[e.DELETE_MESSAGE=9]="DELETE_MESSAGE",e[e.UPDATE_GROUP=12]="UPDATE_GROUP",e[e.DELETE_GROUP=13]="DELETE_GROUP",e[e.UPDATE_LOGIN_USER=17]="UPDATE_LOGIN_USER",e[e.UPDATE_MESSAGE_REACTION=19]="UPDATE_MESSAGE_REACTION",e[e.ADD_GROUP_MEMBER=21]="ADD_GROUP_MEMBER",e[e.DEL_GROUP_MEMBER=22]="DEL_GROUP_MEMBER",e[e.ADD_CONTACTS=23]="ADD_CONTACTS",e[e.UPDATE_CONTACTS=24]="UPDATE_CONTACTS",e[e.DEL_CONTACTS=25]="DEL_CONTACTS",e[e.BLOCK_USER=26]="BLOCK_USER",e[e.DEVICE_CODE=27]="DEVICE_CODE",e[e.MSG_OPEN_CLOCK=28]="MSG_OPEN_CLOCK",e[e.DELETE_SECRET_CHAT=29]="DELETE_SECRET_CHAT",e[e.DELETE_FEED=30]="DELETE_FEED",e[e.FAVORITE_UPDATE=31]="FAVORITE_UPDATE",e[e.STICKERS_UPDATE=32]="STICKERS_UPDATE",e[e.CUSTOM_STICKERS_UPDATE=33]="CUSTOM_STICKERS_UPDATE",e[e.MANAGE_DEVICE_UPDATE=34]="MANAGE_DEVICE_UPDATE",e[e.MASS_MESSAGE_UPDATE=35]="MASS_MESSAGE_UPDATE",e[e.CHAT_WALLPAPER_DELETE=36]="CHAT_WALLPAPER_DELETE",e[e.CHAT_WALLPAPER_ADD=37]="CHAT_WALLPAPER_ADD",e[e.CONTACT_REQUEST=40]="CONTACT_REQUEST",e[e.USER_PREFERENCE_CHANGE=38]="USER_PREFERENCE_CHANGE",e[e.UPDATE_GROUP_PIN=41]="UPDATE_GROUP_PIN",e[e.RTC_CANCEL=46]="RTC_CANCEL",e[e.ADD_FEED_FOLDER=43]="ADD_FEED_FOLDER",e[e.UPDATE_FEED_FOLDER=44]="UPDATE_FEED_FOLDER",e[e.UPDATE_FOLDER_FEED_LIST=47]="UPDATE_FOLDER_FEED_LIST",e[e.DELETE_FEED_FOLDER=45]="DELETE_FEED_FOLDER",e[e.UPDATE_CHATTER=42]="UPDATE_CHATTER",e[e.PAPER_KEY=48]="PAPER_KEY",e[e.PAPER_KEY_LOG=49]="PAPER_KEY_LOG",e[e.USER_LOGIN_SCAN=50]="USER_LOGIN_SCAN",e[e.RTC_RINGING=51]="RTC_RINGING",e[e.ON_UPDATE_PRIVATE_SETTING=52]="ON_UPDATE_PRIVATE_SETTING",e[e.ON_DELETE_PRIVATE_SETTING=53]="ON_DELETE_PRIVATE_SETTING",e[e.ON_UPDATE_LOGIN_PRIVATE_SETTING=54]="ON_UPDATE_LOGIN_PRIVATE_SETTING",e[e.PUSH_LIVE_MESSAGE=56]="PUSH_LIVE_MESSAGE",e[e.PUSH_SYSTEM_NOTICE=58]="PUSH_SYSTEM_NOTICE",e[e.BIG_PACKAGE_PUSH=126]="BIG_PACKAGE_PUSH",e[e.KICK_OUT_DEVICE=127]="KICK_OUT_DEVICE",e[e.CLEAR_HISTORY=128]="CLEAR_HISTORY",e[e.CLEAR_DATA=255]="CLEAR_DATA"}(i||(i={})),function(e){e[e.singleChat=1]="singleChat",e[e.groupChat=2]="groupChat"}(n||(n={})),function(e){e[e.normal=0]="normal",e[e.thread=1]="thread"}(o||(o={})),function(e){e[e.text=0]="text",e[e.system=1]="system"}(r||(r={})),function(e){e[e.text=0]="text",e[e.image=1]="image",e[e.card=2]="card",e[e.audio=3]="audio",e[e.video=4]="video",e[e.file=5]="file",e[e.mergeForward=6]="mergeForward",e[e.sticker=7]="sticker",e[e.richText=8]="richText",e[e.custom=9]="custom"}(a||(a={})),function(e){e[e.Owner=1]="Owner",e[e.Admin=2]="Admin",e[e.Common=3]="Common",e[e.Bot=4]="Bot"}(d||(d={})),function(e){e[e.normal=0]="normal",e[e.recall=1]="recall",e[e.destroy=2]="destroy",e[e.edit=3]="edit",e[e.main_delete=4]="main_delete"}(l||(l={}));const c=["api-coco.typex.im","api-tx.typex-test.cn"];var h,u,g;!function(e){e.error="ERROR",e.warning="WARNING",e.info="INFO"}(h||(h={})),function(e){e[e.SDK_ERROR=-1e4]="SDK_ERROR",e[e.NETWORK_ERROR=-9999]="NETWORK_ERROR",e[e.MAKE_SIGN_FAIL=-9998]="MAKE_SIGN_FAIL",e[e.SUCCESS=0]="SUCCESS"}(u||(u={})),function(e){e[e.up=0]="up",e[e.down=1]="down"}(g||(g={}));var _=Object.freeze({__proto__:null,get Bool(){return s},get ChatType(){return n},get FeedType(){return o},get GroupRole(){return d},get HttpClientResponseCode(){return u},get LogLevel(){return h},get MessageKind(){return r},get MessageOperation(){return l},get MessageType(){return a},get PushMessageType(){return i},RESOURCE_AUTH_DOMAINS:c,get RequestDirection(){return g}});const p={SDK_READY:"sdkReady",SDK_NOT_READY:"sdkNotReady",FEED_LIST_UPDATED:"feedListUpdated",MESSAGE_RECEIVED:"messageReceived",MESSAGE_RECALLED:"messageRecalled",MESSAGE_EDITED:"messageEdited",MESSAGE_DESTROYED:"messageDestroyed",MESSAGE_REACTION_UPDATED:"messageReactionUpdated",MESSAGE_RECEIPT_RECEIVED:"messageReceiptReceived",MESSAGE_OPEN_CLOCK:"messageOpenClock",ROOM_MESSAGE_RECEIVED:"roomMessageReceived",SYSTEM_NOTICE_RECEIVED:"systemNoticeReceived"};var E=Object.freeze({__proto__:null,CHAT_SDK_EVENT:p}),f=Object.freeze({__proto__:null});function m(e,t){return{ok:!1,code:e,msg:t}}function b(e){return{ok:!0,data:e}}const S=e=>{try{return null==e||"string"!=typeof e||0===e.length?null:JSON.parse(e)}catch{return null}},y=e=>{const t=S(e);if(null!==t){let e;return null!=t.content&&(e=S(t.content)??void 0),{client_msg_id:t.client_msg_id,content:e}}return{}},C=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),w=e=>new RegExp(`https?:\\\\?/\\\\?/${C(e)}(?:\\\\.|[^"\\\\\\s])*`,"g"),T=(e,t,s)=>{if(!e||"string"!=typeof e)return e;const i=w(t);return e.replace(i,e=>{const t=(e=>{try{return JSON.parse(`"${e}"`)}catch{return e}})(e),i=s(t);return"string"!=typeof i||i===t?e:(n=i,JSON.stringify(n).slice(1,-1));var n})};class v{constructor(e){Object.defineProperty(this,"all",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.all=e||new Map}on(e,t){const s=this.all.get(e);return s?s.push(t):this.all.set(e,[t]),()=>{this.off(e,t)}}off(e,t){const s=this.all.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let s=this.all.get(e);s&&s.slice().map(e=>{e(t)}),s=this.all.get("*"),s&&s.slice().map(s=>{s(e,t)})}once(e,t){if("*"===e){const s=(e,i)=>{t(e,i),this.off("*",s)};this.on(e,s)}else{const s=i=>{t(i),this.off(e,s)};this.on(e,s)}}}function A(e){const t=(new TextEncoder).encode(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class R extends v{constructor(e){super(),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"wsRoute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pingTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pongTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reConnectTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=e.url,this.token=e.token,this.wsRoute=e.wsRoute??null,this.logger=e.logger,this.ws=null,this.destroyed=!1,this.pingTimeout=null,this.pongTimeout=null,this.reConnectTimeout=null,this.reConnect=this.reConnect.bind(this),window.addEventListener("online",this.reConnect),this.connect()}disconnect(){this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.close(),this.ws=null),null!==this.pingTimeout&&(clearTimeout(this.pingTimeout),this.pingTimeout=null),null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null),null!==this.reConnectTimeout&&(clearTimeout(this.reConnectTimeout),this.reConnectTimeout=null)}connect(){if(this.ws)return void this.logger.warn("ReConnectWebsocket try connect but already connected");const e=new WebSocket(function(e,t={}){const s=new URL(e);return s.searchParams.set("platform",t.platform??"web"),s.searchParams.set("ws_route",t.wsRoute??""),s.toString()}(this.url,{platform:"web",wsRoute:this.wsRoute}),["typex.im.auth.v1",`typex.im.auth.b64url.${A(this.token)}`]);this.ws=e,e.onopen=()=>{this.delaySendPing()},e.onerror=e=>{this.logger.info("ReConnectWebsocket error",e)},e.onmessage=e=>{try{const t=JSON.parse(e.data);if(t.type===i.PONG_MESSAGE?null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null,this.delaySendPing()):this.sendAck(t.id),t.type===i.BIG_PACKAGE_PUSH)for(const e of t.content.big_push)this.emit("message",e);else this.emit("message",t)}catch(e){this.logger.error("ReConnectWebsocket message parse failed",e)}},e.onclose=e=>{4001===e.code?this.kickOff():this.reConnect()}}reConnect(){this.disconnect(),this.destroyed||(this.reConnectTimeout=setTimeout(()=>{this.reConnectTimeout=null,this.connect()},5e3))}send(e){if(this.destroyed)return!1;if(!this.ws)return this.logger.warn("ReConnectWebsocket send before connect"),!1;try{return this.ws.readyState!==this.ws.OPEN?(this.logger.warn("ReConnectWebsocket send but not open",this.ws.readyState),!1):(this.ws.send(JSON.stringify(e)),!0)}catch(e){return this.logger.warn("ReConnectWebsocket send error",e),!1}}sendAck(e){this.send({type:1,ids:[e]})}destroy(){this.destroyed||(this.destroyed=!0,this.disconnect(),window.removeEventListener("online",this.reConnect))}delaySendPing(){null!==this.pingTimeout&&(clearTimeout(this.pingTimeout),this.pingTimeout=null),this.pingTimeout=setTimeout(()=>{this.pingTimeout=null;this.send({type:0})?this.waitPong():this.reConnect()},2e4)}waitPong(){this.pongTimeout=setTimeout(()=>{this.logger.info("ReConnectWebsocket pong timeout"),this.reConnect()},1e4)}kickOff(){this.destroy(),this.emit("kickoff")}}class P extends v{constructor(e){super(),Object.defineProperty(this,"host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.host=e.host,this.context=e.context,this.logger=e.logger,this.ws=null}connect(){null!==this.context.loginUser?(this.ws&&(this.ws.destroy(),this.ws=null),this.ws=new R({url:`${this.host}/ws`,token:this.context.loginUser.sessionId,wsRoute:this.context.deviceId,logger:this.logger}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("kickoff",()=>{this.emit("kickoff")})):this.logger.warn("BusinessWebsocket try connect but not login")}disconnect(){this.ws?(this.ws.destroy(),this.ws=null):this.logger.info("BusinessWebsocket already disconnected")}}class D{constructor(){Object.defineProperty(this,"syncCompleted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"map",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"threadMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"targetMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"list",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.syncCompleted=!1,this.map=new Map,this.chatMap=new Map,this.threadMap=new Map,this.targetMap=new Map,this.waitMap=new Map,this.list=[]}getAll(){const e=[];for(const t of this.list){const s=this.map.get(t);s&&e.push(s)}return e}get(e){return this.map.get(e)??null}getByChat(e,t){let s;return s=t&&"0"!==t?this.threadMap.get(t):this.chatMap.get(e),void 0!==s?this.get(s):null}getByTargetId(e){const t=this.targetMap.get(e);if(void 0===t)return[];const s=[];for(const e of t){const t=this.get(e);null!==t&&s.push(t)}return s}async waitFor(e){const t=this.get(e);if(t)return t;if(this.syncCompleted)return null;let s=this.waitMap.get(e);return s||(s=(()=>{let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}})(),this.waitMap.set(e,s)),await s.promise,this.get(e)}resolveWait(e){const t=this.waitMap.get(e);t&&(t.resolve(),this.waitMap.delete(e))}removeFromList(e){const t=this.list.indexOf(e);t>-1&&this.list.splice(t,1)}remove(e){const t=this.map.get(e);if(t){if(this.map.delete(e),t.feed_type===o.thread)this.threadMap.delete(t.thread_id);else if(this.chatMap.delete(t.chat_id),t.target_id&&"0"!==t.target_id){const e=this.targetMap.get(t.target_id);void 0!==e&&(e.delete(t.id),0===e.size&&this.targetMap.delete(t.target_id))}return this.removeFromList(e),!0}return!1}beforeSave(e){if(this.map.has(e.id))this.removeFromList(e.id);else if(e.feed_type===o.thread)this.threadMap.set(e.thread_id,e.id);else if(this.chatMap.set(e.chat_id,e.id),e.target_id&&"0"!==e.target_id){if(!this.targetMap.has(e.target_id)){const t=new Set;this.targetMap.set(e.target_id,t)}this.targetMap.get(e.target_id)?.add(e.id)}this.map.set(e.id,e)}afterSave(e){this.resolveWait(e.id)}push(e){this.beforeSave(e),this.list.push(e.id),this.afterSave(e)}unshift(e){this.beforeSave(e),this.list.unshift(e.id),this.afterSave(e)}update(e){this.map.has(e.id)&&this.map.set(e.id,e)}markSyncComplete(){this.syncCompleted=!0;for(const[e,t]of this.waitMap)t.resolve();this.waitMap.clear()}isSyncCompleted(){return this.syncCompleted}reset(){this.syncCompleted=!1,this.map.clear(),this.chatMap.clear(),this.threadMap.clear(),this.targetMap.clear(),this.waitMap.clear(),this.list=[]}}function O(e){return(new TextEncoder).encode(e).buffer}async function L(e,s){return window.crypto&&window.crypto.subtle?await async function(e,t){const s=O(t),i=O(e),n=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,i);return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e,s):function(e,s){return t.HmacSHA256(e,s).toString(t.enc.Hex)}(e,s)}const I=e=>{if(null==e)return"";if("object"!=typeof e||Array.isArray(e)){if(Array.isArray(e)){let t="";for(const s of e)t+=I(s);return t}return"string"==typeof e?e:String(e)}{const t=Object.keys(e).sort();let s="";for(const i of t)s+=I(e[i]);return s}};function M(){return m(u.MAKE_SIGN_FAIL,"make sign fail")}class U{constructor(t){Object.defineProperty(this,"api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.api=e.create({baseURL:t.host,headers:{"x-developer":t.developer},withCredentials:!0}),this.context=t.context,this.logger=t.logger}async request(e){try{const{needSign:t=!0,...s}=e;if(s.headers||(s.headers={}),s.headers.platform="web",t&&"POST"===e.method?.toUpperCase()&&s.data){if(null===this.context.loginUser)return this.logger.warn("HttpClient needs make sign but not login"),M();try{const e=await(async(e,t)=>{const s=await I(e);return await L(s,t)})(s.data,this.context.loginUser.secretKey);s.headers.sign=e}catch(e){return this.logger.error("HttpClient make sign error",e),M()}}this.context.loginUser&&(s.headers["X-Sid"]=this.context.loginUser.sessionId);const i=await this.api(s),n=i.data;return n.code===u.SUCCESS?{ok:!0,data:n.data}:(this.logger.info("HttpClient server error",i),{ok:!1,code:n.code,msg:n.msg,msg_i18n:n.msg_i18n})}catch{return{ok:!1,code:u.NETWORK_ERROR,msg:"network error"}}}get(e,t,s){return this.request({url:e,method:"GET",params:t,...s})}post(e,t,s){return this.request({url:e,method:"POST",data:t,...s})}}function x(e){return`${e}`.padStart(2,"0")}class k{constructor(){Object.defineProperty(this,"level",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.level=h.error,this.logHandler=this.createLogHandler()}getPriority(e){switch(e){case h.error:return 3;case h.warning:return 2;case h.info:return 1;default:return 0}}createLogHandler(){return(e,...t)=>{const s=new Date,i=`TypeX >> [${`${s.getFullYear()}-${x(s.getMonth()+1)}-${x(s.getDate())} ${x(s.getHours())}:${x(s.getMinutes())}:${x(s.getSeconds())}.${s.getMilliseconds()}`}]`;switch(e){case h.error:console.error(i,"[ERR]",...t);break;case h.warning:console.warn(i,"[WARN]",...t);break;case h.info:console.info(i,"[INFO]",...t);break;default:console.log(i,...t)}}}log(e,...t){this.getPriority(e)>=this.getPriority(this.level)&&this.logHandler(e,...t)}setLogLevel(e){this.level=e,this.logHandler=this.createLogHandler()}info(...e){this.log(h.info,...e)}warn(...e){this.log(h.warning,...e)}error(...e){this.log(h.error,...e)}}class G{constructor(e){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"emitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleKickoff",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.context=e.context,this.logger=e.logger,this.emitter=e.emitter,this.feedCache=e.feedCache,this.handleKickoff=e.onKickoff}emitFeedListUpdated(){this.emitter.emit(p.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}processCreateFeed(e){this.feedCache.unshift(e.content),this.emitFeedListUpdated()}processUpdateFeed(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===s)return;const i={...s,...t};this.feedCache.update(i),this.emitFeedListUpdated()}processDeleteFeed(e){this.feedCache.remove(e.content.id)&&this.emitFeedListUpdated()}processAddMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,i=e.content;if(i.hide_ids.includes(t))return;const n=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null!==n){if(i.no_last_msg!==s.yes){let e=!1,o=!1;const a={};if(i.message_kind_id!==r.system&&i.sender_id!==t&&i.no_read!==s.yes){e=!0;const t=new Set(n.unread_message_ids);t.add(i.id),a.unread_message_ids=[...t],a.badge=t.size}if(n.last_message_position<i.position&&(e=!0,o=!0,a.last_message_id=i.id,a.last_message_position=i.position,a.last_message_sender_id=i.sender_id,a.last_message_send_at=i.send_at,a.last_message_kind_id=i.message_kind_id,a.last_message_type_id=i.message_type_id,a.last_message=i.content,a.last_message_operation=i.operation,a.last_message_operation_user_id=i.operation_user_id),e){const e={...n,...a};o?this.feedCache.unshift(e):this.feedCache.update(e),this.emitFeedListUpdated()}}this.emitter.emit(p.MESSAGE_RECEIVED,{feed_id:n.id,message:i})}}processUpdateMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==s&&null!=t.operation){let e=!1;const i={};if(t.operation===l.recall||t.operation===l.destroy){if(null!=s.unread_message_ids&&s.unread_message_ids.includes(t.id)){e=!0;const n=new Set(s.unread_message_ids);n.delete(t.id),i.unread_message_ids=[...n],i.badge=i.unread_message_ids.length}s.last_message_id===t.id&&(e=!0,i.last_message=t.content??"{}",i.last_message_operation=t.operation,i.last_message_operation_user_id=t.operation_user_id??"0")}else t.operation===l.edit&&s.last_message_id===t.id&&(e=!0,i.last_message_kind_id=t.message_kind_id,i.last_message_type_id=t.message_type_id,i.last_message=t.content,i.last_message_operation=t.operation,i.last_message_operation_user_id=t.operation_user_id);e&&(this.feedCache.update({...s,...i}),this.emitFeedListUpdated()),t.operation===l.recall?this.emitter.emit(p.MESSAGE_RECALLED,{message_ids:[t.id]}):t.operation===l.edit?null!=t.content&&null!=t.edited_at&&null!=t.message_kind_id&&null!=t.message_type_id&&null!=t.operation_user_id&&this.emitter.emit(p.MESSAGE_EDITED,{chat_id:t.chat_id,content:t.content,edited_at:t.edited_at,id:t.id,message_kind_id:t.message_kind_id,message_type_id:t.message_type_id,operation:t.operation,operation_user_id:t.operation_user_id,thread_id:t.thread_id}):t.operation===l.destroy&&this.emitter.emit(p.MESSAGE_DESTROYED,{feed_id:s.id,message_ids:[t.id]})}}processDeleteMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===s)return;let i=!1;const n={};s.last_message_id===t.id&&(i=!0,n.last_message=t.content??"{}",n.last_message_operation=t.operation,n.last_message_operation_user_id=t.operation_user_id??"0"),i&&(this.feedCache.update({...s,...n}),this.emitFeedListUpdated()),this.emitter.emit(p.MESSAGE_DESTROYED,{feed_id:s.id,message_ids:[t.id]})}processOpenClockMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==s&&Array.isArray(t.msgs_open_clock)){const e=t.msgs_open_clock.map(e=>e.message_id);this.emitter.emit(p.MESSAGE_OPEN_CLOCK,{feed_id:s.id,message_ids:e})}}processPushLiveMessage(e){this.emitter.emit(p.ROOM_MESSAGE_RECEIVED,{room_id:e.content.room_id,content:e.content.message})}processPushSystemNotice(e){this.emitter.emit(p.SYSTEM_NOTICE_RECEIVED,{content:e.content})}processReadMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,s=e.content,i=this.feedCache.getByChat(s.chat_id,s.thread_id);if(null===i)return;let n=!1;const o={};if(s.reader_ids.includes(t)&&s.message_ids.length>0){n=!0;const e=new Set(i.unread_message_ids);s.message_ids.forEach(t=>{e.delete(t)}),o.unread_message_ids=[...e],o.badge=e.size}n&&(this.feedCache.update({...i,...o}),this.emitFeedListUpdated()),this.emitter.emit(p.MESSAGE_RECEIPT_RECEIVED,{feed_id:i.id,message_ids:s.message_ids,reader_user_ids:s.reader_ids})}processKickOutDevice(){this.handleKickoff()}processGroupMember(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,"0");if(null===s)return;const n=new Set(s.chat_member),o=e.type===i.ADD_GROUP_MEMBER,r=e.type===i.DEL_GROUP_MEMBER;t.chat_member.forEach(e=>{o?n.add(e.chat_id):r&&n.delete(e.chat_id)}),this.feedCache.update({...s,chat_member:[...n]}),this.emitFeedListUpdated()}processUpdateGroup(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,"0");if(null===s)return;let i=!1;const n={};null!=t.avatar&&(i=!0,n.avatar=t.avatar),null!=t.name&&(i=!0,n.name=t.name),i&&(this.feedCache.update({...s,...n}),this.emitFeedListUpdated())}processUpdateUserData(e){const t=e.content,s=this.feedCache.getByTargetId(t.id);if(s.length>0){const e={};if(null!=t.avatar&&(e.avatar=t.avatar),null!=t.first_name||null!=t.last_name){let s=t.first_name??"";null!=t.last_name&&(s=s.length>0?`${s} ${t.last_name}`:t.last_name),e.name=s}for(const t of s)this.feedCache.update({...t,...e});this.emitFeedListUpdated()}}processUpdateMessageReaction(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);null!==s&&this.emitter.emit(p.MESSAGE_REACTION_UPDATED,{feed_id:s.id,message_id:t.message_id,reactions:t.reactions})}process(e){switch(this.logger.info("PushMessageProcessor process",e),e.type){case i.CREATE_FEED:this.processCreateFeed(e);break;case i.UPDATE_FEED:this.processUpdateFeed(e);break;case i.DELETE_FEED:this.processDeleteFeed(e);break;case i.ADD_MESSAGE:this.processAddMessage(e);break;case i.UPDATE_MESSAGE:this.processUpdateMessage(e);break;case i.DELETE_MESSAGE:this.processDeleteMessage(e);break;case i.PUSH_LIVE_MESSAGE:this.processPushLiveMessage(e);break;case i.MSG_OPEN_CLOCK:this.processOpenClockMessage(e);break;case i.PUSH_SYSTEM_NOTICE:this.processPushSystemNotice(e);break;case i.READ_MESSAGE:this.processReadMessage(e);break;case i.KICK_OUT_DEVICE:this.processKickOutDevice();break;case i.ADD_GROUP_MEMBER:case i.DEL_GROUP_MEMBER:this.processGroupMember(e);break;case i.UPDATE_GROUP:this.processUpdateGroup(e);break;case i.UPDATE_USER_DATA:this.processUpdateUserData(e);break;case i.UPDATE_MESSAGE_REACTION:this.processUpdateMessageReaction(e)}}}class N{static set(e){localStorage.setItem(this.key,JSON.stringify(e))}static get(){try{const e=localStorage.getItem(this.key);if(!e)return null;return JSON.parse(e)}catch{return null}}static clear(){localStorage.removeItem(this.key)}}Object.defineProperty(N,"key",{enumerable:!0,configurable:!0,writable:!0,value:"__typex_sdk_data__"});const F="__typex_sdk_tab_session_message__";function j(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function K(e){if(!e||"object"!=typeof e)return!1;const t=e,s=t.loginUser;return(null===t.deviceId||"string"==typeof t.deviceId)&&!!s&&"string"==typeof s.userId&&"string"==typeof s.secretKey&&"string"==typeof s.sessionId}class B{constructor(e={}){Object.defineProperty(this,"tabId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"closed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledSessionRequestIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledLogoutIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledLoginIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingSessionRequests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getCurrentSession",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onLogoutBroadcast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onLoginBroadcast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tabId=j(),this.channel=null,this.closed=!1,this.handledSessionRequestIds=new Set,this.handledLogoutIds=new Set,this.handledLoginIds=new Set,this.pendingSessionRequests=new Map,this.getCurrentSession=e.getCurrentSession??null,this.onLogoutBroadcast=e.onLogoutBroadcast??null,this.onLoginBroadcast=e.onLoginBroadcast??null,this.logger=e.logger??null,this.handleBroadcastMessage=this.handleBroadcastMessage.bind(this),this.handleStorageMessage=this.handleStorageMessage.bind(this),"undefined"!=typeof BroadcastChannel&&(this.channel=new BroadcastChannel("typex-sdk-tab-session"),this.channel.onmessage=this.handleBroadcastMessage),"undefined"!=typeof window&&window.addEventListener("storage",this.handleStorageMessage)}publishLogout(){this.publish({type:"logout",senderTabId:this.tabId,logoutId:j(),createdAt:Date.now()})}publishLogin(e){this.publish({type:"login",senderTabId:this.tabId,loginId:j(),createdAt:Date.now(),session:e})}requestCurrentSession(e=500){if(this.closed)return Promise.resolve(null);const t=j();return new Promise(s=>{const i=setTimeout(()=>{this.pendingSessionRequests.delete(t),s(null)},e);this.pendingSessionRequests.set(t,{resolve:s,timeout:i}),this.publish({type:"session-request",senderTabId:this.tabId,requestId:t,createdAt:Date.now()})})}destroy(){this.closed||(this.closed=!0,this.pendingSessionRequests.forEach(e=>{clearTimeout(e.timeout),e.resolve(null)}),this.pendingSessionRequests.clear(),this.channel&&(this.channel.close(),this.channel=null),"undefined"!=typeof window&&window.removeEventListener("storage",this.handleStorageMessage))}publish(e){if(!this.closed&&(this.channel&&this.channel.postMessage(e),"session-response"!==e.type&&"login"!==e.type&&"undefined"!=typeof localStorage))try{localStorage.setItem(F,JSON.stringify({...e,storageNonce:j()}))}catch(e){this.logger?.warn("TabSessionCoordinator storage publish failed",e)}}handleBroadcastMessage(e){this.handleMessage(e.data)}handleStorageMessage(e){if(e.key===F&&e.newValue)try{this.handleMessage(JSON.parse(e.newValue))}catch(e){this.logger?.warn("TabSessionCoordinator storage parse failed",e)}}handleMessage(e){if(!this.closed&&function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.senderTabId&&("session-request"===t.type?"string"==typeof t.requestId&&"number"==typeof t.createdAt:"session-response"===t.type?"string"==typeof t.requesterTabId&&"string"==typeof t.requestId&&"number"==typeof t.createdAt&&K(t.session):"logout"===t.type?"string"==typeof t.logoutId&&"number"==typeof t.createdAt:"login"===t.type&&"string"==typeof t.loginId&&"number"==typeof t.createdAt&&K(t.session))}(e)&&e.senderTabId!==this.tabId){if("logout"===e.type){if(this.handledLogoutIds.has(e.logoutId))return;return this.handledLogoutIds.add(e.logoutId),void this.onLogoutBroadcast?.()}if("login"===e.type){if(this.handledLoginIds.has(e.loginId))return;return this.handledLoginIds.add(e.loginId),void this.onLoginBroadcast?.(e.session)}if("session-request"===e.type){const t=`${e.senderTabId}:${e.requestId}`;if(this.handledSessionRequestIds.has(t))return;this.handledSessionRequestIds.add(t);const s=this.getCurrentSession?.();if(!s)return;return void this.publish({type:"session-response",senderTabId:this.tabId,requesterTabId:e.senderTabId,requestId:e.requestId,createdAt:Date.now(),session:s})}if("session-response"===e.type){if(e.requesterTabId!==this.tabId)return;const t=this.pendingSessionRequests.get(e.requestId);if(!t)return;clearTimeout(t.timeout),this.pendingSessionRequests.delete(e.requestId),t.resolve(e.session)}}}}class H{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.version=0}increment(){this.version++}get(){return this.version}check(e){return e===this.version}}class q extends v{constructor(e){super(),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tabSessionCoordinator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"restoreLoginPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"httpClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pushMessageProcessor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handlePageHide",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.ws.disconnect()}}),Object.defineProperty(this,"handlePageShow",{enumerable:!0,configurable:!0,writable:!0,value:e=>{e.persisted&&this.context.isLogin&&this.ws.connect()}}),this.context={isLogin:!1,loginUser:null,isReady:!1,deviceId:null},this.version=new H,this.logger=new k,this.restoreLoginPromise=null,this.tabSessionCoordinator=new B({logger:this.logger,getCurrentSession:()=>this.getTransferableLoginSession(),onLogoutBroadcast:()=>{this.afterLogout()},onLoginBroadcast:e=>{this.applySharedLoginSession(e)}}),this.httpClient=new U({host:e.httpHost,context:this.context,logger:this.logger,developer:e.developer}),this.feedCache=new D,this.ws=new P({host:e.websocketHost,context:this.context,logger:this.logger}),this.pushMessageProcessor=new G({context:this.context,logger:this.logger,emitter:this,feedCache:this.feedCache,onKickoff:()=>{this.afterLogout()}}),this.init()}init(){this.loadContext(),this.ws.on("message",e=>{this.pushMessageProcessor.process(e)}),this.ws.on("kickoff",()=>{this.afterLogout()}),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.handlePageHide),window.addEventListener("pageshow",this.handlePageShow)),setTimeout(()=>{this.restoreLoginFromActiveTab()},0)}getTransferableLoginSession(){return this.context.isLogin&&null!==this.context.loginUser?{deviceId:this.context.deviceId,loginUser:{...this.context.loginUser}}:null}async restoreLoginFromActiveTab(){if(this.restoreLoginPromise)return this.restoreLoginPromise;this.restoreLoginPromise=this.doRestoreLoginFromActiveTab();try{return await this.restoreLoginPromise}finally{this.restoreLoginPromise=null}}async doRestoreLoginFromActiveTab(){if(this.context.isLogin)return!0;const e=await this.tabSessionCoordinator.requestCurrentSession(500);return!e||this.context.isLogin?this.context.isLogin:this.applySharedLoginSession(e)}async applySharedLoginSession(e){return this.context.isLogin||(this.context.isLogin=!0,this.context.loginUser=e.loginUser,e.deviceId&&(this.context.deviceId=e.deviceId),await this.requestDeviceId(),this.applyLoginStatus()),!0}async requestDeviceId(){if(this.context.deviceId)return!0;const e=await this.httpClient.post("/device_api/device_id",{platform:"web",hash_str:""},{needSign:!1});return!!e.ok&&(this.context.deviceId=e.data,this.saveContext(),!0)}saveContext(){const{context:e}=this;N.set({deviceId:e.deviceId})}loadContext(){const e=N.get();e&&e.deviceId&&(this.context.deviceId=e.deviceId)}applyLoginStatus(){this.version.increment(),this.saveContext(),this.context.isLogin?(this.ws.connect(),this.loadFeedList(),this.context.isReady=!0,this.emit(p.SDK_READY)):(this.ws.disconnect(),this.feedCache.reset(),this.context.isReady=!1,this.emit(p.SDK_NOT_READY))}async loadFeedList(){const e=this.version.get(),t={refresh_at:null,feed_id:null};for(;;){const s=await this.httpClient.get("/feed",{limit:500,last_refresh_at:t.refresh_at??void 0,last_feed_id:t.feed_id??void 0});if(!this.version.check(e))break;if(!s.ok||null===s.data)break;if(t.refresh_at=s.data.refresh_at,t.feed_id=s.data.last_feed_id,(s.data.feed_list??[]).forEach(e=>{this.feedCache.push(e)}),!s.data.has_more)break}this.version.check(e)&&(this.feedCache.markSyncComplete(),this.emit(p.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:!0}))}isReady(){return this.context.isReady}setLogLevel(e){this.logger.setLogLevel(e)}async login(e){if(this.context.isLogin)return b(null);if(await this.restoreLoginFromActiveTab()||this.context.isLogin)return b(null);if(await this.requestDeviceId(),!this.context.deviceId)return this.logger.error("Get deviceId failed"),m(u.SDK_ERROR,"Get deviceId failed");const t=await this.httpClient.post("/user/session/login",{userCode:e.user_code,device_id:this.context.deviceId},{needSign:!1});if(!t.ok)return t;this.context.isLogin=!0,this.context.loginUser={userId:t.data.id,secretKey:t.data.key,sessionId:e.user_code},this.applyLoginStatus();const s=this.getTransferableLoginSession();return s&&this.tabSessionCoordinator.publishLogin(s),b(null)}async logout(){if(!this.context.isLogin)return b(null);const e=await this.httpClient.get("/user/logout");return e.ok?(this.tabSessionCoordinator.publishLogout(),this.afterLogout(),b(null)):e}afterLogout(){(this.context.isLogin||this.context.isReady)&&(this.context.isLogin=!1,this.context.loginUser=null,this.applyLoginStatus())}getLoginUser(){return null===this.context.loginUser?null:this.context.loginUser.userId}async createSingleChatFeed(e){return await this.httpClient.post("/chat/single",{receiver_id:e})}async deleteFeed(e){return await this.httpClient.post("/feed/delete",{feed_id_list:[e],delete_peer:!0})}async getFeedList(){return b({list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}async getFeedDetail(e){return b(await this.feedCache.waitFor(e))}async getFeedMemberList(e){const t=await this.feedCache.get(e);return null!==t&&t.chat_member.length>0?await this.httpClient.post("/chat/chatter_info",{chatters:{[t.chat_id]:t.chat_member}}):b([])}async getUserByUids(e){const t=await this.httpClient.post("/user/users_info",e);return t.ok?b(t.data.map(e=>({id:e.id}))):t}getDomain(e){const[t,s]=c,i=w(t),n=w(s);for(const o of e){if(i.test(o.content))return t;if(n.test(o.content))return s}}appendXsid(e){if(!this.context.loginUser?.sessionId)return e;const t=this.context.loginUser.sessionId,s=this.getDomain(e);return s?e.map(e=>{const i=T(e.content,s,e=>((e,t,s)=>{const i=encodeURIComponent(t),n=encodeURIComponent(s),o=e.indexOf("#"),r=o>=0?e.slice(0,o):e,a=o>=0?e.slice(o):"",d=new RegExp(`([?&])${C(i)}=[^&#]*`);if(d.test(r))return r.replace(d,`$1${i}=${n}`)+a;const l=r.includes("?")?"&":"?";return`${r}${l}${i}=${n}${a}`})(e,"xsid",t));return{...e,content:i}}):e}async markFeedMessageAsRead(e){const t=this.feedCache.get(e);if(!t)return b(!1);if(!(await this.httpClient.post("/feed/update",{id:t.id,mark_unread:s.yes})).ok)return b(!1);return(await this.httpClient.post("/message/read",{chat_id:t.chat_id,thread_id:t.thread_id})).ok?b(!0):b(!1)}async getMessagesByIds(e,t){const s=this.feedCache.get(e);if(!s||!Array.isArray(t)||0===t.length)return b([]);const i=await this.httpClient.post("/message/get_by_msgid",{chat_msg_id_map:{[s.chat_id]:t}});if(i.ok){return b(this.appendXsid(i.data[s.chat_id]))}return b([])}async getFeedMessageList(e){const t=await this.getFeedDetail(e.feed_id);if(t.ok&&t.data){const s=t.data,{chat_id:i,first_position:n,last_message_position:o}=s,{positions:r,nextPosition:a,hasMore:d}=(e=>{const t=[];if(e.direction===g.up){let s=e.startPosition??e.maxPosition;for(;t.length<e.limit&&s>=e.minPosition;)t.push(s),s--;const i=s>=e.minPosition;let n;return i&&(n=s),{positions:t,nextPosition:n,hasMore:i}}{let s=e.startPosition??e.minPosition;for(;t.length<e.limit&&s<=e.maxPosition;)t.push(s),s++;const i=s<=e.maxPosition;let n;return i&&(n=s),{positions:t,nextPosition:n,hasMore:i}}})({maxPosition:o,minPosition:n,startPosition:e.message_position,limit:e.limit,direction:e.direction??g.up});if(r.length>0){const e=await this.httpClient.post("/message/get_by_position",{chat_position:{[i]:r}},{needSign:!1});if(e.ok&&e.data[i]){return b({has_more:d,list:this.appendXsid(e.data[i].reverse()),next_message_position:a})}}}return b({has_more:!1,list:[]})}createCustomMessage(e){if(null===this.context.loginUser)return m(u.SDK_ERROR,"not login");const t=this.feedCache.get(e.feed_id);if(null===t)return m(u.SDK_ERROR,"not found feed");const s=(new Date).toISOString();var i;return b({id:"",chat_id:t.chat_id,thread_id:t.thread_id,position:t.last_message_position,sender_id:this.context.loginUser.userId,message_kind_id:r.text,message_type_id:a.custom,send_at:s,edited_at:s,reader_ids:[],unreader_ids:[],hide_ids:[],operation:l.normal,operation_user_id:"0",content:(i={client_msg_id:e.client_msg_id,content:e.content},JSON.stringify({client_msg_id:i.client_msg_id,content:JSON.stringify(i.content)})),reactions:[]})}async sendMessageToFeed(e){if(e.message_type_id===a.custom){const t=y(e.content);return this.httpClient.post("/message/send_custom",{chat_id:e.chat_id,thread_id:e.thread_id,client_id:t.client_msg_id,content:null==t.content?void 0:JSON.stringify(t.content)})}return m(u.SDK_ERROR,"not support")}async sendMessageReadReceipt(e){const t=this.feedCache.get(e.feed_id);return null===t?m(u.SDK_ERROR,"not found feed"):await this.httpClient.post("/message/read",{chat_id:t.chat_id,message_ids:e.message_ids})}async joinRoom(e){return await this.httpClient.post("/liveshow/join",{room_id:e})}async setMute(e){const t=await this.httpClient.post("/feed/update",{id:e.feedId,is_mute:e.isMute?s.yes:s.no});return t.ok?t.data:null}async leaveRoom(e){return await this.httpClient.post("/liveshow/leave",{room_id:e})}async getJoinedRooms(){return await this.httpClient.get("/liveshow/joined_rooms")}async getRoomRecentMessageList(e){const t=await this.httpClient.get("/liveshow/get_recent_message",{room_id:e});return t.ok?b(t.data):t}async sendMessageToRoom(e){return await this.httpClient.post("/liveshow/send_message",{room_id:e.room_id,content:e.content})}}const $=new Map;function V(e,t){let s=$.get(e);return void 0===s&&(s=new q(t),$.set(e,s)),s}const W={parseSystemMessageContent:e=>{const t=S(e);return null!==t?{text:t.text,text_i18n:t.text_i18n}:{}},parseTextMessageContent:e=>{const t=S(e);return null!==t?{text:t.text,client_msg_id:t.client_msg_id}:{}},parseCustomMessageContent:y};export{q as ChatSDK,V as create,_ as enums,E as events,f as interfaces,W as utils};
1
+ import e from"axios";import t from"crypto-js";var s,i,n,o,r,a,d,l;!function(e){e[e.yes=1]="yes",e[e.no=0]="no"}(s||(s={})),function(e){e[e.CREATE_FEED=0]="CREATE_FEED",e[e.UPDATE_FEED=1]="UPDATE_FEED",e[e.ADD_MESSAGE=2]="ADD_MESSAGE",e[e.UPDATE_MESSAGE=3]="UPDATE_MESSAGE",e[e.UPDATE_USER_DATA=4]="UPDATE_USER_DATA",e[e.USER_LOGIN=5]="USER_LOGIN",e[e.READ_MESSAGE=6]="READ_MESSAGE",e[e.PONG_MESSAGE=8]="PONG_MESSAGE",e[e.DELETE_MESSAGE=9]="DELETE_MESSAGE",e[e.UPDATE_GROUP=12]="UPDATE_GROUP",e[e.DELETE_GROUP=13]="DELETE_GROUP",e[e.UPDATE_LOGIN_USER=17]="UPDATE_LOGIN_USER",e[e.UPDATE_MESSAGE_REACTION=19]="UPDATE_MESSAGE_REACTION",e[e.ADD_GROUP_MEMBER=21]="ADD_GROUP_MEMBER",e[e.DEL_GROUP_MEMBER=22]="DEL_GROUP_MEMBER",e[e.ADD_CONTACTS=23]="ADD_CONTACTS",e[e.UPDATE_CONTACTS=24]="UPDATE_CONTACTS",e[e.DEL_CONTACTS=25]="DEL_CONTACTS",e[e.BLOCK_USER=26]="BLOCK_USER",e[e.DEVICE_CODE=27]="DEVICE_CODE",e[e.MSG_OPEN_CLOCK=28]="MSG_OPEN_CLOCK",e[e.DELETE_SECRET_CHAT=29]="DELETE_SECRET_CHAT",e[e.DELETE_FEED=30]="DELETE_FEED",e[e.FAVORITE_UPDATE=31]="FAVORITE_UPDATE",e[e.STICKERS_UPDATE=32]="STICKERS_UPDATE",e[e.CUSTOM_STICKERS_UPDATE=33]="CUSTOM_STICKERS_UPDATE",e[e.MANAGE_DEVICE_UPDATE=34]="MANAGE_DEVICE_UPDATE",e[e.MASS_MESSAGE_UPDATE=35]="MASS_MESSAGE_UPDATE",e[e.CHAT_WALLPAPER_DELETE=36]="CHAT_WALLPAPER_DELETE",e[e.CHAT_WALLPAPER_ADD=37]="CHAT_WALLPAPER_ADD",e[e.CONTACT_REQUEST=40]="CONTACT_REQUEST",e[e.USER_PREFERENCE_CHANGE=38]="USER_PREFERENCE_CHANGE",e[e.UPDATE_GROUP_PIN=41]="UPDATE_GROUP_PIN",e[e.RTC_CANCEL=46]="RTC_CANCEL",e[e.ADD_FEED_FOLDER=43]="ADD_FEED_FOLDER",e[e.UPDATE_FEED_FOLDER=44]="UPDATE_FEED_FOLDER",e[e.UPDATE_FOLDER_FEED_LIST=47]="UPDATE_FOLDER_FEED_LIST",e[e.DELETE_FEED_FOLDER=45]="DELETE_FEED_FOLDER",e[e.UPDATE_CHATTER=42]="UPDATE_CHATTER",e[e.PAPER_KEY=48]="PAPER_KEY",e[e.PAPER_KEY_LOG=49]="PAPER_KEY_LOG",e[e.USER_LOGIN_SCAN=50]="USER_LOGIN_SCAN",e[e.RTC_RINGING=51]="RTC_RINGING",e[e.ON_UPDATE_PRIVATE_SETTING=52]="ON_UPDATE_PRIVATE_SETTING",e[e.ON_DELETE_PRIVATE_SETTING=53]="ON_DELETE_PRIVATE_SETTING",e[e.ON_UPDATE_LOGIN_PRIVATE_SETTING=54]="ON_UPDATE_LOGIN_PRIVATE_SETTING",e[e.PUSH_LIVE_MESSAGE=56]="PUSH_LIVE_MESSAGE",e[e.PUSH_SYSTEM_NOTICE=58]="PUSH_SYSTEM_NOTICE",e[e.BIG_PACKAGE_PUSH=126]="BIG_PACKAGE_PUSH",e[e.KICK_OUT_DEVICE=127]="KICK_OUT_DEVICE",e[e.CLEAR_HISTORY=128]="CLEAR_HISTORY",e[e.CLEAR_DATA=255]="CLEAR_DATA"}(i||(i={})),function(e){e[e.singleChat=1]="singleChat",e[e.groupChat=2]="groupChat"}(n||(n={})),function(e){e[e.normal=0]="normal",e[e.thread=1]="thread"}(o||(o={})),function(e){e[e.text=0]="text",e[e.system=1]="system"}(r||(r={})),function(e){e[e.text=0]="text",e[e.image=1]="image",e[e.card=2]="card",e[e.audio=3]="audio",e[e.video=4]="video",e[e.file=5]="file",e[e.mergeForward=6]="mergeForward",e[e.sticker=7]="sticker",e[e.richText=8]="richText",e[e.custom=9]="custom"}(a||(a={})),function(e){e[e.Owner=1]="Owner",e[e.Admin=2]="Admin",e[e.Common=3]="Common",e[e.Bot=4]="Bot"}(d||(d={})),function(e){e[e.normal=0]="normal",e[e.recall=1]="recall",e[e.destroy=2]="destroy",e[e.edit=3]="edit",e[e.main_delete=4]="main_delete"}(l||(l={}));const c=["api-coco.typex.im","api-tx.typex-test.cn"];var h,u,g;!function(e){e.error="ERROR",e.warning="WARNING",e.info="INFO"}(h||(h={})),function(e){e[e.SDK_ERROR=-1e4]="SDK_ERROR",e[e.NETWORK_ERROR=-9999]="NETWORK_ERROR",e[e.MAKE_SIGN_FAIL=-9998]="MAKE_SIGN_FAIL",e[e.SUCCESS=0]="SUCCESS"}(u||(u={})),function(e){e[e.up=0]="up",e[e.down=1]="down"}(g||(g={}));var _=Object.freeze({__proto__:null,get Bool(){return s},get ChatType(){return n},get FeedType(){return o},get GroupRole(){return d},get HttpClientResponseCode(){return u},get LogLevel(){return h},get MessageKind(){return r},get MessageOperation(){return l},get MessageType(){return a},get PushMessageType(){return i},RESOURCE_AUTH_DOMAINS:c,get RequestDirection(){return g}});const p={SDK_READY:"sdkReady",SDK_NOT_READY:"sdkNotReady",FEED_LIST_UPDATED:"feedListUpdated",MESSAGE_RECEIVED:"messageReceived",MESSAGE_RECALLED:"messageRecalled",MESSAGE_EDITED:"messageEdited",MESSAGE_DESTROYED:"messageDestroyed",MESSAGE_REACTION_UPDATED:"messageReactionUpdated",MESSAGE_RECEIPT_RECEIVED:"messageReceiptReceived",MESSAGE_OPEN_CLOCK:"messageOpenClock",ROOM_MESSAGE_RECEIVED:"roomMessageReceived",SYSTEM_NOTICE_RECEIVED:"systemNoticeReceived"};var f=Object.freeze({__proto__:null,CHAT_SDK_EVENT:p}),m=Object.freeze({__proto__:null});function E(e,t){return{ok:!1,code:e,msg:t}}function b(e){return{ok:!0,data:e}}const y=e=>{try{return null==e||"string"!=typeof e||0===e.length?null:JSON.parse(e)}catch{return null}};const S=e=>{const t=y(e);if(null!==t){let e;return null!=t.content&&(e=y(t.content)??void 0),{client_msg_id:t.client_msg_id,content:e}}return{}},C=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),w=e=>new RegExp(`https?:\\\\?/\\\\?/${C(e)}(?:\\\\.|[^"\\\\\\s])*`,"g"),v=(e,t,s)=>{if(!e||"string"!=typeof e)return e;const i=w(t);return e.replace(i,e=>{const t=(e=>{try{return JSON.parse(`"${e}"`)}catch{return e}})(e),i=s(t);return"string"!=typeof i||i===t?e:(n=i,JSON.stringify(n).slice(1,-1));var n})};class T{constructor(e){Object.defineProperty(this,"all",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.all=e||new Map}on(e,t){const s=this.all.get(e);return s?s.push(t):this.all.set(e,[t]),()=>{this.off(e,t)}}off(e,t){const s=this.all.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let s=this.all.get(e);s&&s.slice().map(e=>{e(t)}),s=this.all.get("*"),s&&s.slice().map(s=>{s(e,t)})}once(e,t){if("*"===e){const s=(e,i)=>{t(e,i),this.off("*",s)};this.on(e,s)}else{const s=i=>{t(i),this.off(e,s)};this.on(e,s)}}}function R(e){const t=(new TextEncoder).encode(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class A extends T{constructor(e){super(),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"wsRoute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pingTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pongTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reConnectTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=e.url,this.token=e.token,this.wsRoute=e.wsRoute??null,this.logger=e.logger,this.ws=null,this.destroyed=!1,this.pingTimeout=null,this.pongTimeout=null,this.reConnectTimeout=null,this.reConnect=this.reConnect.bind(this),window.addEventListener("online",this.reConnect),this.connect()}disconnect(){this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.close(),this.ws=null),null!==this.pingTimeout&&(clearTimeout(this.pingTimeout),this.pingTimeout=null),null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null),null!==this.reConnectTimeout&&(clearTimeout(this.reConnectTimeout),this.reConnectTimeout=null)}connect(){if(this.ws)return void this.logger.warn("ReConnectWebsocket try connect but already connected");const e=new WebSocket(function(e,t={}){const s=new URL(e);return s.searchParams.set("platform",t.platform??"web"),s.searchParams.set("ws_route",t.wsRoute??""),s.toString()}(this.url,{platform:"web",wsRoute:this.wsRoute}),["typex.im.auth.v1",`typex.im.auth.b64url.${R(this.token)}`]);this.ws=e,e.onopen=()=>{this.delaySendPing()},e.onerror=e=>{this.logger.info("ReConnectWebsocket error",e)},e.onmessage=e=>{try{const t=JSON.parse(e.data);if(t.type===i.PONG_MESSAGE?null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null,this.delaySendPing()):this.sendAck(t.id),t.type===i.BIG_PACKAGE_PUSH)for(const e of t.content.big_push)this.emit("message",e);else this.emit("message",t)}catch(e){this.logger.error("ReConnectWebsocket message parse failed",e)}},e.onclose=e=>{4001===e.code?this.kickOff():this.reConnect()}}reConnect(){this.disconnect(),this.destroyed||(this.reConnectTimeout=setTimeout(()=>{this.reConnectTimeout=null,this.connect()},5e3))}send(e){if(this.destroyed)return!1;if(!this.ws)return this.logger.warn("ReConnectWebsocket send before connect"),!1;try{return this.ws.readyState!==this.ws.OPEN?(this.logger.warn("ReConnectWebsocket send but not open",this.ws.readyState),!1):(this.ws.send(JSON.stringify(e)),!0)}catch(e){return this.logger.warn("ReConnectWebsocket send error",e),!1}}sendAck(e){this.send({type:1,ids:[e]})}destroy(){this.destroyed||(this.destroyed=!0,this.disconnect(),window.removeEventListener("online",this.reConnect))}delaySendPing(){null!==this.pingTimeout&&(clearTimeout(this.pingTimeout),this.pingTimeout=null),this.pingTimeout=setTimeout(()=>{this.pingTimeout=null;this.send({type:0})?this.waitPong():this.reConnect()},2e4)}waitPong(){this.pongTimeout=setTimeout(()=>{this.logger.info("ReConnectWebsocket pong timeout"),this.reConnect()},1e4)}kickOff(){this.destroy(),this.emit("kickoff")}}class P extends T{constructor(e){super(),Object.defineProperty(this,"host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.host=e.host,this.context=e.context,this.logger=e.logger,this.ws=null}connect(){null!==this.context.loginUser?(this.ws&&(this.ws.destroy(),this.ws=null),this.ws=new A({url:`${this.host}/ws`,token:this.context.loginUser.sessionId,wsRoute:this.context.deviceId,logger:this.logger}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("kickoff",()=>{this.emit("kickoff")})):this.logger.warn("BusinessWebsocket try connect but not login")}disconnect(){this.ws?(this.ws.destroy(),this.ws=null):this.logger.info("BusinessWebsocket already disconnected")}}class D{constructor(){Object.defineProperty(this,"syncCompleted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"map",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"threadMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"targetMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"list",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.syncCompleted=!1,this.map=new Map,this.chatMap=new Map,this.threadMap=new Map,this.targetMap=new Map,this.waitMap=new Map,this.list=[]}getAll(){const e=[];for(const t of this.list){const s=this.map.get(t);s&&e.push(s)}return e}get(e){return this.map.get(e)??null}getByChat(e,t){let s;return s=t&&"0"!==t?this.threadMap.get(t):this.chatMap.get(e),void 0!==s?this.get(s):null}getByTargetId(e){const t=this.targetMap.get(e);if(void 0===t)return[];const s=[];for(const e of t){const t=this.get(e);null!==t&&s.push(t)}return s}async waitFor(e){const t=this.get(e);if(t)return t;if(this.syncCompleted)return null;let s=this.waitMap.get(e);return s||(s=(()=>{let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}})(),this.waitMap.set(e,s)),await s.promise,this.get(e)}resolveWait(e){const t=this.waitMap.get(e);t&&(t.resolve(),this.waitMap.delete(e))}removeFromList(e){const t=this.list.indexOf(e);t>-1&&this.list.splice(t,1)}remove(e){const t=this.map.get(e);if(t){if(this.map.delete(e),t.feed_type===o.thread)this.threadMap.delete(t.thread_id);else if(this.chatMap.delete(t.chat_id),t.target_id&&"0"!==t.target_id){const e=this.targetMap.get(t.target_id);void 0!==e&&(e.delete(t.id),0===e.size&&this.targetMap.delete(t.target_id))}return this.removeFromList(e),!0}return!1}beforeSave(e){if(this.map.has(e.id))this.removeFromList(e.id);else if(e.feed_type===o.thread)this.threadMap.set(e.thread_id,e.id);else if(this.chatMap.set(e.chat_id,e.id),e.target_id&&"0"!==e.target_id){if(!this.targetMap.has(e.target_id)){const t=new Set;this.targetMap.set(e.target_id,t)}this.targetMap.get(e.target_id)?.add(e.id)}this.map.set(e.id,e)}afterSave(e){this.resolveWait(e.id)}push(e){this.beforeSave(e),this.list.push(e.id),this.afterSave(e)}unshift(e){this.beforeSave(e),this.list.unshift(e.id),this.afterSave(e)}update(e){this.map.has(e.id)&&this.map.set(e.id,e)}markSyncComplete(){this.syncCompleted=!0;for(const[e,t]of this.waitMap)t.resolve();this.waitMap.clear()}isSyncCompleted(){return this.syncCompleted}reset(){this.syncCompleted=!1,this.map.clear(),this.chatMap.clear(),this.threadMap.clear(),this.targetMap.clear(),this.waitMap.clear(),this.list=[]}}function O(e){return(new TextEncoder).encode(e).buffer}async function I(e,s){return window.crypto&&window.crypto.subtle?await async function(e,t){const s=O(t),i=O(e),n=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,i);return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e,s):function(e,s){return t.HmacSHA256(e,s).toString(t.enc.Hex)}(e,s)}const L=e=>{if(null==e)return"";if("object"!=typeof e||Array.isArray(e)){if(Array.isArray(e)){let t="";for(const s of e)t+=L(s);return t}return"string"==typeof e?e:String(e)}{const t=Object.keys(e).sort();let s="";for(const i of t)s+=L(e[i]);return s}};function M(){return E(u.MAKE_SIGN_FAIL,"make sign fail")}class U{constructor(t){Object.defineProperty(this,"api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.api=e.create({baseURL:t.host,headers:{"x-developer":t.developer},withCredentials:!0}),this.context=t.context,this.logger=t.logger}async request(e){try{const{needSign:t=!0,...s}=e;if(s.headers||(s.headers={}),s.headers.platform="web",t&&"POST"===e.method?.toUpperCase()&&s.data){if(null===this.context.loginUser)return this.logger.warn("HttpClient needs make sign but not login"),M();try{const e=await(async(e,t)=>{const s=await L(e);return await I(s,t)})(s.data,this.context.loginUser.secretKey);s.headers.sign=e}catch(e){return this.logger.error("HttpClient make sign error",e),M()}}this.context.loginUser&&(s.headers["X-Sid"]=this.context.loginUser.sessionId);const i=await this.api(s),n=i.data;return n.code===u.SUCCESS?{ok:!0,data:n.data}:(this.logger.info("HttpClient server error",i),{ok:!1,code:n.code,msg:n.msg,msg_i18n:n.msg_i18n})}catch{return{ok:!1,code:u.NETWORK_ERROR,msg:"network error"}}}get(e,t,s){return this.request({url:e,method:"GET",params:t,...s})}post(e,t,s){return this.request({url:e,method:"POST",data:t,...s})}}function k(e){return`${e}`.padStart(2,"0")}class x{constructor(){Object.defineProperty(this,"level",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.level=h.error,this.logHandler=this.createLogHandler()}getPriority(e){switch(e){case h.error:return 3;case h.warning:return 2;case h.info:return 1;default:return 0}}createLogHandler(){return(e,...t)=>{const s=new Date,i=`TypeX >> [${`${s.getFullYear()}-${k(s.getMonth()+1)}-${k(s.getDate())} ${k(s.getHours())}:${k(s.getMinutes())}:${k(s.getSeconds())}.${s.getMilliseconds()}`}]`;switch(e){case h.error:console.error(i,"[ERR]",...t);break;case h.warning:console.warn(i,"[WARN]",...t);break;case h.info:console.info(i,"[INFO]",...t);break;default:console.log(i,...t)}}}log(e,...t){this.getPriority(e)>=this.getPriority(this.level)&&this.logHandler(e,...t)}setLogLevel(e){this.level=e,this.logHandler=this.createLogHandler()}info(...e){this.log(h.info,...e)}warn(...e){this.log(h.warning,...e)}error(...e){this.log(h.error,...e)}}class G{constructor(e){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"emitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleKickoff",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.context=e.context,this.logger=e.logger,this.emitter=e.emitter,this.feedCache=e.feedCache,this.handleKickoff=e.onKickoff}emitFeedListUpdated(){this.emitter.emit(p.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}processCreateFeed(e){this.feedCache.unshift(e.content),this.emitFeedListUpdated()}processUpdateFeed(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===s)return;const i={...s,...t};this.feedCache.update(i),this.emitFeedListUpdated()}processDeleteFeed(e){this.feedCache.remove(e.content.id)&&this.emitFeedListUpdated()}processAddMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,i=e.content;if(i.hide_ids.includes(t))return;const n=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null!==n){if(i.no_last_msg!==s.yes){let e=!1,o=!1;const a={};if(i.message_kind_id!==r.system&&i.sender_id!==t&&i.no_read!==s.yes){e=!0;const t=new Set(n.unread_message_ids);t.add(i.id),a.unread_message_ids=[...t],a.badge=t.size}if(n.last_message_position<i.position&&(e=!0,o=!0,a.last_message_id=i.id,a.last_message_position=i.position,a.last_message_sender_id=i.sender_id,a.last_message_send_at=i.send_at,a.last_message_kind_id=i.message_kind_id,a.last_message_type_id=i.message_type_id,a.last_message=i.content,a.last_message_operation=i.operation,a.last_message_operation_user_id=i.operation_user_id),e){const e={...n,...a};o?this.feedCache.unshift(e):this.feedCache.update(e),this.emitFeedListUpdated()}}this.emitter.emit(p.MESSAGE_RECEIVED,{feed_id:n.id,message:i})}}processUpdateMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==s&&null!=t.operation){let e=!1;const i={};if(t.operation===l.recall||t.operation===l.destroy){if(null!=s.unread_message_ids&&s.unread_message_ids.includes(t.id)){e=!0;const n=new Set(s.unread_message_ids);n.delete(t.id),i.unread_message_ids=[...n],i.badge=i.unread_message_ids.length}s.last_message_id===t.id&&(e=!0,i.last_message=t.content??"{}",i.last_message_operation=t.operation,i.last_message_operation_user_id=t.operation_user_id??"0")}else t.operation===l.edit&&s.last_message_id===t.id&&(e=!0,i.last_message_kind_id=t.message_kind_id,i.last_message_type_id=t.message_type_id,i.last_message=t.content,i.last_message_operation=t.operation,i.last_message_operation_user_id=t.operation_user_id);e&&(this.feedCache.update({...s,...i}),this.emitFeedListUpdated()),t.operation===l.recall?this.emitter.emit(p.MESSAGE_RECALLED,{message_ids:[t.id]}):t.operation===l.edit?null!=t.content&&null!=t.edited_at&&null!=t.message_kind_id&&null!=t.message_type_id&&null!=t.operation_user_id&&this.emitter.emit(p.MESSAGE_EDITED,{chat_id:t.chat_id,content:t.content,edited_at:t.edited_at,id:t.id,message_kind_id:t.message_kind_id,message_type_id:t.message_type_id,operation:t.operation,operation_user_id:t.operation_user_id,thread_id:t.thread_id}):t.operation===l.destroy&&this.emitter.emit(p.MESSAGE_DESTROYED,{feed_id:s.id,message_ids:[t.id]})}}processDeleteMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===s)return;let i=!1;const n={};s.last_message_id===t.id&&(i=!0,n.last_message=t.content??"{}",n.last_message_operation=t.operation,n.last_message_operation_user_id=t.operation_user_id??"0"),i&&(this.feedCache.update({...s,...n}),this.emitFeedListUpdated()),this.emitter.emit(p.MESSAGE_DESTROYED,{feed_id:s.id,message_ids:[t.id]})}processOpenClockMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==s&&Array.isArray(t.msgs_open_clock)){const e=t.msgs_open_clock.map(e=>e.message_id);this.emitter.emit(p.MESSAGE_OPEN_CLOCK,{feed_id:s.id,message_ids:e})}}processPushLiveMessage(e){this.emitter.emit(p.ROOM_MESSAGE_RECEIVED,{room_id:e.content.room_id,content:e.content.message})}processPushSystemNotice(e){this.emitter.emit(p.SYSTEM_NOTICE_RECEIVED,{content:e.content})}processReadMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,s=e.content,i=this.feedCache.getByChat(s.chat_id,s.thread_id);if(null===i)return;let n=!1;const o={};if(s.reader_ids.includes(t)&&s.message_ids.length>0){n=!0;const e=new Set(i.unread_message_ids);s.message_ids.forEach(t=>{e.delete(t)}),o.unread_message_ids=[...e],o.badge=e.size}n&&(this.feedCache.update({...i,...o}),this.emitFeedListUpdated()),this.emitter.emit(p.MESSAGE_RECEIPT_RECEIVED,{feed_id:i.id,message_ids:s.message_ids,reader_user_ids:s.reader_ids})}processKickOutDevice(){this.handleKickoff()}processGroupMember(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,"0");if(null===s)return;const n=new Set(s.chat_member),o=e.type===i.ADD_GROUP_MEMBER,r=e.type===i.DEL_GROUP_MEMBER;t.chat_member.forEach(e=>{o?n.add(e.chat_id):r&&n.delete(e.chat_id)}),this.feedCache.update({...s,chat_member:[...n]}),this.emitFeedListUpdated()}processUpdateGroup(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,"0");if(null===s)return;let i=!1;const n={};null!=t.avatar&&(i=!0,n.avatar=t.avatar),null!=t.name&&(i=!0,n.name=t.name),i&&(this.feedCache.update({...s,...n}),this.emitFeedListUpdated())}processUpdateUserData(e){const t=e.content,s=this.feedCache.getByTargetId(t.id);if(s.length>0){const e={};if(null!=t.avatar&&(e.avatar=t.avatar),null!=t.first_name||null!=t.last_name){let s=t.first_name??"";null!=t.last_name&&(s=s.length>0?`${s} ${t.last_name}`:t.last_name),e.name=s}for(const t of s)this.feedCache.update({...t,...e});this.emitFeedListUpdated()}}processUpdateMessageReaction(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);null!==s&&this.emitter.emit(p.MESSAGE_REACTION_UPDATED,{feed_id:s.id,message_id:t.message_id,reactions:t.reactions})}process(e){switch(this.logger.info("PushMessageProcessor process",e),e.type){case i.CREATE_FEED:this.processCreateFeed(e);break;case i.UPDATE_FEED:this.processUpdateFeed(e);break;case i.DELETE_FEED:this.processDeleteFeed(e);break;case i.ADD_MESSAGE:this.processAddMessage(e);break;case i.UPDATE_MESSAGE:this.processUpdateMessage(e);break;case i.DELETE_MESSAGE:this.processDeleteMessage(e);break;case i.PUSH_LIVE_MESSAGE:this.processPushLiveMessage(e);break;case i.MSG_OPEN_CLOCK:this.processOpenClockMessage(e);break;case i.PUSH_SYSTEM_NOTICE:this.processPushSystemNotice(e);break;case i.READ_MESSAGE:this.processReadMessage(e);break;case i.KICK_OUT_DEVICE:this.processKickOutDevice();break;case i.ADD_GROUP_MEMBER:case i.DEL_GROUP_MEMBER:this.processGroupMember(e);break;case i.UPDATE_GROUP:this.processUpdateGroup(e);break;case i.UPDATE_USER_DATA:this.processUpdateUserData(e);break;case i.UPDATE_MESSAGE_REACTION:this.processUpdateMessageReaction(e)}}}class N{static set(e){localStorage.setItem(this.key,JSON.stringify(e))}static get(){try{const e=localStorage.getItem(this.key);if(!e)return null;return JSON.parse(e)}catch{return null}}static clear(){localStorage.removeItem(this.key)}}Object.defineProperty(N,"key",{enumerable:!0,configurable:!0,writable:!0,value:"__typex_sdk_data__"});const F="__typex_sdk_tab_session_message__";function j(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function K(e){if(!e||"object"!=typeof e)return!1;const t=e,s=t.loginUser;return(null===t.deviceId||"string"==typeof t.deviceId)&&!!s&&"string"==typeof s.userId&&"string"==typeof s.secretKey&&"string"==typeof s.sessionId}class B{constructor(e={}){Object.defineProperty(this,"tabId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"closed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledSessionRequestIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledLogoutIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledLoginIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingSessionRequests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getCurrentSession",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onLogoutBroadcast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onLoginBroadcast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tabId=j(),this.channel=null,this.closed=!1,this.handledSessionRequestIds=new Set,this.handledLogoutIds=new Set,this.handledLoginIds=new Set,this.pendingSessionRequests=new Map,this.getCurrentSession=e.getCurrentSession??null,this.onLogoutBroadcast=e.onLogoutBroadcast??null,this.onLoginBroadcast=e.onLoginBroadcast??null,this.logger=e.logger??null,this.handleBroadcastMessage=this.handleBroadcastMessage.bind(this),this.handleStorageMessage=this.handleStorageMessage.bind(this),"undefined"!=typeof BroadcastChannel&&(this.channel=new BroadcastChannel("typex-sdk-tab-session"),this.channel.onmessage=this.handleBroadcastMessage),"undefined"!=typeof window&&window.addEventListener("storage",this.handleStorageMessage)}publishLogout(){this.publish({type:"logout",senderTabId:this.tabId,logoutId:j(),createdAt:Date.now()})}publishLogin(e){this.publish({type:"login",senderTabId:this.tabId,loginId:j(),createdAt:Date.now(),session:e})}requestCurrentSession(e=500){if(this.closed)return Promise.resolve(null);const t=j();return new Promise(s=>{const i=setTimeout(()=>{this.pendingSessionRequests.delete(t),s(null)},e);this.pendingSessionRequests.set(t,{resolve:s,timeout:i}),this.publish({type:"session-request",senderTabId:this.tabId,requestId:t,createdAt:Date.now()})})}destroy(){this.closed||(this.closed=!0,this.pendingSessionRequests.forEach(e=>{clearTimeout(e.timeout),e.resolve(null)}),this.pendingSessionRequests.clear(),this.channel&&(this.channel.close(),this.channel=null),"undefined"!=typeof window&&window.removeEventListener("storage",this.handleStorageMessage))}publish(e){if(!this.closed&&(this.channel&&this.channel.postMessage(e),"session-response"!==e.type&&"login"!==e.type&&"undefined"!=typeof localStorage))try{localStorage.setItem(F,JSON.stringify({...e,storageNonce:j()}))}catch(e){this.logger?.warn("TabSessionCoordinator storage publish failed",e)}}handleBroadcastMessage(e){this.handleMessage(e.data)}handleStorageMessage(e){if(e.key===F&&e.newValue)try{this.handleMessage(JSON.parse(e.newValue))}catch(e){this.logger?.warn("TabSessionCoordinator storage parse failed",e)}}handleMessage(e){if(!this.closed&&function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.senderTabId&&("session-request"===t.type?"string"==typeof t.requestId&&"number"==typeof t.createdAt:"session-response"===t.type?"string"==typeof t.requesterTabId&&"string"==typeof t.requestId&&"number"==typeof t.createdAt&&K(t.session):"logout"===t.type?"string"==typeof t.logoutId&&"number"==typeof t.createdAt:"login"===t.type&&"string"==typeof t.loginId&&"number"==typeof t.createdAt&&K(t.session))}(e)&&e.senderTabId!==this.tabId){if("logout"===e.type){if(this.handledLogoutIds.has(e.logoutId))return;return this.handledLogoutIds.add(e.logoutId),void this.onLogoutBroadcast?.()}if("login"===e.type){if(this.handledLoginIds.has(e.loginId))return;return this.handledLoginIds.add(e.loginId),void this.onLoginBroadcast?.(e.session)}if("session-request"===e.type){const t=`${e.senderTabId}:${e.requestId}`;if(this.handledSessionRequestIds.has(t))return;this.handledSessionRequestIds.add(t);const s=this.getCurrentSession?.();if(!s)return;return void this.publish({type:"session-response",senderTabId:this.tabId,requesterTabId:e.senderTabId,requestId:e.requestId,createdAt:Date.now(),session:s})}if("session-response"===e.type){if(e.requesterTabId!==this.tabId)return;const t=this.pendingSessionRequests.get(e.requestId);if(!t)return;clearTimeout(t.timeout),this.pendingSessionRequests.delete(e.requestId),t.resolve(e.session)}}}}class H{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.version=0}increment(){this.version++}get(){return this.version}check(e){return e===this.version}}class q extends T{constructor(e){super(),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tabSessionCoordinator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"restoreLoginPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"httpClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pushMessageProcessor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handlePageHide",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.ws.disconnect()}}),Object.defineProperty(this,"handlePageShow",{enumerable:!0,configurable:!0,writable:!0,value:e=>{e.persisted&&this.context.isLogin&&this.ws.connect()}}),this.context={isLogin:!1,loginUser:null,isReady:!1,deviceId:null},this.version=new H,this.logger=new x,this.restoreLoginPromise=null,this.tabSessionCoordinator=new B({logger:this.logger,getCurrentSession:()=>this.getTransferableLoginSession(),onLogoutBroadcast:()=>{this.afterLogout()},onLoginBroadcast:e=>{this.applySharedLoginSession(e)}}),this.httpClient=new U({host:e.httpHost,context:this.context,logger:this.logger,developer:e.developer}),this.feedCache=new D,this.ws=new P({host:e.websocketHost,context:this.context,logger:this.logger}),this.pushMessageProcessor=new G({context:this.context,logger:this.logger,emitter:this,feedCache:this.feedCache,onKickoff:()=>{this.afterLogout()}}),this.init()}init(){this.loadContext(),this.ws.on("message",e=>{this.pushMessageProcessor.process(e)}),this.ws.on("kickoff",()=>{this.afterLogout()}),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.handlePageHide),window.addEventListener("pageshow",this.handlePageShow)),setTimeout(()=>{this.restoreLoginFromActiveTab()},0)}getTransferableLoginSession(){return this.context.isLogin&&null!==this.context.loginUser?{deviceId:this.context.deviceId,loginUser:{...this.context.loginUser}}:null}async restoreLoginFromActiveTab(){if(this.restoreLoginPromise)return this.restoreLoginPromise;this.restoreLoginPromise=this.doRestoreLoginFromActiveTab();try{return await this.restoreLoginPromise}finally{this.restoreLoginPromise=null}}async doRestoreLoginFromActiveTab(){if(this.context.isLogin)return!0;const e=await this.tabSessionCoordinator.requestCurrentSession(500);return!e||this.context.isLogin?this.context.isLogin:this.applySharedLoginSession(e)}async applySharedLoginSession(e){return this.context.isLogin||(this.context.isLogin=!0,this.context.loginUser=e.loginUser,e.deviceId&&(this.context.deviceId=e.deviceId),await this.requestDeviceId(),this.applyLoginStatus()),!0}async requestDeviceId(){if(this.context.deviceId)return!0;const e=await this.httpClient.post("/device_api/device_id",{platform:"web",hash_str:""},{needSign:!1});return!!e.ok&&(this.context.deviceId=e.data,this.saveContext(),!0)}saveContext(){const{context:e}=this;N.set({deviceId:e.deviceId})}loadContext(){const e=N.get();e&&e.deviceId&&(this.context.deviceId=e.deviceId)}applyLoginStatus(){this.version.increment(),this.saveContext(),this.context.isLogin?(this.ws.connect(),this.loadFeedList(),this.context.isReady=!0,this.emit(p.SDK_READY)):(this.ws.disconnect(),this.feedCache.reset(),this.context.isReady=!1,this.emit(p.SDK_NOT_READY))}async loadFeedList(){const e=this.version.get(),t={refresh_at:null,feed_id:null};for(;;){const s=await this.httpClient.get("/feed",{limit:500,last_refresh_at:t.refresh_at??void 0,last_feed_id:t.feed_id??void 0});if(!this.version.check(e))break;if(!s.ok||null===s.data)break;if(t.refresh_at=s.data.refresh_at,t.feed_id=s.data.last_feed_id,(s.data.feed_list??[]).forEach(e=>{this.feedCache.push(e)}),!s.data.has_more)break}this.version.check(e)&&(this.feedCache.markSyncComplete(),this.emit(p.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:!0}))}isReady(){return this.context.isReady}setLogLevel(e){this.logger.setLogLevel(e)}async login(e){if(this.context.isLogin)return b(null);if(await this.restoreLoginFromActiveTab()||this.context.isLogin)return b(null);if(await this.requestDeviceId(),!this.context.deviceId)return this.logger.error("Get deviceId failed"),E(u.SDK_ERROR,"Get deviceId failed");const t=await this.httpClient.post("/user/session/login",{userCode:e.user_code,device_id:this.context.deviceId},{needSign:!1});if(!t.ok)return t;this.context.isLogin=!0,this.context.loginUser={userId:t.data.id,secretKey:t.data.key,sessionId:e.user_code},this.applyLoginStatus();const s=this.getTransferableLoginSession();return s&&this.tabSessionCoordinator.publishLogin(s),b(null)}async logout(){if(!this.context.isLogin)return b(null);const e=await this.httpClient.get("/user/logout");return e.ok?(this.tabSessionCoordinator.publishLogout(),this.afterLogout(),b(null)):e}afterLogout(){(this.context.isLogin||this.context.isReady)&&(this.context.isLogin=!1,this.context.loginUser=null,this.applyLoginStatus())}getLoginUser(){return null===this.context.loginUser?null:this.context.loginUser.userId}async createSingleChatFeed(e){return await this.httpClient.post("/chat/single",{receiver_id:e})}async deleteFeed(e){return await this.httpClient.post("/feed/delete",{feed_id_list:[e],delete_peer:!0})}async getFeedList(){return b({list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}async getFeedDetail(e){return b(await this.feedCache.waitFor(e))}async getFeedMemberList(e){const t=await this.feedCache.get(e);return null!==t&&t.chat_member.length>0?await this.httpClient.post("/chat/chatter_info",{chatters:{[t.chat_id]:t.chat_member}}):b([])}async getUserByUids(e){const t=await this.httpClient.post("/user/users_info",e);return t.ok?b(t.data.map(e=>({id:e.id}))):t}getDomain(e){const[t,s]=c,i=w(t),n=w(s);for(const o of e){if(i.test(o.content))return t;if(n.test(o.content))return s}}appendXsid(e){if(!this.context.loginUser?.sessionId)return e;const t=this.context.loginUser.sessionId,s=this.getDomain(e);return s?e.map(e=>{const i=v(e.content,s,e=>((e,t,s)=>{const i=encodeURIComponent(t),n=encodeURIComponent(s),o=e.indexOf("#"),r=o>=0?e.slice(0,o):e,a=o>=0?e.slice(o):"",d=new RegExp(`([?&])${C(i)}=[^&#]*`);if(d.test(r))return r.replace(d,`$1${i}=${n}`)+a;const l=r.includes("?")?"&":"?";return`${r}${l}${i}=${n}${a}`})(e,"xsid",t));return{...e,content:i}}):e}async markFeedMessageAsRead(e){const t=this.feedCache.get(e);if(!t)return b(!1);if(!(await this.httpClient.post("/feed/update",{id:t.id,mark_unread:s.yes})).ok)return b(!1);return(await this.httpClient.post("/message/read",{chat_id:t.chat_id,thread_id:t.thread_id})).ok?b(!0):b(!1)}async getMessagesByIds(e,t){const s=this.feedCache.get(e);if(!s||!Array.isArray(t)||0===t.length)return b([]);const i=await this.httpClient.post("/message/get_by_msgid",{chat_msg_id_map:{[s.chat_id]:t}});if(i.ok){return b(this.appendXsid(i.data[s.chat_id]))}return b([])}async getFeedMessageList(e){const t=await this.getFeedDetail(e.feed_id);if(t.ok&&t.data){const s=t.data,{chat_id:i,first_position:n,last_message_position:o}=s,{positions:r,nextPosition:a,hasMore:d}=(e=>{const t=[];if(e.direction===g.up){let s=e.startPosition??e.maxPosition;for(;t.length<e.limit&&s>=e.minPosition;)t.push(s),s--;const i=s>=e.minPosition;let n;return i&&(n=s),{positions:t,nextPosition:n,hasMore:i}}{let s=e.startPosition??e.minPosition;for(;t.length<e.limit&&s<=e.maxPosition;)t.push(s),s++;const i=s<=e.maxPosition;let n;return i&&(n=s),{positions:t,nextPosition:n,hasMore:i}}})({maxPosition:o,minPosition:n,startPosition:e.message_position,limit:e.limit,direction:e.direction??g.up});if(r.length>0){const e=await this.httpClient.post("/message/get_by_position",{chat_position:{[i]:r}},{needSign:!1});if(e.ok&&e.data[i]){return b({has_more:d,list:this.appendXsid(e.data[i].reverse()),next_message_position:a})}}}return b({has_more:!1,list:[]})}async removeMessages(e){const t=this.feedCache.get(e.feedId);return null===t?E(u.SDK_ERROR,"not found feed"):this.httpClient.post("/message/remove",{chat_id:t.chat_id,message_ids:e.messageIds,two_way:e.twoWay,delete_feed:e.deleteFeed??0})}async addReaction(e){if(!e.reaction)return E(u.SDK_ERROR,"reaction is empty");const t=this.feedCache.get(e.feedId);return null===t?E(u.SDK_ERROR,"not found feed"):this.httpClient.post("/message/reaction/add",{feed_id:t.id,chat_id:t.chat_id,message_id:e.messageId,reaction:e.reaction,reaction_op_id:e.reactionOpId})}async deleteReaction(e){if(!e.reaction)return E(u.SDK_ERROR,"reaction is empty");const t=this.feedCache.get(e.feedId);return null===t?E(u.SDK_ERROR,"not found feed"):this.httpClient.post("/message/reaction/delete",{feed_id:t.id,chat_id:t.chat_id,message_id:e.messageId,reaction:e.reaction,reaction_op_id:e.reactionOpId})}async getFolders(e){const t=e&&e.length>0?{folder_ids:e.join(",")}:void 0,s=await this.httpClient.get("/folder",t,{transformResponse:[e=>"string"!=typeof e?e:function(e){const t=e.replace(/("id"\s*:\s*)(-?\d+)(\s*[,}\]])/g,'$1"$2"$3');return JSON.parse(t)}(e)]});if(!s.ok)return s;return b((s.data??[]).map(e=>{return{...e,id:(t=e.id,"string"==typeof t?t:"bigint"==typeof t?t.toString():"number"==typeof t&&Number.isFinite(t)?Math.trunc(t).toString():String(t))};var t}))}createCustomMessage(e){if(null===this.context.loginUser)return E(u.SDK_ERROR,"not login");const t=this.feedCache.get(e.feed_id);if(null===t)return E(u.SDK_ERROR,"not found feed");const s=(new Date).toISOString();var i;return b({id:"",chat_id:t.chat_id,thread_id:e.thread_id??t.thread_id,reply_msg_id:e.reply_msg_id??"0",thread_begin:0,thread_msg_id:e.thread_msg_id,position:t.last_message_position,sender_id:this.context.loginUser.userId,message_kind_id:r.text,message_type_id:a.custom,send_at:s,edited_at:s,reader_ids:[],unreader_ids:[],hide_ids:[],operation:l.normal,operation_user_id:"0",content:(i={client_msg_id:e.client_msg_id,content:e.content},JSON.stringify({client_msg_id:i.client_msg_id,content:JSON.stringify(i.content)})),reactions:[]})}async sendMessageToFeed(e){if(e.message_type_id===a.custom){const t=S(e.content),s={chat_id:e.chat_id,thread_id:e.thread_id,client_id:t.client_msg_id,content:null==t.content?void 0:JSON.stringify(t.content)};return e.reply_msg_id&&"0"!==e.reply_msg_id&&(s.reply_msg_id=e.reply_msg_id),e.thread_msg_id&&"0"!==e.thread_msg_id&&(s.thread_msg_id=e.thread_msg_id),this.httpClient.post("/message/send_custom",s)}return E(u.SDK_ERROR,"not support")}async sendMessageReadReceipt(e){const t=this.feedCache.get(e.feed_id);return null===t?E(u.SDK_ERROR,"not found feed"):await this.httpClient.post("/message/read",{chat_id:t.chat_id,message_ids:e.message_ids})}async joinRoom(e){return await this.httpClient.post("/liveshow/join",{room_id:e})}async setMute(e){const t=await this.httpClient.post("/feed/update",{id:e.feedId,is_mute:e.isMute?s.yes:s.no});return t.ok?t.data:null}async setPin(e){const t=await this.httpClient.post("/feed/update",{id:e.feedId,pin:e.pin?s.yes:s.no});return t.ok?t.data:null}async setName(e){const t=await this.httpClient.post("/feed/update",{id:e.feedId,name:e.name});return t.ok?t.data:null}async setSave(e){const t=await this.httpClient.post("/feed/update",{id:e.feedId,is_save:e.isSave?s.yes:s.no});return t.ok?t.data:null}async setArchive(e){const t=await this.httpClient.post("/feed/update",{id:e.feedId,is_archive:e.isArchive?s.yes:s.no});return t.ok?t.data:null}async setMark(e){const t=await this.httpClient.post("/feed/update",{id:e.feedId,is_mark:e.isMark?s.yes:s.no});return t.ok?t.data:null}async leaveRoom(e){return await this.httpClient.post("/liveshow/leave",{room_id:e})}async getJoinedRooms(){return await this.httpClient.get("/liveshow/joined_rooms")}async getRoomRecentMessageList(e){const t=await this.httpClient.get("/liveshow/get_recent_message",{room_id:e});return t.ok?b(t.data):t}async sendMessageToRoom(e){return await this.httpClient.post("/liveshow/send_message",{room_id:e.room_id,content:e.content})}}const $=new Map;function V(e,t){let s=$.get(e);return void 0===s&&(s=new q(t),$.set(e,s)),s}const W={parseSystemMessageContent:e=>{const t=y(e);return null!==t?{text:t.text,text_i18n:t.text_i18n}:{}},parseTextMessageContent:e=>{const t=y(e);return null!==t?{text:t.text,client_msg_id:t.client_msg_id}:{}},parseCustomMessageContent:S};export{q as ChatSDK,V as create,_ as enums,f as events,m as interfaces,W as utils};
package/dist/web-sdk.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t,s,i,n,o,r,a,d=require("axios"),l=require("crypto-js");!function(e){e[e.yes=1]="yes",e[e.no=0]="no"}(e||(e={})),function(e){e[e.CREATE_FEED=0]="CREATE_FEED",e[e.UPDATE_FEED=1]="UPDATE_FEED",e[e.ADD_MESSAGE=2]="ADD_MESSAGE",e[e.UPDATE_MESSAGE=3]="UPDATE_MESSAGE",e[e.UPDATE_USER_DATA=4]="UPDATE_USER_DATA",e[e.USER_LOGIN=5]="USER_LOGIN",e[e.READ_MESSAGE=6]="READ_MESSAGE",e[e.PONG_MESSAGE=8]="PONG_MESSAGE",e[e.DELETE_MESSAGE=9]="DELETE_MESSAGE",e[e.UPDATE_GROUP=12]="UPDATE_GROUP",e[e.DELETE_GROUP=13]="DELETE_GROUP",e[e.UPDATE_LOGIN_USER=17]="UPDATE_LOGIN_USER",e[e.UPDATE_MESSAGE_REACTION=19]="UPDATE_MESSAGE_REACTION",e[e.ADD_GROUP_MEMBER=21]="ADD_GROUP_MEMBER",e[e.DEL_GROUP_MEMBER=22]="DEL_GROUP_MEMBER",e[e.ADD_CONTACTS=23]="ADD_CONTACTS",e[e.UPDATE_CONTACTS=24]="UPDATE_CONTACTS",e[e.DEL_CONTACTS=25]="DEL_CONTACTS",e[e.BLOCK_USER=26]="BLOCK_USER",e[e.DEVICE_CODE=27]="DEVICE_CODE",e[e.MSG_OPEN_CLOCK=28]="MSG_OPEN_CLOCK",e[e.DELETE_SECRET_CHAT=29]="DELETE_SECRET_CHAT",e[e.DELETE_FEED=30]="DELETE_FEED",e[e.FAVORITE_UPDATE=31]="FAVORITE_UPDATE",e[e.STICKERS_UPDATE=32]="STICKERS_UPDATE",e[e.CUSTOM_STICKERS_UPDATE=33]="CUSTOM_STICKERS_UPDATE",e[e.MANAGE_DEVICE_UPDATE=34]="MANAGE_DEVICE_UPDATE",e[e.MASS_MESSAGE_UPDATE=35]="MASS_MESSAGE_UPDATE",e[e.CHAT_WALLPAPER_DELETE=36]="CHAT_WALLPAPER_DELETE",e[e.CHAT_WALLPAPER_ADD=37]="CHAT_WALLPAPER_ADD",e[e.CONTACT_REQUEST=40]="CONTACT_REQUEST",e[e.USER_PREFERENCE_CHANGE=38]="USER_PREFERENCE_CHANGE",e[e.UPDATE_GROUP_PIN=41]="UPDATE_GROUP_PIN",e[e.RTC_CANCEL=46]="RTC_CANCEL",e[e.ADD_FEED_FOLDER=43]="ADD_FEED_FOLDER",e[e.UPDATE_FEED_FOLDER=44]="UPDATE_FEED_FOLDER",e[e.UPDATE_FOLDER_FEED_LIST=47]="UPDATE_FOLDER_FEED_LIST",e[e.DELETE_FEED_FOLDER=45]="DELETE_FEED_FOLDER",e[e.UPDATE_CHATTER=42]="UPDATE_CHATTER",e[e.PAPER_KEY=48]="PAPER_KEY",e[e.PAPER_KEY_LOG=49]="PAPER_KEY_LOG",e[e.USER_LOGIN_SCAN=50]="USER_LOGIN_SCAN",e[e.RTC_RINGING=51]="RTC_RINGING",e[e.ON_UPDATE_PRIVATE_SETTING=52]="ON_UPDATE_PRIVATE_SETTING",e[e.ON_DELETE_PRIVATE_SETTING=53]="ON_DELETE_PRIVATE_SETTING",e[e.ON_UPDATE_LOGIN_PRIVATE_SETTING=54]="ON_UPDATE_LOGIN_PRIVATE_SETTING",e[e.PUSH_LIVE_MESSAGE=56]="PUSH_LIVE_MESSAGE",e[e.PUSH_SYSTEM_NOTICE=58]="PUSH_SYSTEM_NOTICE",e[e.BIG_PACKAGE_PUSH=126]="BIG_PACKAGE_PUSH",e[e.KICK_OUT_DEVICE=127]="KICK_OUT_DEVICE",e[e.CLEAR_HISTORY=128]="CLEAR_HISTORY",e[e.CLEAR_DATA=255]="CLEAR_DATA"}(t||(t={})),function(e){e[e.singleChat=1]="singleChat",e[e.groupChat=2]="groupChat"}(s||(s={})),function(e){e[e.normal=0]="normal",e[e.thread=1]="thread"}(i||(i={})),function(e){e[e.text=0]="text",e[e.system=1]="system"}(n||(n={})),function(e){e[e.text=0]="text",e[e.image=1]="image",e[e.card=2]="card",e[e.audio=3]="audio",e[e.video=4]="video",e[e.file=5]="file",e[e.mergeForward=6]="mergeForward",e[e.sticker=7]="sticker",e[e.richText=8]="richText",e[e.custom=9]="custom"}(o||(o={})),function(e){e[e.Owner=1]="Owner",e[e.Admin=2]="Admin",e[e.Common=3]="Common",e[e.Bot=4]="Bot"}(r||(r={})),function(e){e[e.normal=0]="normal",e[e.recall=1]="recall",e[e.destroy=2]="destroy",e[e.edit=3]="edit",e[e.main_delete=4]="main_delete"}(a||(a={}));const c=["api-coco.typex.im","api-tx.typex-test.cn"];var h,u,g;!function(e){e.error="ERROR",e.warning="WARNING",e.info="INFO"}(h||(h={})),function(e){e[e.SDK_ERROR=-1e4]="SDK_ERROR",e[e.NETWORK_ERROR=-9999]="NETWORK_ERROR",e[e.MAKE_SIGN_FAIL=-9998]="MAKE_SIGN_FAIL",e[e.SUCCESS=0]="SUCCESS"}(u||(u={})),function(e){e[e.up=0]="up",e[e.down=1]="down"}(g||(g={}));var _=Object.freeze({__proto__:null,get Bool(){return e},get ChatType(){return s},get FeedType(){return i},get GroupRole(){return r},get HttpClientResponseCode(){return u},get LogLevel(){return h},get MessageKind(){return n},get MessageOperation(){return a},get MessageType(){return o},get PushMessageType(){return t},RESOURCE_AUTH_DOMAINS:c,get RequestDirection(){return g}});const p={SDK_READY:"sdkReady",SDK_NOT_READY:"sdkNotReady",FEED_LIST_UPDATED:"feedListUpdated",MESSAGE_RECEIVED:"messageReceived",MESSAGE_RECALLED:"messageRecalled",MESSAGE_EDITED:"messageEdited",MESSAGE_DESTROYED:"messageDestroyed",MESSAGE_REACTION_UPDATED:"messageReactionUpdated",MESSAGE_RECEIPT_RECEIVED:"messageReceiptReceived",MESSAGE_OPEN_CLOCK:"messageOpenClock",ROOM_MESSAGE_RECEIVED:"roomMessageReceived",SYSTEM_NOTICE_RECEIVED:"systemNoticeReceived"};var E=Object.freeze({__proto__:null,CHAT_SDK_EVENT:p}),f=Object.freeze({__proto__:null});function m(e,t){return{ok:!1,code:e,msg:t}}function b(e){return{ok:!0,data:e}}const S=e=>{try{return null==e||"string"!=typeof e||0===e.length?null:JSON.parse(e)}catch{return null}},y=e=>{const t=S(e);if(null!==t){let e;return null!=t.content&&(e=S(t.content)??void 0),{client_msg_id:t.client_msg_id,content:e}}return{}},C=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),w=e=>new RegExp(`https?:\\\\?/\\\\?/${C(e)}(?:\\\\.|[^"\\\\\\s])*`,"g"),T=(e,t,s)=>{if(!e||"string"!=typeof e)return e;const i=w(t);return e.replace(i,e=>{const t=(e=>{try{return JSON.parse(`"${e}"`)}catch{return e}})(e),i=s(t);return"string"!=typeof i||i===t?e:(n=i,JSON.stringify(n).slice(1,-1));var n})};class v{constructor(e){Object.defineProperty(this,"all",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.all=e||new Map}on(e,t){const s=this.all.get(e);return s?s.push(t):this.all.set(e,[t]),()=>{this.off(e,t)}}off(e,t){const s=this.all.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let s=this.all.get(e);s&&s.slice().map(e=>{e(t)}),s=this.all.get("*"),s&&s.slice().map(s=>{s(e,t)})}once(e,t){if("*"===e){const s=(e,i)=>{t(e,i),this.off("*",s)};this.on(e,s)}else{const s=i=>{t(i),this.off(e,s)};this.on(e,s)}}}function A(e){const t=(new TextEncoder).encode(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class R extends v{constructor(e){super(),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"wsRoute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pingTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pongTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reConnectTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=e.url,this.token=e.token,this.wsRoute=e.wsRoute??null,this.logger=e.logger,this.ws=null,this.destroyed=!1,this.pingTimeout=null,this.pongTimeout=null,this.reConnectTimeout=null,this.reConnect=this.reConnect.bind(this),window.addEventListener("online",this.reConnect),this.connect()}disconnect(){this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.close(),this.ws=null),null!==this.pingTimeout&&(clearTimeout(this.pingTimeout),this.pingTimeout=null),null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null),null!==this.reConnectTimeout&&(clearTimeout(this.reConnectTimeout),this.reConnectTimeout=null)}connect(){if(this.ws)return void this.logger.warn("ReConnectWebsocket try connect but already connected");const e=new WebSocket(function(e,t={}){const s=new URL(e);return s.searchParams.set("platform",t.platform??"web"),s.searchParams.set("ws_route",t.wsRoute??""),s.toString()}(this.url,{platform:"web",wsRoute:this.wsRoute}),["typex.im.auth.v1",`typex.im.auth.b64url.${A(this.token)}`]);this.ws=e,e.onopen=()=>{this.delaySendPing()},e.onerror=e=>{this.logger.info("ReConnectWebsocket error",e)},e.onmessage=e=>{try{const s=JSON.parse(e.data);if(s.type===t.PONG_MESSAGE?null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null,this.delaySendPing()):this.sendAck(s.id),s.type===t.BIG_PACKAGE_PUSH)for(const e of s.content.big_push)this.emit("message",e);else this.emit("message",s)}catch(e){this.logger.error("ReConnectWebsocket message parse failed",e)}},e.onclose=e=>{4001===e.code?this.kickOff():this.reConnect()}}reConnect(){this.disconnect(),this.destroyed||(this.reConnectTimeout=setTimeout(()=>{this.reConnectTimeout=null,this.connect()},5e3))}send(e){if(this.destroyed)return!1;if(!this.ws)return this.logger.warn("ReConnectWebsocket send before connect"),!1;try{return this.ws.readyState!==this.ws.OPEN?(this.logger.warn("ReConnectWebsocket send but not open",this.ws.readyState),!1):(this.ws.send(JSON.stringify(e)),!0)}catch(e){return this.logger.warn("ReConnectWebsocket send error",e),!1}}sendAck(e){this.send({type:1,ids:[e]})}destroy(){this.destroyed||(this.destroyed=!0,this.disconnect(),window.removeEventListener("online",this.reConnect))}delaySendPing(){null!==this.pingTimeout&&(clearTimeout(this.pingTimeout),this.pingTimeout=null),this.pingTimeout=setTimeout(()=>{this.pingTimeout=null;this.send({type:0})?this.waitPong():this.reConnect()},2e4)}waitPong(){this.pongTimeout=setTimeout(()=>{this.logger.info("ReConnectWebsocket pong timeout"),this.reConnect()},1e4)}kickOff(){this.destroy(),this.emit("kickoff")}}class P extends v{constructor(e){super(),Object.defineProperty(this,"host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.host=e.host,this.context=e.context,this.logger=e.logger,this.ws=null}connect(){null!==this.context.loginUser?(this.ws&&(this.ws.destroy(),this.ws=null),this.ws=new R({url:`${this.host}/ws`,token:this.context.loginUser.sessionId,wsRoute:this.context.deviceId,logger:this.logger}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("kickoff",()=>{this.emit("kickoff")})):this.logger.warn("BusinessWebsocket try connect but not login")}disconnect(){this.ws?(this.ws.destroy(),this.ws=null):this.logger.info("BusinessWebsocket already disconnected")}}class D{constructor(){Object.defineProperty(this,"syncCompleted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"map",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"threadMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"targetMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"list",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.syncCompleted=!1,this.map=new Map,this.chatMap=new Map,this.threadMap=new Map,this.targetMap=new Map,this.waitMap=new Map,this.list=[]}getAll(){const e=[];for(const t of this.list){const s=this.map.get(t);s&&e.push(s)}return e}get(e){return this.map.get(e)??null}getByChat(e,t){let s;return s=t&&"0"!==t?this.threadMap.get(t):this.chatMap.get(e),void 0!==s?this.get(s):null}getByTargetId(e){const t=this.targetMap.get(e);if(void 0===t)return[];const s=[];for(const e of t){const t=this.get(e);null!==t&&s.push(t)}return s}async waitFor(e){const t=this.get(e);if(t)return t;if(this.syncCompleted)return null;let s=this.waitMap.get(e);return s||(s=(()=>{let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}})(),this.waitMap.set(e,s)),await s.promise,this.get(e)}resolveWait(e){const t=this.waitMap.get(e);t&&(t.resolve(),this.waitMap.delete(e))}removeFromList(e){const t=this.list.indexOf(e);t>-1&&this.list.splice(t,1)}remove(e){const t=this.map.get(e);if(t){if(this.map.delete(e),t.feed_type===i.thread)this.threadMap.delete(t.thread_id);else if(this.chatMap.delete(t.chat_id),t.target_id&&"0"!==t.target_id){const e=this.targetMap.get(t.target_id);void 0!==e&&(e.delete(t.id),0===e.size&&this.targetMap.delete(t.target_id))}return this.removeFromList(e),!0}return!1}beforeSave(e){if(this.map.has(e.id))this.removeFromList(e.id);else if(e.feed_type===i.thread)this.threadMap.set(e.thread_id,e.id);else if(this.chatMap.set(e.chat_id,e.id),e.target_id&&"0"!==e.target_id){if(!this.targetMap.has(e.target_id)){const t=new Set;this.targetMap.set(e.target_id,t)}this.targetMap.get(e.target_id)?.add(e.id)}this.map.set(e.id,e)}afterSave(e){this.resolveWait(e.id)}push(e){this.beforeSave(e),this.list.push(e.id),this.afterSave(e)}unshift(e){this.beforeSave(e),this.list.unshift(e.id),this.afterSave(e)}update(e){this.map.has(e.id)&&this.map.set(e.id,e)}markSyncComplete(){this.syncCompleted=!0;for(const[e,t]of this.waitMap)t.resolve();this.waitMap.clear()}isSyncCompleted(){return this.syncCompleted}reset(){this.syncCompleted=!1,this.map.clear(),this.chatMap.clear(),this.threadMap.clear(),this.targetMap.clear(),this.waitMap.clear(),this.list=[]}}function O(e){return(new TextEncoder).encode(e).buffer}async function L(e,t){return window.crypto&&window.crypto.subtle?await async function(e,t){const s=O(t),i=O(e),n=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,i);return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e,t):function(e,t){return l.HmacSHA256(e,t).toString(l.enc.Hex)}(e,t)}const I=e=>{if(null==e)return"";if("object"!=typeof e||Array.isArray(e)){if(Array.isArray(e)){let t="";for(const s of e)t+=I(s);return t}return"string"==typeof e?e:String(e)}{const t=Object.keys(e).sort();let s="";for(const i of t)s+=I(e[i]);return s}};function M(){return m(u.MAKE_SIGN_FAIL,"make sign fail")}class U{constructor(e){Object.defineProperty(this,"api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.api=d.create({baseURL:e.host,headers:{"x-developer":e.developer},withCredentials:!0}),this.context=e.context,this.logger=e.logger}async request(e){try{const{needSign:t=!0,...s}=e;if(s.headers||(s.headers={}),s.headers.platform="web",t&&"POST"===e.method?.toUpperCase()&&s.data){if(null===this.context.loginUser)return this.logger.warn("HttpClient needs make sign but not login"),M();try{const e=await(async(e,t)=>{const s=await I(e);return await L(s,t)})(s.data,this.context.loginUser.secretKey);s.headers.sign=e}catch(e){return this.logger.error("HttpClient make sign error",e),M()}}this.context.loginUser&&(s.headers["X-Sid"]=this.context.loginUser.sessionId);const i=await this.api(s),n=i.data;return n.code===u.SUCCESS?{ok:!0,data:n.data}:(this.logger.info("HttpClient server error",i),{ok:!1,code:n.code,msg:n.msg,msg_i18n:n.msg_i18n})}catch{return{ok:!1,code:u.NETWORK_ERROR,msg:"network error"}}}get(e,t,s){return this.request({url:e,method:"GET",params:t,...s})}post(e,t,s){return this.request({url:e,method:"POST",data:t,...s})}}function x(e){return`${e}`.padStart(2,"0")}class k{constructor(){Object.defineProperty(this,"level",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.level=h.error,this.logHandler=this.createLogHandler()}getPriority(e){switch(e){case h.error:return 3;case h.warning:return 2;case h.info:return 1;default:return 0}}createLogHandler(){return(e,...t)=>{const s=new Date,i=`TypeX >> [${`${s.getFullYear()}-${x(s.getMonth()+1)}-${x(s.getDate())} ${x(s.getHours())}:${x(s.getMinutes())}:${x(s.getSeconds())}.${s.getMilliseconds()}`}]`;switch(e){case h.error:console.error(i,"[ERR]",...t);break;case h.warning:console.warn(i,"[WARN]",...t);break;case h.info:console.info(i,"[INFO]",...t);break;default:console.log(i,...t)}}}log(e,...t){this.getPriority(e)>=this.getPriority(this.level)&&this.logHandler(e,...t)}setLogLevel(e){this.level=e,this.logHandler=this.createLogHandler()}info(...e){this.log(h.info,...e)}warn(...e){this.log(h.warning,...e)}error(...e){this.log(h.error,...e)}}class G{constructor(e){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"emitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleKickoff",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.context=e.context,this.logger=e.logger,this.emitter=e.emitter,this.feedCache=e.feedCache,this.handleKickoff=e.onKickoff}emitFeedListUpdated(){this.emitter.emit(p.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}processCreateFeed(e){this.feedCache.unshift(e.content),this.emitFeedListUpdated()}processUpdateFeed(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===s)return;const i={...s,...t};this.feedCache.update(i),this.emitFeedListUpdated()}processDeleteFeed(e){this.feedCache.remove(e.content.id)&&this.emitFeedListUpdated()}processAddMessage(t){if(null===this.context.loginUser)return;const s=this.context.loginUser.userId,i=t.content;if(i.hide_ids.includes(s))return;const o=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null!==o){if(i.no_last_msg!==e.yes){let t=!1,r=!1;const a={};if(i.message_kind_id!==n.system&&i.sender_id!==s&&i.no_read!==e.yes){t=!0;const e=new Set(o.unread_message_ids);e.add(i.id),a.unread_message_ids=[...e],a.badge=e.size}if(o.last_message_position<i.position&&(t=!0,r=!0,a.last_message_id=i.id,a.last_message_position=i.position,a.last_message_sender_id=i.sender_id,a.last_message_send_at=i.send_at,a.last_message_kind_id=i.message_kind_id,a.last_message_type_id=i.message_type_id,a.last_message=i.content,a.last_message_operation=i.operation,a.last_message_operation_user_id=i.operation_user_id),t){const e={...o,...a};r?this.feedCache.unshift(e):this.feedCache.update(e),this.emitFeedListUpdated()}}this.emitter.emit(p.MESSAGE_RECEIVED,{feed_id:o.id,message:i})}}processUpdateMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==s&&null!=t.operation){let e=!1;const i={};if(t.operation===a.recall||t.operation===a.destroy){if(null!=s.unread_message_ids&&s.unread_message_ids.includes(t.id)){e=!0;const n=new Set(s.unread_message_ids);n.delete(t.id),i.unread_message_ids=[...n],i.badge=i.unread_message_ids.length}s.last_message_id===t.id&&(e=!0,i.last_message=t.content??"{}",i.last_message_operation=t.operation,i.last_message_operation_user_id=t.operation_user_id??"0")}else t.operation===a.edit&&s.last_message_id===t.id&&(e=!0,i.last_message_kind_id=t.message_kind_id,i.last_message_type_id=t.message_type_id,i.last_message=t.content,i.last_message_operation=t.operation,i.last_message_operation_user_id=t.operation_user_id);e&&(this.feedCache.update({...s,...i}),this.emitFeedListUpdated()),t.operation===a.recall?this.emitter.emit(p.MESSAGE_RECALLED,{message_ids:[t.id]}):t.operation===a.edit?null!=t.content&&null!=t.edited_at&&null!=t.message_kind_id&&null!=t.message_type_id&&null!=t.operation_user_id&&this.emitter.emit(p.MESSAGE_EDITED,{chat_id:t.chat_id,content:t.content,edited_at:t.edited_at,id:t.id,message_kind_id:t.message_kind_id,message_type_id:t.message_type_id,operation:t.operation,operation_user_id:t.operation_user_id,thread_id:t.thread_id}):t.operation===a.destroy&&this.emitter.emit(p.MESSAGE_DESTROYED,{feed_id:s.id,message_ids:[t.id]})}}processDeleteMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===s)return;let i=!1;const n={};s.last_message_id===t.id&&(i=!0,n.last_message=t.content??"{}",n.last_message_operation=t.operation,n.last_message_operation_user_id=t.operation_user_id??"0"),i&&(this.feedCache.update({...s,...n}),this.emitFeedListUpdated()),this.emitter.emit(p.MESSAGE_DESTROYED,{feed_id:s.id,message_ids:[t.id]})}processOpenClockMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==s&&Array.isArray(t.msgs_open_clock)){const e=t.msgs_open_clock.map(e=>e.message_id);this.emitter.emit(p.MESSAGE_OPEN_CLOCK,{feed_id:s.id,message_ids:e})}}processPushLiveMessage(e){this.emitter.emit(p.ROOM_MESSAGE_RECEIVED,{room_id:e.content.room_id,content:e.content.message})}processPushSystemNotice(e){this.emitter.emit(p.SYSTEM_NOTICE_RECEIVED,{content:e.content})}processReadMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,s=e.content,i=this.feedCache.getByChat(s.chat_id,s.thread_id);if(null===i)return;let n=!1;const o={};if(s.reader_ids.includes(t)&&s.message_ids.length>0){n=!0;const e=new Set(i.unread_message_ids);s.message_ids.forEach(t=>{e.delete(t)}),o.unread_message_ids=[...e],o.badge=e.size}n&&(this.feedCache.update({...i,...o}),this.emitFeedListUpdated()),this.emitter.emit(p.MESSAGE_RECEIPT_RECEIVED,{feed_id:i.id,message_ids:s.message_ids,reader_user_ids:s.reader_ids})}processKickOutDevice(){this.handleKickoff()}processGroupMember(e){const s=e.content,i=this.feedCache.getByChat(s.chat_id,"0");if(null===i)return;const n=new Set(i.chat_member),o=e.type===t.ADD_GROUP_MEMBER,r=e.type===t.DEL_GROUP_MEMBER;s.chat_member.forEach(e=>{o?n.add(e.chat_id):r&&n.delete(e.chat_id)}),this.feedCache.update({...i,chat_member:[...n]}),this.emitFeedListUpdated()}processUpdateGroup(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,"0");if(null===s)return;let i=!1;const n={};null!=t.avatar&&(i=!0,n.avatar=t.avatar),null!=t.name&&(i=!0,n.name=t.name),i&&(this.feedCache.update({...s,...n}),this.emitFeedListUpdated())}processUpdateUserData(e){const t=e.content,s=this.feedCache.getByTargetId(t.id);if(s.length>0){const e={};if(null!=t.avatar&&(e.avatar=t.avatar),null!=t.first_name||null!=t.last_name){let s=t.first_name??"";null!=t.last_name&&(s=s.length>0?`${s} ${t.last_name}`:t.last_name),e.name=s}for(const t of s)this.feedCache.update({...t,...e});this.emitFeedListUpdated()}}processUpdateMessageReaction(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);null!==s&&this.emitter.emit(p.MESSAGE_REACTION_UPDATED,{feed_id:s.id,message_id:t.message_id,reactions:t.reactions})}process(e){switch(this.logger.info("PushMessageProcessor process",e),e.type){case t.CREATE_FEED:this.processCreateFeed(e);break;case t.UPDATE_FEED:this.processUpdateFeed(e);break;case t.DELETE_FEED:this.processDeleteFeed(e);break;case t.ADD_MESSAGE:this.processAddMessage(e);break;case t.UPDATE_MESSAGE:this.processUpdateMessage(e);break;case t.DELETE_MESSAGE:this.processDeleteMessage(e);break;case t.PUSH_LIVE_MESSAGE:this.processPushLiveMessage(e);break;case t.MSG_OPEN_CLOCK:this.processOpenClockMessage(e);break;case t.PUSH_SYSTEM_NOTICE:this.processPushSystemNotice(e);break;case t.READ_MESSAGE:this.processReadMessage(e);break;case t.KICK_OUT_DEVICE:this.processKickOutDevice();break;case t.ADD_GROUP_MEMBER:case t.DEL_GROUP_MEMBER:this.processGroupMember(e);break;case t.UPDATE_GROUP:this.processUpdateGroup(e);break;case t.UPDATE_USER_DATA:this.processUpdateUserData(e);break;case t.UPDATE_MESSAGE_REACTION:this.processUpdateMessageReaction(e)}}}class N{static set(e){localStorage.setItem(this.key,JSON.stringify(e))}static get(){try{const e=localStorage.getItem(this.key);if(!e)return null;return JSON.parse(e)}catch{return null}}static clear(){localStorage.removeItem(this.key)}}Object.defineProperty(N,"key",{enumerable:!0,configurable:!0,writable:!0,value:"__typex_sdk_data__"});const F="__typex_sdk_tab_session_message__";function j(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function K(e){if(!e||"object"!=typeof e)return!1;const t=e,s=t.loginUser;return(null===t.deviceId||"string"==typeof t.deviceId)&&!!s&&"string"==typeof s.userId&&"string"==typeof s.secretKey&&"string"==typeof s.sessionId}class B{constructor(e={}){Object.defineProperty(this,"tabId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"closed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledSessionRequestIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledLogoutIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledLoginIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingSessionRequests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getCurrentSession",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onLogoutBroadcast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onLoginBroadcast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tabId=j(),this.channel=null,this.closed=!1,this.handledSessionRequestIds=new Set,this.handledLogoutIds=new Set,this.handledLoginIds=new Set,this.pendingSessionRequests=new Map,this.getCurrentSession=e.getCurrentSession??null,this.onLogoutBroadcast=e.onLogoutBroadcast??null,this.onLoginBroadcast=e.onLoginBroadcast??null,this.logger=e.logger??null,this.handleBroadcastMessage=this.handleBroadcastMessage.bind(this),this.handleStorageMessage=this.handleStorageMessage.bind(this),"undefined"!=typeof BroadcastChannel&&(this.channel=new BroadcastChannel("typex-sdk-tab-session"),this.channel.onmessage=this.handleBroadcastMessage),"undefined"!=typeof window&&window.addEventListener("storage",this.handleStorageMessage)}publishLogout(){this.publish({type:"logout",senderTabId:this.tabId,logoutId:j(),createdAt:Date.now()})}publishLogin(e){this.publish({type:"login",senderTabId:this.tabId,loginId:j(),createdAt:Date.now(),session:e})}requestCurrentSession(e=500){if(this.closed)return Promise.resolve(null);const t=j();return new Promise(s=>{const i=setTimeout(()=>{this.pendingSessionRequests.delete(t),s(null)},e);this.pendingSessionRequests.set(t,{resolve:s,timeout:i}),this.publish({type:"session-request",senderTabId:this.tabId,requestId:t,createdAt:Date.now()})})}destroy(){this.closed||(this.closed=!0,this.pendingSessionRequests.forEach(e=>{clearTimeout(e.timeout),e.resolve(null)}),this.pendingSessionRequests.clear(),this.channel&&(this.channel.close(),this.channel=null),"undefined"!=typeof window&&window.removeEventListener("storage",this.handleStorageMessage))}publish(e){if(!this.closed&&(this.channel&&this.channel.postMessage(e),"session-response"!==e.type&&"login"!==e.type&&"undefined"!=typeof localStorage))try{localStorage.setItem(F,JSON.stringify({...e,storageNonce:j()}))}catch(e){this.logger?.warn("TabSessionCoordinator storage publish failed",e)}}handleBroadcastMessage(e){this.handleMessage(e.data)}handleStorageMessage(e){if(e.key===F&&e.newValue)try{this.handleMessage(JSON.parse(e.newValue))}catch(e){this.logger?.warn("TabSessionCoordinator storage parse failed",e)}}handleMessage(e){if(!this.closed&&function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.senderTabId&&("session-request"===t.type?"string"==typeof t.requestId&&"number"==typeof t.createdAt:"session-response"===t.type?"string"==typeof t.requesterTabId&&"string"==typeof t.requestId&&"number"==typeof t.createdAt&&K(t.session):"logout"===t.type?"string"==typeof t.logoutId&&"number"==typeof t.createdAt:"login"===t.type&&"string"==typeof t.loginId&&"number"==typeof t.createdAt&&K(t.session))}(e)&&e.senderTabId!==this.tabId){if("logout"===e.type){if(this.handledLogoutIds.has(e.logoutId))return;return this.handledLogoutIds.add(e.logoutId),void this.onLogoutBroadcast?.()}if("login"===e.type){if(this.handledLoginIds.has(e.loginId))return;return this.handledLoginIds.add(e.loginId),void this.onLoginBroadcast?.(e.session)}if("session-request"===e.type){const t=`${e.senderTabId}:${e.requestId}`;if(this.handledSessionRequestIds.has(t))return;this.handledSessionRequestIds.add(t);const s=this.getCurrentSession?.();if(!s)return;return void this.publish({type:"session-response",senderTabId:this.tabId,requesterTabId:e.senderTabId,requestId:e.requestId,createdAt:Date.now(),session:s})}if("session-response"===e.type){if(e.requesterTabId!==this.tabId)return;const t=this.pendingSessionRequests.get(e.requestId);if(!t)return;clearTimeout(t.timeout),this.pendingSessionRequests.delete(e.requestId),t.resolve(e.session)}}}}class H{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.version=0}increment(){this.version++}get(){return this.version}check(e){return e===this.version}}class q extends v{constructor(e){super(),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tabSessionCoordinator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"restoreLoginPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"httpClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pushMessageProcessor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handlePageHide",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.ws.disconnect()}}),Object.defineProperty(this,"handlePageShow",{enumerable:!0,configurable:!0,writable:!0,value:e=>{e.persisted&&this.context.isLogin&&this.ws.connect()}}),this.context={isLogin:!1,loginUser:null,isReady:!1,deviceId:null},this.version=new H,this.logger=new k,this.restoreLoginPromise=null,this.tabSessionCoordinator=new B({logger:this.logger,getCurrentSession:()=>this.getTransferableLoginSession(),onLogoutBroadcast:()=>{this.afterLogout()},onLoginBroadcast:e=>{this.applySharedLoginSession(e)}}),this.httpClient=new U({host:e.httpHost,context:this.context,logger:this.logger,developer:e.developer}),this.feedCache=new D,this.ws=new P({host:e.websocketHost,context:this.context,logger:this.logger}),this.pushMessageProcessor=new G({context:this.context,logger:this.logger,emitter:this,feedCache:this.feedCache,onKickoff:()=>{this.afterLogout()}}),this.init()}init(){this.loadContext(),this.ws.on("message",e=>{this.pushMessageProcessor.process(e)}),this.ws.on("kickoff",()=>{this.afterLogout()}),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.handlePageHide),window.addEventListener("pageshow",this.handlePageShow)),setTimeout(()=>{this.restoreLoginFromActiveTab()},0)}getTransferableLoginSession(){return this.context.isLogin&&null!==this.context.loginUser?{deviceId:this.context.deviceId,loginUser:{...this.context.loginUser}}:null}async restoreLoginFromActiveTab(){if(this.restoreLoginPromise)return this.restoreLoginPromise;this.restoreLoginPromise=this.doRestoreLoginFromActiveTab();try{return await this.restoreLoginPromise}finally{this.restoreLoginPromise=null}}async doRestoreLoginFromActiveTab(){if(this.context.isLogin)return!0;const e=await this.tabSessionCoordinator.requestCurrentSession(500);return!e||this.context.isLogin?this.context.isLogin:this.applySharedLoginSession(e)}async applySharedLoginSession(e){return this.context.isLogin||(this.context.isLogin=!0,this.context.loginUser=e.loginUser,e.deviceId&&(this.context.deviceId=e.deviceId),await this.requestDeviceId(),this.applyLoginStatus()),!0}async requestDeviceId(){if(this.context.deviceId)return!0;const e=await this.httpClient.post("/device_api/device_id",{platform:"web",hash_str:""},{needSign:!1});return!!e.ok&&(this.context.deviceId=e.data,this.saveContext(),!0)}saveContext(){const{context:e}=this;N.set({deviceId:e.deviceId})}loadContext(){const e=N.get();e&&e.deviceId&&(this.context.deviceId=e.deviceId)}applyLoginStatus(){this.version.increment(),this.saveContext(),this.context.isLogin?(this.ws.connect(),this.loadFeedList(),this.context.isReady=!0,this.emit(p.SDK_READY)):(this.ws.disconnect(),this.feedCache.reset(),this.context.isReady=!1,this.emit(p.SDK_NOT_READY))}async loadFeedList(){const e=this.version.get(),t={refresh_at:null,feed_id:null};for(;;){const s=await this.httpClient.get("/feed",{limit:500,last_refresh_at:t.refresh_at??void 0,last_feed_id:t.feed_id??void 0});if(!this.version.check(e))break;if(!s.ok||null===s.data)break;if(t.refresh_at=s.data.refresh_at,t.feed_id=s.data.last_feed_id,(s.data.feed_list??[]).forEach(e=>{this.feedCache.push(e)}),!s.data.has_more)break}this.version.check(e)&&(this.feedCache.markSyncComplete(),this.emit(p.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:!0}))}isReady(){return this.context.isReady}setLogLevel(e){this.logger.setLogLevel(e)}async login(e){if(this.context.isLogin)return b(null);if(await this.restoreLoginFromActiveTab()||this.context.isLogin)return b(null);if(await this.requestDeviceId(),!this.context.deviceId)return this.logger.error("Get deviceId failed"),m(u.SDK_ERROR,"Get deviceId failed");const t=await this.httpClient.post("/user/session/login",{userCode:e.user_code,device_id:this.context.deviceId},{needSign:!1});if(!t.ok)return t;this.context.isLogin=!0,this.context.loginUser={userId:t.data.id,secretKey:t.data.key,sessionId:e.user_code},this.applyLoginStatus();const s=this.getTransferableLoginSession();return s&&this.tabSessionCoordinator.publishLogin(s),b(null)}async logout(){if(!this.context.isLogin)return b(null);const e=await this.httpClient.get("/user/logout");return e.ok?(this.tabSessionCoordinator.publishLogout(),this.afterLogout(),b(null)):e}afterLogout(){(this.context.isLogin||this.context.isReady)&&(this.context.isLogin=!1,this.context.loginUser=null,this.applyLoginStatus())}getLoginUser(){return null===this.context.loginUser?null:this.context.loginUser.userId}async createSingleChatFeed(e){return await this.httpClient.post("/chat/single",{receiver_id:e})}async deleteFeed(e){return await this.httpClient.post("/feed/delete",{feed_id_list:[e],delete_peer:!0})}async getFeedList(){return b({list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}async getFeedDetail(e){return b(await this.feedCache.waitFor(e))}async getFeedMemberList(e){const t=await this.feedCache.get(e);return null!==t&&t.chat_member.length>0?await this.httpClient.post("/chat/chatter_info",{chatters:{[t.chat_id]:t.chat_member}}):b([])}async getUserByUids(e){const t=await this.httpClient.post("/user/users_info",e);return t.ok?b(t.data.map(e=>({id:e.id}))):t}getDomain(e){const[t,s]=c,i=w(t),n=w(s);for(const o of e){if(i.test(o.content))return t;if(n.test(o.content))return s}}appendXsid(e){if(!this.context.loginUser?.sessionId)return e;const t=this.context.loginUser.sessionId,s=this.getDomain(e);return s?e.map(e=>{const i=T(e.content,s,e=>((e,t,s)=>{const i=encodeURIComponent(t),n=encodeURIComponent(s),o=e.indexOf("#"),r=o>=0?e.slice(0,o):e,a=o>=0?e.slice(o):"",d=new RegExp(`([?&])${C(i)}=[^&#]*`);if(d.test(r))return r.replace(d,`$1${i}=${n}`)+a;const l=r.includes("?")?"&":"?";return`${r}${l}${i}=${n}${a}`})(e,"xsid",t));return{...e,content:i}}):e}async markFeedMessageAsRead(t){const s=this.feedCache.get(t);if(!s)return b(!1);if(!(await this.httpClient.post("/feed/update",{id:s.id,mark_unread:e.yes})).ok)return b(!1);return(await this.httpClient.post("/message/read",{chat_id:s.chat_id,thread_id:s.thread_id})).ok?b(!0):b(!1)}async getMessagesByIds(e,t){const s=this.feedCache.get(e);if(!s||!Array.isArray(t)||0===t.length)return b([]);const i=await this.httpClient.post("/message/get_by_msgid",{chat_msg_id_map:{[s.chat_id]:t}});if(i.ok){return b(this.appendXsid(i.data[s.chat_id]))}return b([])}async getFeedMessageList(e){const t=await this.getFeedDetail(e.feed_id);if(t.ok&&t.data){const s=t.data,{chat_id:i,first_position:n,last_message_position:o}=s,{positions:r,nextPosition:a,hasMore:d}=(e=>{const t=[];if(e.direction===g.up){let s=e.startPosition??e.maxPosition;for(;t.length<e.limit&&s>=e.minPosition;)t.push(s),s--;const i=s>=e.minPosition;let n;return i&&(n=s),{positions:t,nextPosition:n,hasMore:i}}{let s=e.startPosition??e.minPosition;for(;t.length<e.limit&&s<=e.maxPosition;)t.push(s),s++;const i=s<=e.maxPosition;let n;return i&&(n=s),{positions:t,nextPosition:n,hasMore:i}}})({maxPosition:o,minPosition:n,startPosition:e.message_position,limit:e.limit,direction:e.direction??g.up});if(r.length>0){const e=await this.httpClient.post("/message/get_by_position",{chat_position:{[i]:r}},{needSign:!1});if(e.ok&&e.data[i]){return b({has_more:d,list:this.appendXsid(e.data[i].reverse()),next_message_position:a})}}}return b({has_more:!1,list:[]})}createCustomMessage(e){if(null===this.context.loginUser)return m(u.SDK_ERROR,"not login");const t=this.feedCache.get(e.feed_id);if(null===t)return m(u.SDK_ERROR,"not found feed");const s=(new Date).toISOString();var i;return b({id:"",chat_id:t.chat_id,thread_id:t.thread_id,position:t.last_message_position,sender_id:this.context.loginUser.userId,message_kind_id:n.text,message_type_id:o.custom,send_at:s,edited_at:s,reader_ids:[],unreader_ids:[],hide_ids:[],operation:a.normal,operation_user_id:"0",content:(i={client_msg_id:e.client_msg_id,content:e.content},JSON.stringify({client_msg_id:i.client_msg_id,content:JSON.stringify(i.content)})),reactions:[]})}async sendMessageToFeed(e){if(e.message_type_id===o.custom){const t=y(e.content);return this.httpClient.post("/message/send_custom",{chat_id:e.chat_id,thread_id:e.thread_id,client_id:t.client_msg_id,content:null==t.content?void 0:JSON.stringify(t.content)})}return m(u.SDK_ERROR,"not support")}async sendMessageReadReceipt(e){const t=this.feedCache.get(e.feed_id);return null===t?m(u.SDK_ERROR,"not found feed"):await this.httpClient.post("/message/read",{chat_id:t.chat_id,message_ids:e.message_ids})}async joinRoom(e){return await this.httpClient.post("/liveshow/join",{room_id:e})}async setMute(t){const s=await this.httpClient.post("/feed/update",{id:t.feedId,is_mute:t.isMute?e.yes:e.no});return s.ok?s.data:null}async leaveRoom(e){return await this.httpClient.post("/liveshow/leave",{room_id:e})}async getJoinedRooms(){return await this.httpClient.get("/liveshow/joined_rooms")}async getRoomRecentMessageList(e){const t=await this.httpClient.get("/liveshow/get_recent_message",{room_id:e});return t.ok?b(t.data):t}async sendMessageToRoom(e){return await this.httpClient.post("/liveshow/send_message",{room_id:e.room_id,content:e.content})}}const $=new Map;const V={parseSystemMessageContent:e=>{const t=S(e);return null!==t?{text:t.text,text_i18n:t.text_i18n}:{}},parseTextMessageContent:e=>{const t=S(e);return null!==t?{text:t.text,client_msg_id:t.client_msg_id}:{}},parseCustomMessageContent:y};exports.ChatSDK=q,exports.create=function(e,t){let s=$.get(e);return void 0===s&&(s=new q(t),$.set(e,s)),s},exports.enums=_,exports.events=E,exports.interfaces=f,exports.utils=V;
1
+ "use strict";var e,t,s,i,n,o,r,a,d=require("axios"),l=require("crypto-js");!function(e){e[e.yes=1]="yes",e[e.no=0]="no"}(e||(e={})),function(e){e[e.CREATE_FEED=0]="CREATE_FEED",e[e.UPDATE_FEED=1]="UPDATE_FEED",e[e.ADD_MESSAGE=2]="ADD_MESSAGE",e[e.UPDATE_MESSAGE=3]="UPDATE_MESSAGE",e[e.UPDATE_USER_DATA=4]="UPDATE_USER_DATA",e[e.USER_LOGIN=5]="USER_LOGIN",e[e.READ_MESSAGE=6]="READ_MESSAGE",e[e.PONG_MESSAGE=8]="PONG_MESSAGE",e[e.DELETE_MESSAGE=9]="DELETE_MESSAGE",e[e.UPDATE_GROUP=12]="UPDATE_GROUP",e[e.DELETE_GROUP=13]="DELETE_GROUP",e[e.UPDATE_LOGIN_USER=17]="UPDATE_LOGIN_USER",e[e.UPDATE_MESSAGE_REACTION=19]="UPDATE_MESSAGE_REACTION",e[e.ADD_GROUP_MEMBER=21]="ADD_GROUP_MEMBER",e[e.DEL_GROUP_MEMBER=22]="DEL_GROUP_MEMBER",e[e.ADD_CONTACTS=23]="ADD_CONTACTS",e[e.UPDATE_CONTACTS=24]="UPDATE_CONTACTS",e[e.DEL_CONTACTS=25]="DEL_CONTACTS",e[e.BLOCK_USER=26]="BLOCK_USER",e[e.DEVICE_CODE=27]="DEVICE_CODE",e[e.MSG_OPEN_CLOCK=28]="MSG_OPEN_CLOCK",e[e.DELETE_SECRET_CHAT=29]="DELETE_SECRET_CHAT",e[e.DELETE_FEED=30]="DELETE_FEED",e[e.FAVORITE_UPDATE=31]="FAVORITE_UPDATE",e[e.STICKERS_UPDATE=32]="STICKERS_UPDATE",e[e.CUSTOM_STICKERS_UPDATE=33]="CUSTOM_STICKERS_UPDATE",e[e.MANAGE_DEVICE_UPDATE=34]="MANAGE_DEVICE_UPDATE",e[e.MASS_MESSAGE_UPDATE=35]="MASS_MESSAGE_UPDATE",e[e.CHAT_WALLPAPER_DELETE=36]="CHAT_WALLPAPER_DELETE",e[e.CHAT_WALLPAPER_ADD=37]="CHAT_WALLPAPER_ADD",e[e.CONTACT_REQUEST=40]="CONTACT_REQUEST",e[e.USER_PREFERENCE_CHANGE=38]="USER_PREFERENCE_CHANGE",e[e.UPDATE_GROUP_PIN=41]="UPDATE_GROUP_PIN",e[e.RTC_CANCEL=46]="RTC_CANCEL",e[e.ADD_FEED_FOLDER=43]="ADD_FEED_FOLDER",e[e.UPDATE_FEED_FOLDER=44]="UPDATE_FEED_FOLDER",e[e.UPDATE_FOLDER_FEED_LIST=47]="UPDATE_FOLDER_FEED_LIST",e[e.DELETE_FEED_FOLDER=45]="DELETE_FEED_FOLDER",e[e.UPDATE_CHATTER=42]="UPDATE_CHATTER",e[e.PAPER_KEY=48]="PAPER_KEY",e[e.PAPER_KEY_LOG=49]="PAPER_KEY_LOG",e[e.USER_LOGIN_SCAN=50]="USER_LOGIN_SCAN",e[e.RTC_RINGING=51]="RTC_RINGING",e[e.ON_UPDATE_PRIVATE_SETTING=52]="ON_UPDATE_PRIVATE_SETTING",e[e.ON_DELETE_PRIVATE_SETTING=53]="ON_DELETE_PRIVATE_SETTING",e[e.ON_UPDATE_LOGIN_PRIVATE_SETTING=54]="ON_UPDATE_LOGIN_PRIVATE_SETTING",e[e.PUSH_LIVE_MESSAGE=56]="PUSH_LIVE_MESSAGE",e[e.PUSH_SYSTEM_NOTICE=58]="PUSH_SYSTEM_NOTICE",e[e.BIG_PACKAGE_PUSH=126]="BIG_PACKAGE_PUSH",e[e.KICK_OUT_DEVICE=127]="KICK_OUT_DEVICE",e[e.CLEAR_HISTORY=128]="CLEAR_HISTORY",e[e.CLEAR_DATA=255]="CLEAR_DATA"}(t||(t={})),function(e){e[e.singleChat=1]="singleChat",e[e.groupChat=2]="groupChat"}(s||(s={})),function(e){e[e.normal=0]="normal",e[e.thread=1]="thread"}(i||(i={})),function(e){e[e.text=0]="text",e[e.system=1]="system"}(n||(n={})),function(e){e[e.text=0]="text",e[e.image=1]="image",e[e.card=2]="card",e[e.audio=3]="audio",e[e.video=4]="video",e[e.file=5]="file",e[e.mergeForward=6]="mergeForward",e[e.sticker=7]="sticker",e[e.richText=8]="richText",e[e.custom=9]="custom"}(o||(o={})),function(e){e[e.Owner=1]="Owner",e[e.Admin=2]="Admin",e[e.Common=3]="Common",e[e.Bot=4]="Bot"}(r||(r={})),function(e){e[e.normal=0]="normal",e[e.recall=1]="recall",e[e.destroy=2]="destroy",e[e.edit=3]="edit",e[e.main_delete=4]="main_delete"}(a||(a={}));const c=["api-coco.typex.im","api-tx.typex-test.cn"];var h,u,g;!function(e){e.error="ERROR",e.warning="WARNING",e.info="INFO"}(h||(h={})),function(e){e[e.SDK_ERROR=-1e4]="SDK_ERROR",e[e.NETWORK_ERROR=-9999]="NETWORK_ERROR",e[e.MAKE_SIGN_FAIL=-9998]="MAKE_SIGN_FAIL",e[e.SUCCESS=0]="SUCCESS"}(u||(u={})),function(e){e[e.up=0]="up",e[e.down=1]="down"}(g||(g={}));var _=Object.freeze({__proto__:null,get Bool(){return e},get ChatType(){return s},get FeedType(){return i},get GroupRole(){return r},get HttpClientResponseCode(){return u},get LogLevel(){return h},get MessageKind(){return n},get MessageOperation(){return a},get MessageType(){return o},get PushMessageType(){return t},RESOURCE_AUTH_DOMAINS:c,get RequestDirection(){return g}});const p={SDK_READY:"sdkReady",SDK_NOT_READY:"sdkNotReady",FEED_LIST_UPDATED:"feedListUpdated",MESSAGE_RECEIVED:"messageReceived",MESSAGE_RECALLED:"messageRecalled",MESSAGE_EDITED:"messageEdited",MESSAGE_DESTROYED:"messageDestroyed",MESSAGE_REACTION_UPDATED:"messageReactionUpdated",MESSAGE_RECEIPT_RECEIVED:"messageReceiptReceived",MESSAGE_OPEN_CLOCK:"messageOpenClock",ROOM_MESSAGE_RECEIVED:"roomMessageReceived",SYSTEM_NOTICE_RECEIVED:"systemNoticeReceived"};var f=Object.freeze({__proto__:null,CHAT_SDK_EVENT:p}),m=Object.freeze({__proto__:null});function E(e,t){return{ok:!1,code:e,msg:t}}function b(e){return{ok:!0,data:e}}const y=e=>{try{return null==e||"string"!=typeof e||0===e.length?null:JSON.parse(e)}catch{return null}};const S=e=>{const t=y(e);if(null!==t){let e;return null!=t.content&&(e=y(t.content)??void 0),{client_msg_id:t.client_msg_id,content:e}}return{}},C=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),w=e=>new RegExp(`https?:\\\\?/\\\\?/${C(e)}(?:\\\\.|[^"\\\\\\s])*`,"g"),v=(e,t,s)=>{if(!e||"string"!=typeof e)return e;const i=w(t);return e.replace(i,e=>{const t=(e=>{try{return JSON.parse(`"${e}"`)}catch{return e}})(e),i=s(t);return"string"!=typeof i||i===t?e:(n=i,JSON.stringify(n).slice(1,-1));var n})};class T{constructor(e){Object.defineProperty(this,"all",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.all=e||new Map}on(e,t){const s=this.all.get(e);return s?s.push(t):this.all.set(e,[t]),()=>{this.off(e,t)}}off(e,t){const s=this.all.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let s=this.all.get(e);s&&s.slice().map(e=>{e(t)}),s=this.all.get("*"),s&&s.slice().map(s=>{s(e,t)})}once(e,t){if("*"===e){const s=(e,i)=>{t(e,i),this.off("*",s)};this.on(e,s)}else{const s=i=>{t(i),this.off(e,s)};this.on(e,s)}}}function R(e){const t=(new TextEncoder).encode(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class A extends T{constructor(e){super(),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"wsRoute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pingTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pongTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reConnectTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=e.url,this.token=e.token,this.wsRoute=e.wsRoute??null,this.logger=e.logger,this.ws=null,this.destroyed=!1,this.pingTimeout=null,this.pongTimeout=null,this.reConnectTimeout=null,this.reConnect=this.reConnect.bind(this),window.addEventListener("online",this.reConnect),this.connect()}disconnect(){this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.close(),this.ws=null),null!==this.pingTimeout&&(clearTimeout(this.pingTimeout),this.pingTimeout=null),null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null),null!==this.reConnectTimeout&&(clearTimeout(this.reConnectTimeout),this.reConnectTimeout=null)}connect(){if(this.ws)return void this.logger.warn("ReConnectWebsocket try connect but already connected");const e=new WebSocket(function(e,t={}){const s=new URL(e);return s.searchParams.set("platform",t.platform??"web"),s.searchParams.set("ws_route",t.wsRoute??""),s.toString()}(this.url,{platform:"web",wsRoute:this.wsRoute}),["typex.im.auth.v1",`typex.im.auth.b64url.${R(this.token)}`]);this.ws=e,e.onopen=()=>{this.delaySendPing()},e.onerror=e=>{this.logger.info("ReConnectWebsocket error",e)},e.onmessage=e=>{try{const s=JSON.parse(e.data);if(s.type===t.PONG_MESSAGE?null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null,this.delaySendPing()):this.sendAck(s.id),s.type===t.BIG_PACKAGE_PUSH)for(const e of s.content.big_push)this.emit("message",e);else this.emit("message",s)}catch(e){this.logger.error("ReConnectWebsocket message parse failed",e)}},e.onclose=e=>{4001===e.code?this.kickOff():this.reConnect()}}reConnect(){this.disconnect(),this.destroyed||(this.reConnectTimeout=setTimeout(()=>{this.reConnectTimeout=null,this.connect()},5e3))}send(e){if(this.destroyed)return!1;if(!this.ws)return this.logger.warn("ReConnectWebsocket send before connect"),!1;try{return this.ws.readyState!==this.ws.OPEN?(this.logger.warn("ReConnectWebsocket send but not open",this.ws.readyState),!1):(this.ws.send(JSON.stringify(e)),!0)}catch(e){return this.logger.warn("ReConnectWebsocket send error",e),!1}}sendAck(e){this.send({type:1,ids:[e]})}destroy(){this.destroyed||(this.destroyed=!0,this.disconnect(),window.removeEventListener("online",this.reConnect))}delaySendPing(){null!==this.pingTimeout&&(clearTimeout(this.pingTimeout),this.pingTimeout=null),this.pingTimeout=setTimeout(()=>{this.pingTimeout=null;this.send({type:0})?this.waitPong():this.reConnect()},2e4)}waitPong(){this.pongTimeout=setTimeout(()=>{this.logger.info("ReConnectWebsocket pong timeout"),this.reConnect()},1e4)}kickOff(){this.destroy(),this.emit("kickoff")}}class P extends T{constructor(e){super(),Object.defineProperty(this,"host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.host=e.host,this.context=e.context,this.logger=e.logger,this.ws=null}connect(){null!==this.context.loginUser?(this.ws&&(this.ws.destroy(),this.ws=null),this.ws=new A({url:`${this.host}/ws`,token:this.context.loginUser.sessionId,wsRoute:this.context.deviceId,logger:this.logger}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("kickoff",()=>{this.emit("kickoff")})):this.logger.warn("BusinessWebsocket try connect but not login")}disconnect(){this.ws?(this.ws.destroy(),this.ws=null):this.logger.info("BusinessWebsocket already disconnected")}}class D{constructor(){Object.defineProperty(this,"syncCompleted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"map",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"threadMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"targetMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"list",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.syncCompleted=!1,this.map=new Map,this.chatMap=new Map,this.threadMap=new Map,this.targetMap=new Map,this.waitMap=new Map,this.list=[]}getAll(){const e=[];for(const t of this.list){const s=this.map.get(t);s&&e.push(s)}return e}get(e){return this.map.get(e)??null}getByChat(e,t){let s;return s=t&&"0"!==t?this.threadMap.get(t):this.chatMap.get(e),void 0!==s?this.get(s):null}getByTargetId(e){const t=this.targetMap.get(e);if(void 0===t)return[];const s=[];for(const e of t){const t=this.get(e);null!==t&&s.push(t)}return s}async waitFor(e){const t=this.get(e);if(t)return t;if(this.syncCompleted)return null;let s=this.waitMap.get(e);return s||(s=(()=>{let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}})(),this.waitMap.set(e,s)),await s.promise,this.get(e)}resolveWait(e){const t=this.waitMap.get(e);t&&(t.resolve(),this.waitMap.delete(e))}removeFromList(e){const t=this.list.indexOf(e);t>-1&&this.list.splice(t,1)}remove(e){const t=this.map.get(e);if(t){if(this.map.delete(e),t.feed_type===i.thread)this.threadMap.delete(t.thread_id);else if(this.chatMap.delete(t.chat_id),t.target_id&&"0"!==t.target_id){const e=this.targetMap.get(t.target_id);void 0!==e&&(e.delete(t.id),0===e.size&&this.targetMap.delete(t.target_id))}return this.removeFromList(e),!0}return!1}beforeSave(e){if(this.map.has(e.id))this.removeFromList(e.id);else if(e.feed_type===i.thread)this.threadMap.set(e.thread_id,e.id);else if(this.chatMap.set(e.chat_id,e.id),e.target_id&&"0"!==e.target_id){if(!this.targetMap.has(e.target_id)){const t=new Set;this.targetMap.set(e.target_id,t)}this.targetMap.get(e.target_id)?.add(e.id)}this.map.set(e.id,e)}afterSave(e){this.resolveWait(e.id)}push(e){this.beforeSave(e),this.list.push(e.id),this.afterSave(e)}unshift(e){this.beforeSave(e),this.list.unshift(e.id),this.afterSave(e)}update(e){this.map.has(e.id)&&this.map.set(e.id,e)}markSyncComplete(){this.syncCompleted=!0;for(const[e,t]of this.waitMap)t.resolve();this.waitMap.clear()}isSyncCompleted(){return this.syncCompleted}reset(){this.syncCompleted=!1,this.map.clear(),this.chatMap.clear(),this.threadMap.clear(),this.targetMap.clear(),this.waitMap.clear(),this.list=[]}}function O(e){return(new TextEncoder).encode(e).buffer}async function I(e,t){return window.crypto&&window.crypto.subtle?await async function(e,t){const s=O(t),i=O(e),n=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,i);return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e,t):function(e,t){return l.HmacSHA256(e,t).toString(l.enc.Hex)}(e,t)}const L=e=>{if(null==e)return"";if("object"!=typeof e||Array.isArray(e)){if(Array.isArray(e)){let t="";for(const s of e)t+=L(s);return t}return"string"==typeof e?e:String(e)}{const t=Object.keys(e).sort();let s="";for(const i of t)s+=L(e[i]);return s}};function M(){return E(u.MAKE_SIGN_FAIL,"make sign fail")}class U{constructor(e){Object.defineProperty(this,"api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.api=d.create({baseURL:e.host,headers:{"x-developer":e.developer},withCredentials:!0}),this.context=e.context,this.logger=e.logger}async request(e){try{const{needSign:t=!0,...s}=e;if(s.headers||(s.headers={}),s.headers.platform="web",t&&"POST"===e.method?.toUpperCase()&&s.data){if(null===this.context.loginUser)return this.logger.warn("HttpClient needs make sign but not login"),M();try{const e=await(async(e,t)=>{const s=await L(e);return await I(s,t)})(s.data,this.context.loginUser.secretKey);s.headers.sign=e}catch(e){return this.logger.error("HttpClient make sign error",e),M()}}this.context.loginUser&&(s.headers["X-Sid"]=this.context.loginUser.sessionId);const i=await this.api(s),n=i.data;return n.code===u.SUCCESS?{ok:!0,data:n.data}:(this.logger.info("HttpClient server error",i),{ok:!1,code:n.code,msg:n.msg,msg_i18n:n.msg_i18n})}catch{return{ok:!1,code:u.NETWORK_ERROR,msg:"network error"}}}get(e,t,s){return this.request({url:e,method:"GET",params:t,...s})}post(e,t,s){return this.request({url:e,method:"POST",data:t,...s})}}function k(e){return`${e}`.padStart(2,"0")}class x{constructor(){Object.defineProperty(this,"level",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.level=h.error,this.logHandler=this.createLogHandler()}getPriority(e){switch(e){case h.error:return 3;case h.warning:return 2;case h.info:return 1;default:return 0}}createLogHandler(){return(e,...t)=>{const s=new Date,i=`TypeX >> [${`${s.getFullYear()}-${k(s.getMonth()+1)}-${k(s.getDate())} ${k(s.getHours())}:${k(s.getMinutes())}:${k(s.getSeconds())}.${s.getMilliseconds()}`}]`;switch(e){case h.error:console.error(i,"[ERR]",...t);break;case h.warning:console.warn(i,"[WARN]",...t);break;case h.info:console.info(i,"[INFO]",...t);break;default:console.log(i,...t)}}}log(e,...t){this.getPriority(e)>=this.getPriority(this.level)&&this.logHandler(e,...t)}setLogLevel(e){this.level=e,this.logHandler=this.createLogHandler()}info(...e){this.log(h.info,...e)}warn(...e){this.log(h.warning,...e)}error(...e){this.log(h.error,...e)}}class G{constructor(e){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"emitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleKickoff",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.context=e.context,this.logger=e.logger,this.emitter=e.emitter,this.feedCache=e.feedCache,this.handleKickoff=e.onKickoff}emitFeedListUpdated(){this.emitter.emit(p.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}processCreateFeed(e){this.feedCache.unshift(e.content),this.emitFeedListUpdated()}processUpdateFeed(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===s)return;const i={...s,...t};this.feedCache.update(i),this.emitFeedListUpdated()}processDeleteFeed(e){this.feedCache.remove(e.content.id)&&this.emitFeedListUpdated()}processAddMessage(t){if(null===this.context.loginUser)return;const s=this.context.loginUser.userId,i=t.content;if(i.hide_ids.includes(s))return;const o=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null!==o){if(i.no_last_msg!==e.yes){let t=!1,r=!1;const a={};if(i.message_kind_id!==n.system&&i.sender_id!==s&&i.no_read!==e.yes){t=!0;const e=new Set(o.unread_message_ids);e.add(i.id),a.unread_message_ids=[...e],a.badge=e.size}if(o.last_message_position<i.position&&(t=!0,r=!0,a.last_message_id=i.id,a.last_message_position=i.position,a.last_message_sender_id=i.sender_id,a.last_message_send_at=i.send_at,a.last_message_kind_id=i.message_kind_id,a.last_message_type_id=i.message_type_id,a.last_message=i.content,a.last_message_operation=i.operation,a.last_message_operation_user_id=i.operation_user_id),t){const e={...o,...a};r?this.feedCache.unshift(e):this.feedCache.update(e),this.emitFeedListUpdated()}}this.emitter.emit(p.MESSAGE_RECEIVED,{feed_id:o.id,message:i})}}processUpdateMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==s&&null!=t.operation){let e=!1;const i={};if(t.operation===a.recall||t.operation===a.destroy){if(null!=s.unread_message_ids&&s.unread_message_ids.includes(t.id)){e=!0;const n=new Set(s.unread_message_ids);n.delete(t.id),i.unread_message_ids=[...n],i.badge=i.unread_message_ids.length}s.last_message_id===t.id&&(e=!0,i.last_message=t.content??"{}",i.last_message_operation=t.operation,i.last_message_operation_user_id=t.operation_user_id??"0")}else t.operation===a.edit&&s.last_message_id===t.id&&(e=!0,i.last_message_kind_id=t.message_kind_id,i.last_message_type_id=t.message_type_id,i.last_message=t.content,i.last_message_operation=t.operation,i.last_message_operation_user_id=t.operation_user_id);e&&(this.feedCache.update({...s,...i}),this.emitFeedListUpdated()),t.operation===a.recall?this.emitter.emit(p.MESSAGE_RECALLED,{message_ids:[t.id]}):t.operation===a.edit?null!=t.content&&null!=t.edited_at&&null!=t.message_kind_id&&null!=t.message_type_id&&null!=t.operation_user_id&&this.emitter.emit(p.MESSAGE_EDITED,{chat_id:t.chat_id,content:t.content,edited_at:t.edited_at,id:t.id,message_kind_id:t.message_kind_id,message_type_id:t.message_type_id,operation:t.operation,operation_user_id:t.operation_user_id,thread_id:t.thread_id}):t.operation===a.destroy&&this.emitter.emit(p.MESSAGE_DESTROYED,{feed_id:s.id,message_ids:[t.id]})}}processDeleteMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===s)return;let i=!1;const n={};s.last_message_id===t.id&&(i=!0,n.last_message=t.content??"{}",n.last_message_operation=t.operation,n.last_message_operation_user_id=t.operation_user_id??"0"),i&&(this.feedCache.update({...s,...n}),this.emitFeedListUpdated()),this.emitter.emit(p.MESSAGE_DESTROYED,{feed_id:s.id,message_ids:[t.id]})}processOpenClockMessage(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==s&&Array.isArray(t.msgs_open_clock)){const e=t.msgs_open_clock.map(e=>e.message_id);this.emitter.emit(p.MESSAGE_OPEN_CLOCK,{feed_id:s.id,message_ids:e})}}processPushLiveMessage(e){this.emitter.emit(p.ROOM_MESSAGE_RECEIVED,{room_id:e.content.room_id,content:e.content.message})}processPushSystemNotice(e){this.emitter.emit(p.SYSTEM_NOTICE_RECEIVED,{content:e.content})}processReadMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,s=e.content,i=this.feedCache.getByChat(s.chat_id,s.thread_id);if(null===i)return;let n=!1;const o={};if(s.reader_ids.includes(t)&&s.message_ids.length>0){n=!0;const e=new Set(i.unread_message_ids);s.message_ids.forEach(t=>{e.delete(t)}),o.unread_message_ids=[...e],o.badge=e.size}n&&(this.feedCache.update({...i,...o}),this.emitFeedListUpdated()),this.emitter.emit(p.MESSAGE_RECEIPT_RECEIVED,{feed_id:i.id,message_ids:s.message_ids,reader_user_ids:s.reader_ids})}processKickOutDevice(){this.handleKickoff()}processGroupMember(e){const s=e.content,i=this.feedCache.getByChat(s.chat_id,"0");if(null===i)return;const n=new Set(i.chat_member),o=e.type===t.ADD_GROUP_MEMBER,r=e.type===t.DEL_GROUP_MEMBER;s.chat_member.forEach(e=>{o?n.add(e.chat_id):r&&n.delete(e.chat_id)}),this.feedCache.update({...i,chat_member:[...n]}),this.emitFeedListUpdated()}processUpdateGroup(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,"0");if(null===s)return;let i=!1;const n={};null!=t.avatar&&(i=!0,n.avatar=t.avatar),null!=t.name&&(i=!0,n.name=t.name),i&&(this.feedCache.update({...s,...n}),this.emitFeedListUpdated())}processUpdateUserData(e){const t=e.content,s=this.feedCache.getByTargetId(t.id);if(s.length>0){const e={};if(null!=t.avatar&&(e.avatar=t.avatar),null!=t.first_name||null!=t.last_name){let s=t.first_name??"";null!=t.last_name&&(s=s.length>0?`${s} ${t.last_name}`:t.last_name),e.name=s}for(const t of s)this.feedCache.update({...t,...e});this.emitFeedListUpdated()}}processUpdateMessageReaction(e){const t=e.content,s=this.feedCache.getByChat(t.chat_id,t.thread_id);null!==s&&this.emitter.emit(p.MESSAGE_REACTION_UPDATED,{feed_id:s.id,message_id:t.message_id,reactions:t.reactions})}process(e){switch(this.logger.info("PushMessageProcessor process",e),e.type){case t.CREATE_FEED:this.processCreateFeed(e);break;case t.UPDATE_FEED:this.processUpdateFeed(e);break;case t.DELETE_FEED:this.processDeleteFeed(e);break;case t.ADD_MESSAGE:this.processAddMessage(e);break;case t.UPDATE_MESSAGE:this.processUpdateMessage(e);break;case t.DELETE_MESSAGE:this.processDeleteMessage(e);break;case t.PUSH_LIVE_MESSAGE:this.processPushLiveMessage(e);break;case t.MSG_OPEN_CLOCK:this.processOpenClockMessage(e);break;case t.PUSH_SYSTEM_NOTICE:this.processPushSystemNotice(e);break;case t.READ_MESSAGE:this.processReadMessage(e);break;case t.KICK_OUT_DEVICE:this.processKickOutDevice();break;case t.ADD_GROUP_MEMBER:case t.DEL_GROUP_MEMBER:this.processGroupMember(e);break;case t.UPDATE_GROUP:this.processUpdateGroup(e);break;case t.UPDATE_USER_DATA:this.processUpdateUserData(e);break;case t.UPDATE_MESSAGE_REACTION:this.processUpdateMessageReaction(e)}}}class N{static set(e){localStorage.setItem(this.key,JSON.stringify(e))}static get(){try{const e=localStorage.getItem(this.key);if(!e)return null;return JSON.parse(e)}catch{return null}}static clear(){localStorage.removeItem(this.key)}}Object.defineProperty(N,"key",{enumerable:!0,configurable:!0,writable:!0,value:"__typex_sdk_data__"});const F="__typex_sdk_tab_session_message__";function j(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function K(e){if(!e||"object"!=typeof e)return!1;const t=e,s=t.loginUser;return(null===t.deviceId||"string"==typeof t.deviceId)&&!!s&&"string"==typeof s.userId&&"string"==typeof s.secretKey&&"string"==typeof s.sessionId}class B{constructor(e={}){Object.defineProperty(this,"tabId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"closed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledSessionRequestIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledLogoutIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handledLoginIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingSessionRequests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getCurrentSession",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onLogoutBroadcast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onLoginBroadcast",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tabId=j(),this.channel=null,this.closed=!1,this.handledSessionRequestIds=new Set,this.handledLogoutIds=new Set,this.handledLoginIds=new Set,this.pendingSessionRequests=new Map,this.getCurrentSession=e.getCurrentSession??null,this.onLogoutBroadcast=e.onLogoutBroadcast??null,this.onLoginBroadcast=e.onLoginBroadcast??null,this.logger=e.logger??null,this.handleBroadcastMessage=this.handleBroadcastMessage.bind(this),this.handleStorageMessage=this.handleStorageMessage.bind(this),"undefined"!=typeof BroadcastChannel&&(this.channel=new BroadcastChannel("typex-sdk-tab-session"),this.channel.onmessage=this.handleBroadcastMessage),"undefined"!=typeof window&&window.addEventListener("storage",this.handleStorageMessage)}publishLogout(){this.publish({type:"logout",senderTabId:this.tabId,logoutId:j(),createdAt:Date.now()})}publishLogin(e){this.publish({type:"login",senderTabId:this.tabId,loginId:j(),createdAt:Date.now(),session:e})}requestCurrentSession(e=500){if(this.closed)return Promise.resolve(null);const t=j();return new Promise(s=>{const i=setTimeout(()=>{this.pendingSessionRequests.delete(t),s(null)},e);this.pendingSessionRequests.set(t,{resolve:s,timeout:i}),this.publish({type:"session-request",senderTabId:this.tabId,requestId:t,createdAt:Date.now()})})}destroy(){this.closed||(this.closed=!0,this.pendingSessionRequests.forEach(e=>{clearTimeout(e.timeout),e.resolve(null)}),this.pendingSessionRequests.clear(),this.channel&&(this.channel.close(),this.channel=null),"undefined"!=typeof window&&window.removeEventListener("storage",this.handleStorageMessage))}publish(e){if(!this.closed&&(this.channel&&this.channel.postMessage(e),"session-response"!==e.type&&"login"!==e.type&&"undefined"!=typeof localStorage))try{localStorage.setItem(F,JSON.stringify({...e,storageNonce:j()}))}catch(e){this.logger?.warn("TabSessionCoordinator storage publish failed",e)}}handleBroadcastMessage(e){this.handleMessage(e.data)}handleStorageMessage(e){if(e.key===F&&e.newValue)try{this.handleMessage(JSON.parse(e.newValue))}catch(e){this.logger?.warn("TabSessionCoordinator storage parse failed",e)}}handleMessage(e){if(!this.closed&&function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.senderTabId&&("session-request"===t.type?"string"==typeof t.requestId&&"number"==typeof t.createdAt:"session-response"===t.type?"string"==typeof t.requesterTabId&&"string"==typeof t.requestId&&"number"==typeof t.createdAt&&K(t.session):"logout"===t.type?"string"==typeof t.logoutId&&"number"==typeof t.createdAt:"login"===t.type&&"string"==typeof t.loginId&&"number"==typeof t.createdAt&&K(t.session))}(e)&&e.senderTabId!==this.tabId){if("logout"===e.type){if(this.handledLogoutIds.has(e.logoutId))return;return this.handledLogoutIds.add(e.logoutId),void this.onLogoutBroadcast?.()}if("login"===e.type){if(this.handledLoginIds.has(e.loginId))return;return this.handledLoginIds.add(e.loginId),void this.onLoginBroadcast?.(e.session)}if("session-request"===e.type){const t=`${e.senderTabId}:${e.requestId}`;if(this.handledSessionRequestIds.has(t))return;this.handledSessionRequestIds.add(t);const s=this.getCurrentSession?.();if(!s)return;return void this.publish({type:"session-response",senderTabId:this.tabId,requesterTabId:e.senderTabId,requestId:e.requestId,createdAt:Date.now(),session:s})}if("session-response"===e.type){if(e.requesterTabId!==this.tabId)return;const t=this.pendingSessionRequests.get(e.requestId);if(!t)return;clearTimeout(t.timeout),this.pendingSessionRequests.delete(e.requestId),t.resolve(e.session)}}}}class H{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.version=0}increment(){this.version++}get(){return this.version}check(e){return e===this.version}}class q extends T{constructor(e){super(),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tabSessionCoordinator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"restoreLoginPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"httpClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pushMessageProcessor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handlePageHide",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.ws.disconnect()}}),Object.defineProperty(this,"handlePageShow",{enumerable:!0,configurable:!0,writable:!0,value:e=>{e.persisted&&this.context.isLogin&&this.ws.connect()}}),this.context={isLogin:!1,loginUser:null,isReady:!1,deviceId:null},this.version=new H,this.logger=new x,this.restoreLoginPromise=null,this.tabSessionCoordinator=new B({logger:this.logger,getCurrentSession:()=>this.getTransferableLoginSession(),onLogoutBroadcast:()=>{this.afterLogout()},onLoginBroadcast:e=>{this.applySharedLoginSession(e)}}),this.httpClient=new U({host:e.httpHost,context:this.context,logger:this.logger,developer:e.developer}),this.feedCache=new D,this.ws=new P({host:e.websocketHost,context:this.context,logger:this.logger}),this.pushMessageProcessor=new G({context:this.context,logger:this.logger,emitter:this,feedCache:this.feedCache,onKickoff:()=>{this.afterLogout()}}),this.init()}init(){this.loadContext(),this.ws.on("message",e=>{this.pushMessageProcessor.process(e)}),this.ws.on("kickoff",()=>{this.afterLogout()}),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.handlePageHide),window.addEventListener("pageshow",this.handlePageShow)),setTimeout(()=>{this.restoreLoginFromActiveTab()},0)}getTransferableLoginSession(){return this.context.isLogin&&null!==this.context.loginUser?{deviceId:this.context.deviceId,loginUser:{...this.context.loginUser}}:null}async restoreLoginFromActiveTab(){if(this.restoreLoginPromise)return this.restoreLoginPromise;this.restoreLoginPromise=this.doRestoreLoginFromActiveTab();try{return await this.restoreLoginPromise}finally{this.restoreLoginPromise=null}}async doRestoreLoginFromActiveTab(){if(this.context.isLogin)return!0;const e=await this.tabSessionCoordinator.requestCurrentSession(500);return!e||this.context.isLogin?this.context.isLogin:this.applySharedLoginSession(e)}async applySharedLoginSession(e){return this.context.isLogin||(this.context.isLogin=!0,this.context.loginUser=e.loginUser,e.deviceId&&(this.context.deviceId=e.deviceId),await this.requestDeviceId(),this.applyLoginStatus()),!0}async requestDeviceId(){if(this.context.deviceId)return!0;const e=await this.httpClient.post("/device_api/device_id",{platform:"web",hash_str:""},{needSign:!1});return!!e.ok&&(this.context.deviceId=e.data,this.saveContext(),!0)}saveContext(){const{context:e}=this;N.set({deviceId:e.deviceId})}loadContext(){const e=N.get();e&&e.deviceId&&(this.context.deviceId=e.deviceId)}applyLoginStatus(){this.version.increment(),this.saveContext(),this.context.isLogin?(this.ws.connect(),this.loadFeedList(),this.context.isReady=!0,this.emit(p.SDK_READY)):(this.ws.disconnect(),this.feedCache.reset(),this.context.isReady=!1,this.emit(p.SDK_NOT_READY))}async loadFeedList(){const e=this.version.get(),t={refresh_at:null,feed_id:null};for(;;){const s=await this.httpClient.get("/feed",{limit:500,last_refresh_at:t.refresh_at??void 0,last_feed_id:t.feed_id??void 0});if(!this.version.check(e))break;if(!s.ok||null===s.data)break;if(t.refresh_at=s.data.refresh_at,t.feed_id=s.data.last_feed_id,(s.data.feed_list??[]).forEach(e=>{this.feedCache.push(e)}),!s.data.has_more)break}this.version.check(e)&&(this.feedCache.markSyncComplete(),this.emit(p.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:!0}))}isReady(){return this.context.isReady}setLogLevel(e){this.logger.setLogLevel(e)}async login(e){if(this.context.isLogin)return b(null);if(await this.restoreLoginFromActiveTab()||this.context.isLogin)return b(null);if(await this.requestDeviceId(),!this.context.deviceId)return this.logger.error("Get deviceId failed"),E(u.SDK_ERROR,"Get deviceId failed");const t=await this.httpClient.post("/user/session/login",{userCode:e.user_code,device_id:this.context.deviceId},{needSign:!1});if(!t.ok)return t;this.context.isLogin=!0,this.context.loginUser={userId:t.data.id,secretKey:t.data.key,sessionId:e.user_code},this.applyLoginStatus();const s=this.getTransferableLoginSession();return s&&this.tabSessionCoordinator.publishLogin(s),b(null)}async logout(){if(!this.context.isLogin)return b(null);const e=await this.httpClient.get("/user/logout");return e.ok?(this.tabSessionCoordinator.publishLogout(),this.afterLogout(),b(null)):e}afterLogout(){(this.context.isLogin||this.context.isReady)&&(this.context.isLogin=!1,this.context.loginUser=null,this.applyLoginStatus())}getLoginUser(){return null===this.context.loginUser?null:this.context.loginUser.userId}async createSingleChatFeed(e){return await this.httpClient.post("/chat/single",{receiver_id:e})}async deleteFeed(e){return await this.httpClient.post("/feed/delete",{feed_id_list:[e],delete_peer:!0})}async getFeedList(){return b({list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}async getFeedDetail(e){return b(await this.feedCache.waitFor(e))}async getFeedMemberList(e){const t=await this.feedCache.get(e);return null!==t&&t.chat_member.length>0?await this.httpClient.post("/chat/chatter_info",{chatters:{[t.chat_id]:t.chat_member}}):b([])}async getUserByUids(e){const t=await this.httpClient.post("/user/users_info",e);return t.ok?b(t.data.map(e=>({id:e.id}))):t}getDomain(e){const[t,s]=c,i=w(t),n=w(s);for(const o of e){if(i.test(o.content))return t;if(n.test(o.content))return s}}appendXsid(e){if(!this.context.loginUser?.sessionId)return e;const t=this.context.loginUser.sessionId,s=this.getDomain(e);return s?e.map(e=>{const i=v(e.content,s,e=>((e,t,s)=>{const i=encodeURIComponent(t),n=encodeURIComponent(s),o=e.indexOf("#"),r=o>=0?e.slice(0,o):e,a=o>=0?e.slice(o):"",d=new RegExp(`([?&])${C(i)}=[^&#]*`);if(d.test(r))return r.replace(d,`$1${i}=${n}`)+a;const l=r.includes("?")?"&":"?";return`${r}${l}${i}=${n}${a}`})(e,"xsid",t));return{...e,content:i}}):e}async markFeedMessageAsRead(t){const s=this.feedCache.get(t);if(!s)return b(!1);if(!(await this.httpClient.post("/feed/update",{id:s.id,mark_unread:e.yes})).ok)return b(!1);return(await this.httpClient.post("/message/read",{chat_id:s.chat_id,thread_id:s.thread_id})).ok?b(!0):b(!1)}async getMessagesByIds(e,t){const s=this.feedCache.get(e);if(!s||!Array.isArray(t)||0===t.length)return b([]);const i=await this.httpClient.post("/message/get_by_msgid",{chat_msg_id_map:{[s.chat_id]:t}});if(i.ok){return b(this.appendXsid(i.data[s.chat_id]))}return b([])}async getFeedMessageList(e){const t=await this.getFeedDetail(e.feed_id);if(t.ok&&t.data){const s=t.data,{chat_id:i,first_position:n,last_message_position:o}=s,{positions:r,nextPosition:a,hasMore:d}=(e=>{const t=[];if(e.direction===g.up){let s=e.startPosition??e.maxPosition;for(;t.length<e.limit&&s>=e.minPosition;)t.push(s),s--;const i=s>=e.minPosition;let n;return i&&(n=s),{positions:t,nextPosition:n,hasMore:i}}{let s=e.startPosition??e.minPosition;for(;t.length<e.limit&&s<=e.maxPosition;)t.push(s),s++;const i=s<=e.maxPosition;let n;return i&&(n=s),{positions:t,nextPosition:n,hasMore:i}}})({maxPosition:o,minPosition:n,startPosition:e.message_position,limit:e.limit,direction:e.direction??g.up});if(r.length>0){const e=await this.httpClient.post("/message/get_by_position",{chat_position:{[i]:r}},{needSign:!1});if(e.ok&&e.data[i]){return b({has_more:d,list:this.appendXsid(e.data[i].reverse()),next_message_position:a})}}}return b({has_more:!1,list:[]})}async removeMessages(e){const t=this.feedCache.get(e.feedId);return null===t?E(u.SDK_ERROR,"not found feed"):this.httpClient.post("/message/remove",{chat_id:t.chat_id,message_ids:e.messageIds,two_way:e.twoWay,delete_feed:e.deleteFeed??0})}async addReaction(e){if(!e.reaction)return E(u.SDK_ERROR,"reaction is empty");const t=this.feedCache.get(e.feedId);return null===t?E(u.SDK_ERROR,"not found feed"):this.httpClient.post("/message/reaction/add",{feed_id:t.id,chat_id:t.chat_id,message_id:e.messageId,reaction:e.reaction,reaction_op_id:e.reactionOpId})}async deleteReaction(e){if(!e.reaction)return E(u.SDK_ERROR,"reaction is empty");const t=this.feedCache.get(e.feedId);return null===t?E(u.SDK_ERROR,"not found feed"):this.httpClient.post("/message/reaction/delete",{feed_id:t.id,chat_id:t.chat_id,message_id:e.messageId,reaction:e.reaction,reaction_op_id:e.reactionOpId})}async getFolders(e){const t=e&&e.length>0?{folder_ids:e.join(",")}:void 0,s=await this.httpClient.get("/folder",t,{transformResponse:[e=>"string"!=typeof e?e:function(e){const t=e.replace(/("id"\s*:\s*)(-?\d+)(\s*[,}\]])/g,'$1"$2"$3');return JSON.parse(t)}(e)]});if(!s.ok)return s;return b((s.data??[]).map(e=>{return{...e,id:(t=e.id,"string"==typeof t?t:"bigint"==typeof t?t.toString():"number"==typeof t&&Number.isFinite(t)?Math.trunc(t).toString():String(t))};var t}))}createCustomMessage(e){if(null===this.context.loginUser)return E(u.SDK_ERROR,"not login");const t=this.feedCache.get(e.feed_id);if(null===t)return E(u.SDK_ERROR,"not found feed");const s=(new Date).toISOString();var i;return b({id:"",chat_id:t.chat_id,thread_id:e.thread_id??t.thread_id,reply_msg_id:e.reply_msg_id??"0",thread_begin:0,thread_msg_id:e.thread_msg_id,position:t.last_message_position,sender_id:this.context.loginUser.userId,message_kind_id:n.text,message_type_id:o.custom,send_at:s,edited_at:s,reader_ids:[],unreader_ids:[],hide_ids:[],operation:a.normal,operation_user_id:"0",content:(i={client_msg_id:e.client_msg_id,content:e.content},JSON.stringify({client_msg_id:i.client_msg_id,content:JSON.stringify(i.content)})),reactions:[]})}async sendMessageToFeed(e){if(e.message_type_id===o.custom){const t=S(e.content),s={chat_id:e.chat_id,thread_id:e.thread_id,client_id:t.client_msg_id,content:null==t.content?void 0:JSON.stringify(t.content)};return e.reply_msg_id&&"0"!==e.reply_msg_id&&(s.reply_msg_id=e.reply_msg_id),e.thread_msg_id&&"0"!==e.thread_msg_id&&(s.thread_msg_id=e.thread_msg_id),this.httpClient.post("/message/send_custom",s)}return E(u.SDK_ERROR,"not support")}async sendMessageReadReceipt(e){const t=this.feedCache.get(e.feed_id);return null===t?E(u.SDK_ERROR,"not found feed"):await this.httpClient.post("/message/read",{chat_id:t.chat_id,message_ids:e.message_ids})}async joinRoom(e){return await this.httpClient.post("/liveshow/join",{room_id:e})}async setMute(t){const s=await this.httpClient.post("/feed/update",{id:t.feedId,is_mute:t.isMute?e.yes:e.no});return s.ok?s.data:null}async setPin(t){const s=await this.httpClient.post("/feed/update",{id:t.feedId,pin:t.pin?e.yes:e.no});return s.ok?s.data:null}async setName(e){const t=await this.httpClient.post("/feed/update",{id:e.feedId,name:e.name});return t.ok?t.data:null}async setSave(t){const s=await this.httpClient.post("/feed/update",{id:t.feedId,is_save:t.isSave?e.yes:e.no});return s.ok?s.data:null}async setArchive(t){const s=await this.httpClient.post("/feed/update",{id:t.feedId,is_archive:t.isArchive?e.yes:e.no});return s.ok?s.data:null}async setMark(t){const s=await this.httpClient.post("/feed/update",{id:t.feedId,is_mark:t.isMark?e.yes:e.no});return s.ok?s.data:null}async leaveRoom(e){return await this.httpClient.post("/liveshow/leave",{room_id:e})}async getJoinedRooms(){return await this.httpClient.get("/liveshow/joined_rooms")}async getRoomRecentMessageList(e){const t=await this.httpClient.get("/liveshow/get_recent_message",{room_id:e});return t.ok?b(t.data):t}async sendMessageToRoom(e){return await this.httpClient.post("/liveshow/send_message",{room_id:e.room_id,content:e.content})}}const $=new Map;const V={parseSystemMessageContent:e=>{const t=y(e);return null!==t?{text:t.text,text_i18n:t.text_i18n}:{}},parseTextMessageContent:e=>{const t=y(e);return null!==t?{text:t.text,client_msg_id:t.client_msg_id}:{}},parseCustomMessageContent:S};exports.ChatSDK=q,exports.create=function(e,t){let s=$.get(e);return void 0===s&&(s=new q(t),$.set(e,s)),s},exports.enums=_,exports.events=f,exports.interfaces=m,exports.utils=V;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typexim/web-sdk",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",