@typexim/web-sdk 0.0.4-alpha.9 → 0.0.5-alpha.10

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
@@ -48,11 +48,13 @@ chat.once(
48
48
  1. SDK_READY
49
49
  2. SDK_NOT_READY
50
50
  3. MESSAGE_RECEIVED
51
- 4. MESSAGE_RECALLED
52
- 5. MESSAGE_RECEIPT_RECEIVED
53
- 6. FEED_LIST_UPDATED
54
- 7. ROOM_MESSAGE_RECEIVED
55
- 8. SYSTEM_NOTICE_RECEIVED
51
+ 4. MESSAGE_EDITED
52
+ 5. MESSAGE_RECALLED
53
+ 6. MESSAGE_REACTION_UPDATED
54
+ 7. MESSAGE_RECEIPT_RECEIVED
55
+ 8. FEED_LIST_UPDATED
56
+ 9. ROOM_MESSAGE_RECEIVED
57
+ 10. SYSTEM_NOTICE_RECEIVED
56
58
 
57
59
  ### 初始化
58
60
 
@@ -78,6 +80,7 @@ chat.once(
78
80
  2. deleteFeed
79
81
  3. getFeedList(不分页,最多100条)
80
82
  4. getFeedDetail
83
+ 5. getFeedMemberList
81
84
 
82
85
  ### 会话Feed消息
83
86
 
@@ -1,4 +1,4 @@
1
- export declare enum Boolean {
1
+ export declare enum Bool {
2
2
  yes = 1,
3
3
  no = 0
4
4
  }
@@ -107,5 +107,18 @@ export declare enum MessageOperation {
107
107
  /**
108
108
  * 撤回
109
109
  */
110
- recall = 1
110
+ recall = 1,
111
+ /**
112
+ * 销毁
113
+ */
114
+ destroy = 2,
115
+ /**
116
+ * 编辑
117
+ */
118
+ edit = 3,
119
+ /**
120
+ * thread主消息删除
121
+ */
122
+ main_delete = 4
111
123
  }
124
+ export declare const RESOURCE_AUTH_DOMAINS: readonly ["api-coco.typex.im", "api-tx.typex-test.cn"];
@@ -1,4 +1,4 @@
1
- import { Feed, Message } from './interfaces';
1
+ import { Feed, Message, Reaction } from './interfaces';
2
2
  export declare const CHAT_SDK_EVENT: {
3
3
  /**
4
4
  * sdk用户已登录,可以调用发送消息等API
@@ -20,6 +20,18 @@ export declare const CHAT_SDK_EVENT: {
20
20
  * message撤回
21
21
  */
22
22
  readonly MESSAGE_RECALLED: "messageRecalled";
23
+ /**
24
+ * message编辑
25
+ */
26
+ readonly MESSAGE_EDITED: "messageEdited";
27
+ /**
28
+ * message销毁
29
+ */
30
+ readonly MESSAGE_DESTROYED: "messageDestroyed";
31
+ /**
32
+ * message回复表情更新
33
+ */
34
+ readonly MESSAGE_REACTION_UPDATED: "messageReactionUpdated";
23
35
  /**
24
36
  * sdk收到message已读回执
25
37
  */
@@ -56,12 +68,28 @@ export type CHAT_SDK_EVENT_MAP = {
56
68
  */
57
69
  message: Message;
58
70
  };
71
+ [CHAT_SDK_EVENT.MESSAGE_DESTROYED]: {
72
+ /**
73
+ * 收到的消息所属的feed_id
74
+ */
75
+ feed_id: string;
76
+ /**
77
+ * 收到的消息
78
+ */
79
+ message_ids: string[];
80
+ };
59
81
  [CHAT_SDK_EVENT.MESSAGE_RECALLED]: {
60
82
  /**
61
83
  * 撤回的消息id列表
62
84
  */
63
85
  message_ids: string[];
64
86
  };
87
+ [CHAT_SDK_EVENT.MESSAGE_EDITED]: Pick<Message, 'chat_id' | 'content' | 'edited_at' | 'id' | 'message_kind_id' | 'message_type_id' | 'operation' | 'operation_user_id' | 'thread_id'>;
88
+ [CHAT_SDK_EVENT.MESSAGE_REACTION_UPDATED]: {
89
+ feed_id: string;
90
+ message_id: string;
91
+ reactions: Reaction[];
92
+ };
65
93
  [CHAT_SDK_EVENT.MESSAGE_RECEIPT_RECEIVED]: {
66
94
  /**
67
95
  * feed id
@@ -78,7 +106,11 @@ export type CHAT_SDK_EVENT_MAP = {
78
106
  };
79
107
  [CHAT_SDK_EVENT.ROOM_MESSAGE_RECEIVED]: {
80
108
  /**
81
- * 收到的消息
109
+ * 直播间id
110
+ */
111
+ room_id: string;
112
+ /**
113
+ * 消息内容
82
114
  */
83
115
  content: string;
84
116
  };
@@ -1,4 +1,4 @@
1
- import { ChatType, FeedType, MessageKind, MessageOperation, MessageType } from '../enums';
1
+ import { Bool, ChatType, FeedType, MessageKind, MessageOperation, MessageType } from '../enums';
2
2
  export type ApiResponse<T = any> = {
3
3
  code: number;
4
4
  data: T;
@@ -23,6 +23,28 @@ export type User = {
23
23
  key: string;
24
24
  session_id: string;
25
25
  };
26
+ export type Chatter = {
27
+ /**
28
+ * 头像地址
29
+ */
30
+ avatar: string;
31
+ /**
32
+ * chat id
33
+ */
34
+ chat_id: string;
35
+ /**
36
+ * chatter id
37
+ */
38
+ chatter_id: string;
39
+ /**
40
+ * 名称
41
+ */
42
+ name: string;
43
+ /**
44
+ * user id
45
+ */
46
+ user_id: string;
47
+ };
26
48
  export type Feed = {
27
49
  /**
28
50
  * feedId
@@ -43,13 +65,13 @@ export type Feed = {
43
65
  /**
44
66
  * 单聊时对方的user_id
45
67
  */
46
- target_id: string;
68
+ target_id?: string;
47
69
  /**
48
70
  * chat类型
49
71
  */
50
72
  chat_type: ChatType;
51
73
  /**
52
- * 会话成员的user_id列表
74
+ * 会话成员的chatter_id列表
53
75
  */
54
76
  chat_member: string[];
55
77
  /**
@@ -112,6 +134,51 @@ export type Feed = {
112
134
  * 最后一条消息的操作人id
113
135
  */
114
136
  last_message_operation_user_id: string;
137
+ show_real?: Bool;
138
+ is_mute?: Bool;
139
+ chat: {
140
+ id: string;
141
+ init_user_id: string;
142
+ chat_type: ChatType;
143
+ max_position: number;
144
+ status: number;
145
+ e2e: Bool;
146
+ updated_at: string;
147
+ created_at: string;
148
+ deleted_at: string;
149
+ ext: any;
150
+ };
151
+ group_chat?: {
152
+ id: string;
153
+ chat_id: string;
154
+ name: string;
155
+ avatar: string;
156
+ notice: string;
157
+ admin_user: Array<{
158
+ id: string;
159
+ set_by_user_id: string;
160
+ set_by_user_name: string;
161
+ }>;
162
+ owner_user_id: string;
163
+ desc?: string;
164
+ chat_member_count: number;
165
+ /** 邀请链接权限 0: 未开启;1: 开启 */
166
+ destruction_time?: number;
167
+ my_tags?: Array<{
168
+ id: string;
169
+ name: string;
170
+ }>;
171
+ invite_code: string;
172
+ show_real?: number;
173
+ invite_code_expire_time?: number;
174
+ invite_code_user_limit?: number;
175
+ show_avatar?: Bool;
176
+ };
177
+ };
178
+ export type ReactionUser = Pick<Chatter, 'avatar' | 'name' | 'user_id'>;
179
+ export type Reaction = {
180
+ emoji: string;
181
+ user_list: ReactionUser;
115
182
  };
116
183
  export type Message = {
117
184
  /**
@@ -150,6 +217,10 @@ export type Message = {
150
217
  * 发送时间
151
218
  */
152
219
  send_at: string;
220
+ /**
221
+ * 编辑时间
222
+ */
223
+ edited_at: string;
153
224
  /**
154
225
  * 已读信息的用户id
155
226
  */
@@ -170,4 +241,8 @@ export type Message = {
170
241
  * 消息操作人id
171
242
  */
172
243
  operation_user_id: string;
244
+ /**
245
+ * 对消息的回复表情
246
+ */
247
+ reactions: Reaction[];
173
248
  };
@@ -1,5 +1,5 @@
1
- import { PushMessageType } from '../enums';
2
- import { Feed, Message } from './business';
1
+ import { Bool, PushMessageType } from '../enums';
2
+ import { Chatter, Feed, Message, Reaction } from './business';
3
3
  export type PushMessageBase<T = PushMessageType, U = unknown> = {
4
4
  id: string;
5
5
  timestamp?: number;
@@ -12,16 +12,46 @@ export type PushMessageBigPackageContent = {
12
12
  };
13
13
  export type PushMessageBigPackage = PushMessageBase<PushMessageType.BIG_PACKAGE_PUSH, PushMessageBigPackageContent>;
14
14
  export type PushMessageCreateFeed = PushMessageBase<PushMessageType.CREATE_FEED, Feed>;
15
- export type PushMessageUpdateFeeds = PushMessageBase<PushMessageType.UPDATE_FEED>;
16
- export type PushMessageAddMessage = PushMessageBase<PushMessageType.ADD_MESSAGE, Message>;
15
+ export type PushMessageUpdateFeeds = PushMessageBase<PushMessageType.UPDATE_FEED, Feed>;
16
+ export type PushMessageAddMessage = PushMessageBase<PushMessageType.ADD_MESSAGE, Message & {
17
+ /**
18
+ * 值为Bool.yes时,消息不参与已读/未读逻辑,直接已读处理
19
+ */
20
+ no_read?: Bool;
21
+ /**
22
+ * 值为Bool.yes时,消息不会导致feed排序更新,也不会更新feed的last_message_*
23
+ */
24
+ no_last_msg?: Bool;
25
+ }>;
17
26
  export type PushMessageUpdateMessage = PushMessageBase<PushMessageType.UPDATE_MESSAGE, Partial<Message> & Pick<Message, 'id' | 'chat_id' | 'thread_id'>>;
27
+ export type PushMessageDeleteMessage = PushMessageBase<PushMessageType.DELETE_MESSAGE, Partial<Message> & Pick<Message, 'id' | 'chat_id' | 'thread_id'> & {
28
+ expire_ids?: string[];
29
+ }>;
18
30
  export type PushMessageDeleteFeed = PushMessageBase<PushMessageType.DELETE_FEED, {
19
31
  /**
20
32
  * feed id
21
33
  */
22
34
  id: string;
23
35
  }>;
24
- export type PushMessagePushLiveMessage = PushMessageBase<PushMessageType.PUSH_LIVE_MESSAGE, string>;
36
+ export type PushMessageUpdateMessageReaction = PushMessageBase<PushMessageType.UPDATE_MESSAGE_REACTION, {
37
+ chat_id: string;
38
+ thread_id: string;
39
+ message_id: string;
40
+ reactions: Reaction[];
41
+ }>;
42
+ /**
43
+ * 直播间消息推送,调用/liveshow/send_message触发
44
+ */
45
+ export type PushMessagePushLiveMessage = PushMessageBase<PushMessageType.PUSH_LIVE_MESSAGE, {
46
+ /**
47
+ * 直播间id
48
+ */
49
+ room_id: string;
50
+ /**
51
+ * 消息内容
52
+ */
53
+ message: string;
54
+ }>;
25
55
  export type PushMessageReadMessage = PushMessageBase<PushMessageType.READ_MESSAGE, {
26
56
  chat_id: string;
27
57
  message_ids: string[];
@@ -29,5 +59,25 @@ export type PushMessageReadMessage = PushMessageBase<PushMessageType.READ_MESSAG
29
59
  thread_id: string;
30
60
  }>;
31
61
  export type PushMessagePushSystemNotice = PushMessageBase<PushMessageType.PUSH_SYSTEM_NOTICE, string>;
32
- export type SpecialPushMessage = PushMessagePong | PushMessageBigPackage | PushMessageCreateFeed | PushMessageUpdateFeeds | PushMessageAddMessage | PushMessageUpdateMessage | PushMessageDeleteFeed | PushMessagePushLiveMessage | PushMessageReadMessage | PushMessagePushSystemNotice;
62
+ export type PushMessageAddGroupMember = PushMessageBase<PushMessageType.ADD_GROUP_MEMBER, {
63
+ chat_id: string;
64
+ chat_member: Chatter[];
65
+ }>;
66
+ export type PushMessageDelGroupMember = PushMessageBase<PushMessageType.DEL_GROUP_MEMBER, {
67
+ chat_id: string;
68
+ chat_member: Chatter[];
69
+ }>;
70
+ export type PushMessageUpdateGroup = PushMessageBase<PushMessageType.UPDATE_GROUP, {
71
+ chat_id: string;
72
+ name?: string;
73
+ avatar?: string;
74
+ }>;
75
+ export type PushMessageUpdateUserData = PushMessageBase<PushMessageType.UPDATE_USER_DATA, {
76
+ id: string;
77
+ first_name?: string;
78
+ last_name?: string;
79
+ avatar?: string;
80
+ }>;
81
+ export type PushMessageUpdateFeedData = PushMessageBase<PushMessageType.UPDATE_FEED, Feed>;
82
+ export type SpecialPushMessage = PushMessagePong | PushMessageBigPackage | PushMessageCreateFeed | PushMessageUpdateFeeds | PushMessageAddMessage | PushMessageUpdateMessage | PushMessageDeleteFeed | PushMessagePushLiveMessage | PushMessageReadMessage | PushMessagePushSystemNotice | PushMessageAddGroupMember | PushMessageDelGroupMember | PushMessageUpdateGroup | PushMessageUpdateUserData | PushMessageUpdateMessageReaction | PushMessageUpdateFeedData | PushMessageDeleteMessage;
33
83
  export type PushMessage = PushMessageBase<Exclude<PushMessageType, SpecialPushMessage['type']>> | SpecialPushMessage;
@@ -1,6 +1,6 @@
1
1
  import { LogLevel } from '../enums';
2
2
  import { CHAT_SDK_EVENT_MAP } from '../events';
3
- import { Feed, Message } from '../interfaces';
3
+ import { Chatter, Feed, Message } from '../interfaces';
4
4
  import { ChatSDKConfig, HttpClientResponse, SDKCreateCustomMessageReq, SDKGetFeedListResp, SDKGetFeedMessageListReq, SDKGetFeedMessageListResp, SDKGetRoomRecentMessageListResp, SDKLoginReq, SDKSendMessageReadReceiptReq, SDKSendMessageToRoomReq } from '../interfaces/sdk';
5
5
  import Base from './Base';
6
6
  export default class ChatSDK extends Base<CHAT_SDK_EVENT_MAP> {
@@ -70,6 +70,31 @@ export default class ChatSDK extends Base<CHAT_SDK_EVENT_MAP> {
70
70
  * @returns
71
71
  */
72
72
  getFeedDetail(feed_id: string): Promise<HttpClientResponse<Feed | null>>;
73
+ /**
74
+ * 根据 Feed ID 获取Feed的成员列表
75
+ * @param feed_id
76
+ * @returns
77
+ */
78
+ getFeedMemberList(feed_id: string): Promise<HttpClientResponse<Chatter[]>>;
79
+ private getDomain;
80
+ /**
81
+ * 检测链接域名并为需要鉴权的域名添加x-sid参数
82
+ * @param messages
83
+ */
84
+ private appendXsid;
85
+ /**
86
+ * 标记Feed的所有消息为已读
87
+ * @param feedId
88
+ * @returns
89
+ */
90
+ markFeedMessageAsRead(feedId: string): Promise<HttpClientResponse<boolean>>;
91
+ /**
92
+ * 获取Feed的消息
93
+ * @param feedId
94
+ * @param messageIds
95
+ * @returns
96
+ */
97
+ getMessagesByIds(feedId: string, messageIds: string[]): Promise<import("../interfaces").HttpClientResponseOk<Message[]>>;
73
98
  /**
74
99
  * 获取某个 Feed 的消息列表
75
100
  * @param req
@@ -98,6 +123,16 @@ export default class ChatSDK extends Base<CHAT_SDK_EVENT_MAP> {
98
123
  * @returns {Promise<HttpClientResponse>} 请求结果
99
124
  */
100
125
  joinRoom(room_id: string): Promise<HttpClientResponse>;
126
+ /**
127
+ * 设置 Feed 是否静言
128
+ * @param feedId Feed id
129
+ * @param isMute 是否静言
130
+ * @returns
131
+ */
132
+ setMute(params: {
133
+ feedId: string;
134
+ isMute: boolean;
135
+ }): Promise<Feed | null>;
101
136
  /**
102
137
  * 离开直播间
103
138
  * @param {string} room_id 直播间id
@@ -4,12 +4,14 @@ export default class FeedCache {
4
4
  private map;
5
5
  private chatMap;
6
6
  private threadMap;
7
+ private targetMap;
7
8
  private list;
8
9
  private waitMap;
9
10
  constructor();
10
11
  getAll(): Feed[];
11
12
  get(feedId: string): Feed | null;
12
13
  getByChat(chatId: string, threadId: string): Feed | null;
14
+ getByTargetId(targetId: string): Feed[];
13
15
  waitFor(feedId: string): Promise<Feed | null>;
14
16
  private resolveWait;
15
17
  private removeFromList;
@@ -18,12 +18,18 @@ export default class PushMessageProcessor {
18
18
  });
19
19
  private emitFeedListUpdated;
20
20
  private processCreateFeed;
21
+ private processUpdateFeed;
21
22
  private processDeleteFeed;
22
23
  private processAddMessage;
23
24
  private processUpdateMessage;
25
+ private processDeleteMessage;
24
26
  private processPushLiveMessage;
25
27
  private processPushSystemNotice;
26
28
  private processReadMessage;
27
29
  private processKickOutDevice;
30
+ private processGroupMember;
31
+ private processUpdateGroup;
32
+ private processUpdateUserData;
33
+ private processUpdateMessageReaction;
28
34
  process(pushMessage: PushMessage): void;
29
35
  }
@@ -35,3 +35,22 @@ export declare const parseTextMessageContent: (str: string) => {
35
35
  text?: string;
36
36
  client_msg_id?: string;
37
37
  };
38
+ /**
39
+ * 向URL添加查询参数
40
+ * @param url
41
+ * @param key
42
+ * @param value
43
+ * @returns
44
+ */
45
+ export declare const appendQueryParam: (url: string, key: string, value: string) => string;
46
+ /**
47
+ * 按域名匹配 JSON 字符串中的 URL
48
+ * 同时支持:
49
+ * - https://api-coco.typex.im/...
50
+ * - https:\/\/api-coco.typex.im\/...
51
+ */
52
+ export declare const createDomainUrlRegex: (domain: string) => RegExp;
53
+ /**
54
+ * 替换消息 content(JSON 字符串)里指定域名的 URL
55
+ */
56
+ export declare const replaceDomainUrlsInContent: (content: string, domain: string, replaceUrl: (url: string) => string) => string;
@@ -1 +1 @@
1
- import e from"js-cookie";import t from"axios";import i from"crypto-js";var s,n,o,r,a,l,c,d,h,u,_;!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"}(n||(n={})),function(e){e[e.singleChat=1]="singleChat",e[e.groupChat=2]="groupChat"}(o||(o={})),function(e){e[e.normal=0]="normal",e[e.thread=1]="thread"}(r||(r={})),function(e){e[e.text=0]="text",e[e.system=1]="system"}(a||(a={})),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"}(l||(l={})),function(e){e[e.Owner=1]="Owner",e[e.Admin=2]="Admin",e[e.Common=3]="Common",e[e.Bot=4]="Bot"}(c||(c={})),function(e){e[e.normal=0]="normal",e[e.recall=1]="recall"}(d||(d={})),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.REQUEST_SINGLETON_LOCK_FAIL=-9997]="REQUEST_SINGLETON_LOCK_FAIL",e[e.SUCCESS=0]="SUCCESS"}(u||(u={})),function(e){e[e.up=0]="up",e[e.down=1]="down"}(_||(_={}));var g=Object.freeze({__proto__:null,get Boolean(){return s},get ChatType(){return o},get FeedType(){return r},get GroupRole(){return c},get HttpClientResponseCode(){return u},get LogLevel(){return h},get MessageKind(){return a},get MessageOperation(){return d},get MessageType(){return l},get PushMessageType(){return n},get RequestDirection(){return _}});const E={SDK_READY:"sdkReady",SDK_NOT_READY:"sdkNotReady",FEED_LIST_UPDATED:"feedListUpdated",MESSAGE_RECEIVED:"messageReceived",MESSAGE_RECALLED:"messageRecalled",MESSAGE_RECEIPT_RECEIVED:"messageReceiptReceived",ROOM_MESSAGE_RECEIVED:"roomMessageReceived",SYSTEM_NOTICE_RECEIVED:"systemNoticeReceived"};var m=Object.freeze({__proto__:null,CHAT_SDK_EVENT:E}),p=Object.freeze({__proto__:null});function f(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}},C=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{}};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 i=this.all.get(e);return i?i.push(t):this.all.set(e,[t]),()=>{this.off(e,t)}}off(e,t){const i=this.all.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let i=this.all.get(e);i&&i.slice().map(e=>{e(t)}),i=this.all.get("*"),i&&i.slice().map(i=>{i(e,t)})}once(e,t){if("*"===e){const i=(e,s)=>{t(e,s),this.off("*",i)};this.on(e,i)}else{const i=s=>{t(s),this.off(e,i)};this.on(e,i)}}}class A extends T{constructor(e){super(),Object.defineProperty(this,"url",{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.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(this.url);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===n.PONG_MESSAGE?null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null,this.delaySendPing()):this.sendAck(t.id),t.type===n.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 R 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(){if(null===this.context.loginUser)return void this.logger.warn("BusinessWebsocket try connect but not login");if(this.ws)return void this.logger.warn("BusinessWebsocket try connect but already connected");const e=`${this.host}/ws?token=${this.context.loginUser.sessionId}&platform=web`;this.ws=new A({url:e,logger:this.logger}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("kickoff",()=>{this.emit("kickoff")})}disconnect(){this.ws?(this.ws.destroy(),this.ws=null):this.logger.info("BusinessWebsocket already disconnected")}}class v{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,"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.waitMap=new Map,this.list=[]}getAll(){const e=[];for(const t of this.list){const i=this.map.get(t);i&&e.push(i)}return e}get(e){return this.map.get(e)??null}getByChat(e,t){let i;return i=t&&"0"!==t?this.threadMap.get(t):this.chatMap.get(e),void 0!==i?this.get(i):null}async waitFor(e){const t=this.get(e);if(t)return t;if(this.syncCompleted)return null;let i=this.waitMap.get(e);return i||(i=(()=>{let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}})(),this.waitMap.set(e,i)),await i.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);return!!t&&(this.map.delete(e),t.feed_type===r.thread?this.threadMap.delete(t.thread_id):this.chatMap.delete(t.chat_id),this.removeFromList(e),!0)}beforeSave(e){this.map.has(e.id)?this.removeFromList(e.id):e.feed_type===r.thread?this.threadMap.set(e.thread_id,e.id):this.chatMap.set(e.chat_id,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.waitMap.clear(),this.list=[]}}function y(e){return(new TextEncoder).encode(e).buffer}async function w(e,t){return window.crypto&&window.crypto.subtle?await async function(e,t){const i=y(t),s=y(e),n=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,s);return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e,t):function(e,t){return i.HmacSHA256(e,t).toString(i.enc.Hex)}(e,t)}const P=e=>{if(null==e)return"";if("object"!=typeof e||Array.isArray(e)){if(Array.isArray(e)){let t="";for(const i of e)t+=P(i);return t}return"string"==typeof e?e:String(e)}{const t=Object.keys(e).sort();let i="";for(const s of t)i+=P(e[s]);return i}};function O(){return f(u.MAKE_SIGN_FAIL,"make sign fail")}class D{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=t.create({baseURL:e.host,headers:{"x-developer":e.developer}}),this.context=e.context,this.logger=e.logger}async request(e){try{const{needSign:t=!0,...i}=e;if(i.headers||(i.headers={}),i.headers.platform="web",t&&"POST"===e.method?.toUpperCase()&&i.data){if(null===this.context.loginUser)return this.logger.warn("HttpClient needs make sign but not login"),O();try{const e=await(async(e,t)=>{const i=await P(e);return await w(i,t)})(i.data,this.context.loginUser.secretKey);i.headers.sign=e}catch(e){return this.logger.error("HttpClient make sign error",e),O()}}const s=await this.api(i),n=s.data;return n.code===u.SUCCESS?{ok:!0,data:n.data}:(this.logger.info("HttpClient server error",s),{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,i){return this.request({url:e,method:"GET",params:t,...i})}post(e,t,i){return this.request({url:e,method:"POST",data:t,...i})}}function L(e){return`${e}`.padStart(2,"0")}class M{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 i=new Date,s=`TypeX >> [${`${i.getFullYear()}-${L(i.getMonth()+1)}-${L(i.getDate())} ${L(i.getHours())}:${L(i.getMinutes())}:${L(i.getSeconds())}.${i.getMilliseconds()}`}]`;switch(e){case h.error:console.error(s,"[ERR]",...t);break;case h.warning:console.warn(s,"[WARN]",...t);break;case h.info:console.info(s,"[INFO]",...t);break;default:console.log(s,...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 I{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(E.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}processCreateFeed(e){this.feedCache.unshift(e.content),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,s=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null===s)return;let n=!1;const o={};if(i.message_kind_id!==a.system&&i.sender_id!==t){n=!0;const e=new Set(s.unread_message_ids);e.add(i.id),o.unread_message_ids=[...e],o.badge=e.size}s.last_message_position<i.position&&(n=!0,o.last_message_id=i.id,o.last_message_position=i.position,o.last_message_sender_id=i.sender_id,o.last_message_send_at=i.send_at,o.last_message_kind_id=i.message_kind_id,o.last_message_type_id=i.message_type_id,o.last_message=i.content,o.last_message_operation=i.operation,o.last_message_operation_user_id=i.operation_user_id),n&&(this.feedCache.unshift({...s,...o}),this.emitFeedListUpdated()),this.emitter.emit(E.MESSAGE_RECEIVED,{feed_id:s.id,message:i})}processUpdateMessage(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==i&&null!=t.operation){let e=!1;const s={};if(t.operation===d.recall){if(null!=i.unread_message_ids&&i.unread_message_ids.includes(t.id)){e=!0;const n=new Set(i.unread_message_ids);n.delete(t.id),s.unread_message_ids=[...n],s.badge=s.unread_message_ids.length}i.last_message_id===t.id&&(e=!0,s.last_message=t.content??"{}",s.last_message_operation=t.operation,s.last_message_operation_user_id=t.operation_user_id??"0")}e&&(this.feedCache.unshift({...i,...s}),this.emitFeedListUpdated()),t.operation===d.recall&&this.emitter.emit(E.MESSAGE_RECALLED,{message_ids:[t.id]})}}processPushLiveMessage(e){this.emitter.emit(E.ROOM_MESSAGE_RECEIVED,{content:e.content})}processPushSystemNotice(e){this.emitter.emit(E.SYSTEM_NOTICE_RECEIVED,{content:e.content})}processReadMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,i=e.content,s=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null===s)return;let n=!1;const o={};if(i.reader_ids.includes(t)&&i.message_ids.length>0){n=!0;const e=new Set(s.unread_message_ids);i.message_ids.forEach(t=>{e.delete(t)}),o.unread_message_ids=[...e],o.badge=e.size}n&&(this.feedCache.update({...s,...o}),this.emitFeedListUpdated()),this.emitter.emit(E.MESSAGE_RECEIPT_RECEIVED,{feed_id:s.id,message_ids:i.message_ids,reader_user_ids:i.reader_ids})}processKickOutDevice(){this.handleKickoff()}process(e){switch(this.logger.info("PushMessageProcessor process",e),e.type){case n.CREATE_FEED:this.processCreateFeed(e);break;case n.DELETE_FEED:this.processDeleteFeed(e);break;case n.ADD_MESSAGE:this.processAddMessage(e);break;case n.UPDATE_MESSAGE:this.processUpdateMessage(e);break;case n.PUSH_LIVE_MESSAGE:this.processPushLiveMessage(e);break;case n.PUSH_SYSTEM_NOTICE:this.processPushSystemNotice(e);break;case n.READ_MESSAGE:this.processReadMessage(e);break;case n.KICK_OUT_DEVICE:this.processKickOutDevice()}}}class U{constructor(){Object.defineProperty(this,"obtained",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortLockObtain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.obtained=!1,this.abortLockObtain=null}async requestLock(){if(this.obtained)return!0;let e=()=>{};const t=new Promise(t=>{e=t}),i=new Promise(e=>{this.abortLockObtain=e});navigator.locks.request("typex-sdk",{ifAvailable:!0},async t=>{t?(this.obtained=!0,e(!0),await i):e(!1)});return await t}releaseLock(){this.obtained=!1,null!==this.abortLockObtain&&(this.abortLockObtain(),this.abortLockObtain=null)}}class k{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(k,"key",{enumerable:!0,configurable:!0,writable:!0,value:"__typex_sdk_data__"});class N{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 G 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,"singletonLock",{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}),this.context={isLogin:!1,loginUser:null,isReady:!1,deviceId:null},this.version=new N,this.singletonLock=new U,this.logger=new M,this.httpClient=new D({host:e.httpHost,context:this.context,logger:this.logger,developer:e.developer}),this.feedCache=new v,this.ws=new R({host:e.websocketHost,context:this.context,logger:this.logger}),this.pushMessageProcessor=new I({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()})}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;k.set({deviceId:e.deviceId})}loadContext(){const e=k.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(E.SDK_READY)):(this.ws.disconnect(),this.feedCache.reset(),this.singletonLock.releaseLock(),this.context.isReady=!1,this.emit(E.SDK_NOT_READY))}async loadFeedList(){const e=this.version.get(),t={refresh_at:null,feed_id:null};for(;;){const i=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(!i.ok)break;if(t.refresh_at=i.data.refresh_at,t.feed_id=i.data.last_feed_id,(i.data.feed_list??[]).forEach(e=>{this.feedCache.push(e)}),!i.data.has_more)break}this.version.check(e)&&(this.feedCache.markSyncComplete(),this.emit(E.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:!0}))}isReady(){return this.context.isReady}setLogLevel(e){this.logger.setLogLevel(e)}async login(t){if(this.context.isLogin)return b(null);if(!await this.singletonLock.requestLock())return this.logger.error("Another active TypeX SDK instance detected"),f(u.REQUEST_SINGLETON_LOCK_FAIL,"Another active TypeX SDK instance detected");if(await this.requestDeviceId(),!this.context.deviceId)return this.logger.error("Get deviceId failed"),f(u.SDK_ERROR,"Get deviceId failed");const i=await this.httpClient.post("/user/session/login",{userCode:t.user_code,device_id:this.context.deviceId},{needSign:!1});if(!i.ok)return this.singletonLock.releaseLock(),i;const s=e.get("sessionid");return s?(this.context.isLogin=!0,this.context.loginUser={userId:i.data.id,secretKey:i.data.key,sessionId:s},this.applyLoginStatus(),b(null)):(this.singletonLock.releaseLock(),f(u.SDK_ERROR,"Get sessionId failed"))}async logout(){if(!this.context.isLogin)return b(null);const e=await this.httpClient.get("/user/logout");return e.ok?(this.afterLogout(),b(null)):e}async afterLogout(){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 getFeedMessageList(e){const t=await this.getFeedDetail(e.feed_id);if(t.ok&&t.data){const i=t.data,{chat_id:s,first_position:n,last_message_position:o}=i,{positions:r,nextPosition:a,hasMore:l}=(e=>{const t=[];if(e.direction===_.up){let i=e.startPosition??e.maxPosition;for(;t.length<e.limit&&i>=e.minPosition;)t.push(i),i--;const s=i>=e.minPosition;let n;return s&&(n=i),{positions:t,nextPosition:n,hasMore:s}}{let i=e.startPosition??e.minPosition;for(;t.length<e.limit&&i<=e.maxPosition;)t.push(i),i++;const s=i<=e.maxPosition;let n;return s&&(n=i),{positions:t,nextPosition:n,hasMore:s}}})({maxPosition:o,minPosition:n,startPosition:e.message_position,limit:e.limit,direction:e.direction??_.up});if(r.length>0){const e=await this.httpClient.post("/message/get_by_position",{chat_position:{[s]:r}},{needSign:!1});if(e.ok&&e.data[s]){return b({has_more:l,list:e.data[s].reverse(),next_message_position:a})}}}return b({has_more:!1,list:[]})}createCustomMessage(e){if(null===this.context.loginUser)return f(u.SDK_ERROR,"not login");const t=this.feedCache.get(e.feed_id);if(null===t)return f(u.SDK_ERROR,"not found feed");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:a.text,message_type_id:l.custom,send_at:(new Date).toISOString(),reader_ids:[],unreader_ids:[],hide_ids:[],operation:d.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)}))})}async sendMessageToFeed(e){if(e.message_type_id===l.custom){const t=C(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 f(u.SDK_ERROR,"not support")}async sendMessageReadReceipt(e){const t=this.feedCache.get(e.feed_id);return null===t?f(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 leaveRoom(e){return await this.httpClient.post("/liveshow/leave",{room_id:e})}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 x=new Map;function F(e,t){let i=x.get(e);return void 0===i&&(i=new G(t),x.set(e,i)),i}const K={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:C};export{G as ChatSDK,F as create,g as enums,m as events,p as interfaces,K as utils};
1
+ import e from"axios";import t from"crypto-js";var i,s,n,r,o,a,d,c;!function(e){e[e.yes=1]="yes",e[e.no=0]="no"}(i||(i={})),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"}(s||(s={})),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"}(r||(r={})),function(e){e[e.text=0]="text",e[e.system=1]="system"}(o||(o={})),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"}(c||(c={}));const l=["api-coco.typex.im","api-tx.typex-test.cn"];var h,_,u;!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.REQUEST_SINGLETON_LOCK_FAIL=-9997]="REQUEST_SINGLETON_LOCK_FAIL",e[e.SUCCESS=0]="SUCCESS"}(_||(_={})),function(e){e[e.up=0]="up",e[e.down=1]="down"}(u||(u={}));var g=Object.freeze({__proto__:null,get Bool(){return i},get ChatType(){return n},get FeedType(){return r},get GroupRole(){return d},get HttpClientResponseCode(){return _},get LogLevel(){return h},get MessageKind(){return o},get MessageOperation(){return c},get MessageType(){return a},get PushMessageType(){return s},RESOURCE_AUTH_DOMAINS:l,get RequestDirection(){return u}});const E={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",ROOM_MESSAGE_RECEIVED:"roomMessageReceived",SYSTEM_NOTICE_RECEIVED:"systemNoticeReceived"};var p=Object.freeze({__proto__:null,CHAT_SDK_EVENT:E}),m=Object.freeze({__proto__:null});function f(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}},C=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{}},T=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),A=e=>new RegExp(`https?:\\\\?/\\\\?/${T(e)}(?:\\\\.|[^"\\\\\\s])*`,"g"),y=(e,t,i)=>{if(!e||"string"!=typeof e)return e;const s=A(t);return e.replace(s,e=>{const t=(e=>{try{return JSON.parse(`"${e}"`)}catch{return e}})(e),s=i(t);return"string"!=typeof s||s===t?e:(n=s,JSON.stringify(n).slice(1,-1));var n})};class R{constructor(e){Object.defineProperty(this,"all",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.all=e||new Map}on(e,t){const i=this.all.get(e);return i?i.push(t):this.all.set(e,[t]),()=>{this.off(e,t)}}off(e,t){const i=this.all.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let i=this.all.get(e);i&&i.slice().map(e=>{e(t)}),i=this.all.get("*"),i&&i.slice().map(i=>{i(e,t)})}once(e,t){if("*"===e){const i=(e,s)=>{t(e,s),this.off("*",i)};this.on(e,i)}else{const i=s=>{t(s),this.off(e,i)};this.on(e,i)}}}class D extends R{constructor(e){super(),Object.defineProperty(this,"url",{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.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(this.url);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===s.PONG_MESSAGE?null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null,this.delaySendPing()):this.sendAck(t.id),t.type===s.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 v extends R{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(){if(null===this.context.loginUser)return void this.logger.warn("BusinessWebsocket try connect but not login");if(this.ws)return void this.logger.warn("BusinessWebsocket try connect but already connected");const e=`${this.host}/ws?token=${this.context.loginUser.sessionId}&platform=web`;this.ws=new D({url:e,logger:this.logger}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("kickoff",()=>{this.emit("kickoff")})}disconnect(){this.ws?(this.ws.destroy(),this.ws=null):this.logger.info("BusinessWebsocket already disconnected")}}class w{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 i=this.map.get(t);i&&e.push(i)}return e}get(e){return this.map.get(e)??null}getByChat(e,t){let i;return i=t&&"0"!==t?this.threadMap.get(t):this.chatMap.get(e),void 0!==i?this.get(i):null}getByTargetId(e){const t=this.targetMap.get(e);if(void 0===t)return[];const i=[];for(const e of t){const t=this.get(e);null!==t&&i.push(t)}return i}async waitFor(e){const t=this.get(e);if(t)return t;if(this.syncCompleted)return null;let i=this.waitMap.get(e);return i||(i=(()=>{let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}})(),this.waitMap.set(e,i)),await i.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===r.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===r.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 P(e,i){return window.crypto&&window.crypto.subtle?await async function(e,t){const i=O(t),s=O(e),n=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("HMAC",n,s);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e,i):function(e,i){return t.HmacSHA256(e,i).toString(t.enc.Hex)}(e,i)}const M=e=>{if(null==e)return"";if("object"!=typeof e||Array.isArray(e)){if(Array.isArray(e)){let t="";for(const i of e)t+=M(i);return t}return"string"==typeof e?e:String(e)}{const t=Object.keys(e).sort();let i="";for(const s of t)i+=M(e[s]);return i}};function L(){return f(_.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,...i}=e;if(i.headers||(i.headers={}),i.headers.platform="web",t&&"POST"===e.method?.toUpperCase()&&i.data){if(null===this.context.loginUser)return this.logger.warn("HttpClient needs make sign but not login"),L();try{const e=await(async(e,t)=>{const i=await M(e);return await P(i,t)})(i.data,this.context.loginUser.secretKey);i.headers.sign=e}catch(e){return this.logger.error("HttpClient make sign error",e),L()}}this.context.loginUser&&(i.headers["X-Sid"]=this.context.loginUser.sessionId);const s=await this.api(i),n=s.data;return n.code===_.SUCCESS?{ok:!0,data:n.data}:(this.logger.info("HttpClient server error",s),{ok:!1,code:n.code,msg:n.msg,msg_i18n:n.msg_i18n})}catch{return{ok:!1,code:_.NETWORK_ERROR,msg:"network error"}}}get(e,t,i){return this.request({url:e,method:"GET",params:t,...i})}post(e,t,i){return this.request({url:e,method:"POST",data:t,...i})}}function I(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 i=new Date,s=`TypeX >> [${`${i.getFullYear()}-${I(i.getMonth()+1)}-${I(i.getDate())} ${I(i.getHours())}:${I(i.getMinutes())}:${I(i.getSeconds())}.${i.getMilliseconds()}`}]`;switch(e){case h.error:console.error(s,"[ERR]",...t);break;case h.warning:console.warn(s,"[WARN]",...t);break;case h.info:console.info(s,"[INFO]",...t);break;default:console.log(s,...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(E.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,i=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===i)return;const s={...i,...t};this.feedCache.update(s),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,s=e.content;if(s.hide_ids.includes(t))return;const n=this.feedCache.getByChat(s.chat_id,s.thread_id);if(null!==n){if(s.no_last_msg!==i.yes){let e=!1,r=!1;const a={};if(s.message_kind_id!==o.system&&s.sender_id!==t&&s.no_read!==i.yes){e=!0;const t=new Set(n.unread_message_ids);t.add(s.id),a.unread_message_ids=[...t],a.badge=t.size}if(n.last_message_position<s.position&&(e=!0,r=!0,a.last_message_id=s.id,a.last_message_position=s.position,a.last_message_sender_id=s.sender_id,a.last_message_send_at=s.send_at,a.last_message_kind_id=s.message_kind_id,a.last_message_type_id=s.message_type_id,a.last_message=s.content,a.last_message_operation=s.operation,a.last_message_operation_user_id=s.operation_user_id),e){const e={...n,...a};r?this.feedCache.unshift(e):this.feedCache.update(e),this.emitFeedListUpdated()}}this.emitter.emit(E.MESSAGE_RECEIVED,{feed_id:n.id,message:s})}}processUpdateMessage(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==i&&null!=t.operation){let e=!1;const s={};if(t.operation===c.recall||t.operation===c.destroy){if(null!=i.unread_message_ids&&i.unread_message_ids.includes(t.id)){e=!0;const n=new Set(i.unread_message_ids);n.delete(t.id),s.unread_message_ids=[...n],s.badge=s.unread_message_ids.length}i.last_message_id===t.id&&(e=!0,s.last_message=t.content??"{}",s.last_message_operation=t.operation,s.last_message_operation_user_id=t.operation_user_id??"0")}else t.operation===c.edit&&i.last_message_id===t.id&&(e=!0,s.last_message_kind_id=t.message_kind_id,s.last_message_type_id=t.message_type_id,s.last_message=t.content,s.last_message_operation=t.operation,s.last_message_operation_user_id=t.operation_user_id);e&&(this.feedCache.update({...i,...s}),this.emitFeedListUpdated()),t.operation===c.recall?this.emitter.emit(E.MESSAGE_RECALLED,{message_ids:[t.id]}):t.operation===c.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(E.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===c.destroy&&this.emitter.emit(E.MESSAGE_DESTROYED,{feed_id:i.id,message_ids:[t.id]})}}processDeleteMessage(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===i)return;let s=!1;const n={};i.last_message_id===t.id&&(s=!0,n.last_message=t.content??"{}",n.last_message_operation=t.operation,n.last_message_operation_user_id=t.operation_user_id??"0"),s&&(this.feedCache.update({...i,...n}),this.emitFeedListUpdated()),this.emitter.emit(E.MESSAGE_DESTROYED,{feed_id:i.id,message_ids:[t.id]})}processPushLiveMessage(e){this.emitter.emit(E.ROOM_MESSAGE_RECEIVED,{room_id:e.content.room_id,content:e.content.message})}processPushSystemNotice(e){this.emitter.emit(E.SYSTEM_NOTICE_RECEIVED,{content:e.content})}processReadMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,i=e.content,s=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null===s)return;let n=!1;const r={};if(i.reader_ids.includes(t)&&i.message_ids.length>0){n=!0;const e=new Set(s.unread_message_ids);i.message_ids.forEach(t=>{e.delete(t)}),r.unread_message_ids=[...e],r.badge=e.size}n&&(this.feedCache.update({...s,...r}),this.emitFeedListUpdated()),this.emitter.emit(E.MESSAGE_RECEIPT_RECEIVED,{feed_id:s.id,message_ids:i.message_ids,reader_user_ids:i.reader_ids})}processKickOutDevice(){this.handleKickoff()}processGroupMember(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,"0");if(null===i)return;const n=new Set(i.chat_member),r=e.type===s.ADD_GROUP_MEMBER,o=e.type===s.DEL_GROUP_MEMBER;t.chat_member.forEach(e=>{r?n.add(e.chat_id):o&&n.delete(e.chat_id)}),this.feedCache.update({...i,chat_member:[...n]}),this.emitFeedListUpdated()}processUpdateGroup(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,"0");if(null===i)return;let s=!1;const n={};null!=t.avatar&&(s=!0,n.avatar=t.avatar),null!=t.name&&(s=!0,n.name=t.name),s&&(this.feedCache.update({...i,...n}),this.emitFeedListUpdated())}processUpdateUserData(e){const t=e.content,i=this.feedCache.getByTargetId(t.id);if(i.length>0){const e={};if(null!=t.avatar&&(e.avatar=t.avatar),null!=t.first_name||null!=t.last_name){let i=t.first_name??"";null!=t.last_name&&(i=i.length>0?`${i} ${t.last_name}`:t.last_name),e.name=i}for(const t of i)this.feedCache.update({...t,...e});this.emitFeedListUpdated()}}processUpdateMessageReaction(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,t.thread_id);null!==i&&this.emitter.emit(E.MESSAGE_REACTION_UPDATED,{feed_id:i.id,message_id:t.message_id,reactions:t.reactions})}process(e){switch(this.logger.info("PushMessageProcessor process",e),e.type){case s.CREATE_FEED:this.processCreateFeed(e);break;case s.UPDATE_FEED:this.processUpdateFeed(e);break;case s.DELETE_FEED:this.processDeleteFeed(e);break;case s.ADD_MESSAGE:this.processAddMessage(e);break;case s.UPDATE_MESSAGE:this.processUpdateMessage(e);break;case s.DELETE_MESSAGE:this.processDeleteMessage(e);break;case s.PUSH_LIVE_MESSAGE:this.processPushLiveMessage(e);break;case s.PUSH_SYSTEM_NOTICE:this.processPushSystemNotice(e);break;case s.READ_MESSAGE:this.processReadMessage(e);break;case s.KICK_OUT_DEVICE:this.processKickOutDevice();break;case s.ADD_GROUP_MEMBER:case s.DEL_GROUP_MEMBER:this.processGroupMember(e);break;case s.UPDATE_GROUP:this.processUpdateGroup(e);break;case s.UPDATE_USER_DATA:this.processUpdateUserData(e);break;case s.UPDATE_MESSAGE_REACTION:this.processUpdateMessageReaction(e)}}}class x{constructor(){Object.defineProperty(this,"obtained",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortLockObtain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.obtained=!1,this.abortLockObtain=null}async requestLock(){if(this.obtained)return!0;let e=()=>{};const t=new Promise(t=>{e=t}),i=new Promise(e=>{this.abortLockObtain=e});navigator.locks.request("typex-sdk",{ifAvailable:!0},async t=>{t?(this.obtained=!0,e(!0),await i):e(!1)});return await t}releaseLock(){this.obtained=!1,null!==this.abortLockObtain&&(this.abortLockObtain(),this.abortLockObtain=null)}}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__"});class F{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 K extends R{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,"singletonLock",{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}),this.context={isLogin:!1,loginUser:null,isReady:!1,deviceId:null},this.version=new F,this.singletonLock=new x,this.logger=new k,this.httpClient=new U({host:e.httpHost,context:this.context,logger:this.logger,developer:e.developer}),this.feedCache=new w,this.ws=new v({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()})}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(E.SDK_READY)):(this.ws.disconnect(),this.feedCache.reset(),this.singletonLock.releaseLock(),this.context.isReady=!1,this.emit(E.SDK_NOT_READY))}async loadFeedList(){const e=this.version.get(),t={refresh_at:null,feed_id:null};for(;;){const i=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(!i.ok||null===i.data)break;if(t.refresh_at=i.data.refresh_at,t.feed_id=i.data.last_feed_id,(i.data.feed_list??[]).forEach(e=>{this.feedCache.push(e)}),!i.data.has_more)break}this.version.check(e)&&(this.feedCache.markSyncComplete(),this.emit(E.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.singletonLock.requestLock())return this.logger.error("Another active TypeX SDK instance detected"),f(_.REQUEST_SINGLETON_LOCK_FAIL,"Another active TypeX SDK instance detected");if(await this.requestDeviceId(),!this.context.deviceId)return this.logger.error("Get deviceId failed"),f(_.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});return t.ok?(this.context.isLogin=!0,this.context.loginUser={userId:t.data.id,secretKey:t.data.key,sessionId:e.user_code},this.applyLoginStatus(),b(null)):(this.singletonLock.releaseLock(),t)}async logout(){if(!this.context.isLogin)return b(null);const e=await this.httpClient.get("/user/logout");return e.ok?(this.afterLogout(),b(null)):e}async afterLogout(){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([])}getDomain(e){const[t,i]=l,s=A(t),n=A(i);for(const r of e){if(s.test(r.content))return t;if(n.test(r.content))return i}}appendXsid(e){if(!this.context.loginUser?.sessionId)return e;const t=this.context.loginUser.sessionId,i=this.getDomain(e);return i?e.map(e=>{const s=y(e.content,i,e=>((e,t,i)=>{const s=encodeURIComponent(t),n=encodeURIComponent(i),r=e.indexOf("#"),o=r>=0?e.slice(0,r):e,a=r>=0?e.slice(r):"",d=new RegExp(`([?&])${T(s)}=[^&#]*`);if(d.test(o))return o.replace(d,`$1${s}=${n}`)+a;const c=o.includes("?")?"&":"?";return`${o}${c}${s}=${n}${a}`})(e,"xsid",t));return{...e,content:s}}):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:i.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 i=this.feedCache.get(e);if(!i||!Array.isArray(t)||0===t.length)return b([]);const s=await this.httpClient.post("/message/get_by_msgid",{chat_msg_id_map:{[i.chat_id]:t}});if(s.ok){return b(this.appendXsid(s.data[i.chat_id]))}return b([])}async getFeedMessageList(e){const t=await this.getFeedDetail(e.feed_id);if(t.ok&&t.data){const i=t.data,{chat_id:s,first_position:n,last_message_position:r}=i,{positions:o,nextPosition:a,hasMore:d}=(e=>{const t=[];if(e.direction===u.up){let i=e.startPosition??e.maxPosition;for(;t.length<e.limit&&i>=e.minPosition;)t.push(i),i--;const s=i>=e.minPosition;let n;return s&&(n=i),{positions:t,nextPosition:n,hasMore:s}}{let i=e.startPosition??e.minPosition;for(;t.length<e.limit&&i<=e.maxPosition;)t.push(i),i++;const s=i<=e.maxPosition;let n;return s&&(n=i),{positions:t,nextPosition:n,hasMore:s}}})({maxPosition:r,minPosition:n,startPosition:e.message_position,limit:e.limit,direction:e.direction??u.up});if(o.length>0){const e=await this.httpClient.post("/message/get_by_position",{chat_position:{[s]:o}},{needSign:!1});if(e.ok&&e.data[s]){return b({has_more:d,list:this.appendXsid(e.data[s].reverse()),next_message_position:a})}}}return b({has_more:!1,list:[]})}createCustomMessage(e){if(null===this.context.loginUser)return f(_.SDK_ERROR,"not login");const t=this.feedCache.get(e.feed_id);if(null===t)return f(_.SDK_ERROR,"not found feed");const i=(new Date).toISOString();var s;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:o.text,message_type_id:a.custom,send_at:i,edited_at:i,reader_ids:[],unreader_ids:[],hide_ids:[],operation:c.normal,operation_user_id:"0",content:(s={client_msg_id:e.client_msg_id,content:e.content},JSON.stringify({client_msg_id:s.client_msg_id,content:JSON.stringify(s.content)})),reactions:[]})}async sendMessageToFeed(e){if(e.message_type_id===a.custom){const t=C(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 f(_.SDK_ERROR,"not support")}async sendMessageReadReceipt(e){const t=this.feedCache.get(e.feed_id);return null===t?f(_.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?i.yes:i.no});return t.ok?t.data:null}async leaveRoom(e){return await this.httpClient.post("/liveshow/leave",{room_id:e})}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 j=new Map;function H(e,t){let i=j.get(e);return void 0===i&&(i=new K(t),j.set(e,i)),i}const B={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:C};export{K as ChatSDK,H as create,g as enums,p as events,m as interfaces,B as utils};
package/dist/web-sdk.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t,i,s,n,o,r,a,l,c,d,h=require("js-cookie"),u=require("axios"),_=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"}(i||(i={})),function(e){e[e.normal=0]="normal",e[e.thread=1]="thread"}(s||(s={})),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"}(a||(a={})),function(e){e.error="ERROR",e.warning="WARNING",e.info="INFO"}(l||(l={})),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.REQUEST_SINGLETON_LOCK_FAIL=-9997]="REQUEST_SINGLETON_LOCK_FAIL",e[e.SUCCESS=0]="SUCCESS"}(c||(c={})),function(e){e[e.up=0]="up",e[e.down=1]="down"}(d||(d={}));var g=Object.freeze({__proto__:null,get Boolean(){return e},get ChatType(){return i},get FeedType(){return s},get GroupRole(){return r},get HttpClientResponseCode(){return c},get LogLevel(){return l},get MessageKind(){return n},get MessageOperation(){return a},get MessageType(){return o},get PushMessageType(){return t},get RequestDirection(){return d}});const E={SDK_READY:"sdkReady",SDK_NOT_READY:"sdkNotReady",FEED_LIST_UPDATED:"feedListUpdated",MESSAGE_RECEIVED:"messageReceived",MESSAGE_RECALLED:"messageRecalled",MESSAGE_RECEIPT_RECEIVED:"messageReceiptReceived",ROOM_MESSAGE_RECEIVED:"roomMessageReceived",SYSTEM_NOTICE_RECEIVED:"systemNoticeReceived"};var p=Object.freeze({__proto__:null,CHAT_SDK_EVENT:E}),m=Object.freeze({__proto__:null});function f(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}},C=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{}};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 i=this.all.get(e);return i?i.push(t):this.all.set(e,[t]),()=>{this.off(e,t)}}off(e,t){const i=this.all.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let i=this.all.get(e);i&&i.slice().map(e=>{e(t)}),i=this.all.get("*"),i&&i.slice().map(i=>{i(e,t)})}once(e,t){if("*"===e){const i=(e,s)=>{t(e,s),this.off("*",i)};this.on(e,i)}else{const i=s=>{t(s),this.off(e,i)};this.on(e,i)}}}class A extends T{constructor(e){super(),Object.defineProperty(this,"url",{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.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(this.url);this.ws=e,e.onopen=()=>{this.delaySendPing()},e.onerror=e=>{this.logger.info("ReConnectWebsocket error",e)},e.onmessage=e=>{try{const i=JSON.parse(e.data);if(i.type===t.PONG_MESSAGE?null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null,this.delaySendPing()):this.sendAck(i.id),i.type===t.BIG_PACKAGE_PUSH)for(const e of i.content.big_push)this.emit("message",e);else this.emit("message",i)}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 R 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(){if(null===this.context.loginUser)return void this.logger.warn("BusinessWebsocket try connect but not login");if(this.ws)return void this.logger.warn("BusinessWebsocket try connect but already connected");const e=`${this.host}/ws?token=${this.context.loginUser.sessionId}&platform=web`;this.ws=new A({url:e,logger:this.logger}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("kickoff",()=>{this.emit("kickoff")})}disconnect(){this.ws?(this.ws.destroy(),this.ws=null):this.logger.info("BusinessWebsocket already disconnected")}}class v{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,"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.waitMap=new Map,this.list=[]}getAll(){const e=[];for(const t of this.list){const i=this.map.get(t);i&&e.push(i)}return e}get(e){return this.map.get(e)??null}getByChat(e,t){let i;return i=t&&"0"!==t?this.threadMap.get(t):this.chatMap.get(e),void 0!==i?this.get(i):null}async waitFor(e){const t=this.get(e);if(t)return t;if(this.syncCompleted)return null;let i=this.waitMap.get(e);return i||(i=(()=>{let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}})(),this.waitMap.set(e,i)),await i.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);return!!t&&(this.map.delete(e),t.feed_type===s.thread?this.threadMap.delete(t.thread_id):this.chatMap.delete(t.chat_id),this.removeFromList(e),!0)}beforeSave(e){this.map.has(e.id)?this.removeFromList(e.id):e.feed_type===s.thread?this.threadMap.set(e.thread_id,e.id):this.chatMap.set(e.chat_id,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.waitMap.clear(),this.list=[]}}function y(e){return(new TextEncoder).encode(e).buffer}async function w(e,t){return window.crypto&&window.crypto.subtle?await async function(e,t){const i=y(t),s=y(e),n=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,s);return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e,t):function(e,t){return _.HmacSHA256(e,t).toString(_.enc.Hex)}(e,t)}const P=e=>{if(null==e)return"";if("object"!=typeof e||Array.isArray(e)){if(Array.isArray(e)){let t="";for(const i of e)t+=P(i);return t}return"string"==typeof e?e:String(e)}{const t=Object.keys(e).sort();let i="";for(const s of t)i+=P(e[s]);return i}};function D(){return f(c.MAKE_SIGN_FAIL,"make sign fail")}class O{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=u.create({baseURL:e.host,headers:{"x-developer":e.developer}}),this.context=e.context,this.logger=e.logger}async request(e){try{const{needSign:t=!0,...i}=e;if(i.headers||(i.headers={}),i.headers.platform="web",t&&"POST"===e.method?.toUpperCase()&&i.data){if(null===this.context.loginUser)return this.logger.warn("HttpClient needs make sign but not login"),D();try{const e=await(async(e,t)=>{const i=await P(e);return await w(i,t)})(i.data,this.context.loginUser.secretKey);i.headers.sign=e}catch(e){return this.logger.error("HttpClient make sign error",e),D()}}const s=await this.api(i),n=s.data;return n.code===c.SUCCESS?{ok:!0,data:n.data}:(this.logger.info("HttpClient server error",s),{ok:!1,code:n.code,msg:n.msg,msg_i18n:n.msg_i18n})}catch{return{ok:!1,code:c.NETWORK_ERROR,msg:"network error"}}}get(e,t,i){return this.request({url:e,method:"GET",params:t,...i})}post(e,t,i){return this.request({url:e,method:"POST",data:t,...i})}}function L(e){return`${e}`.padStart(2,"0")}class M{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=l.error,this.logHandler=this.createLogHandler()}getPriority(e){switch(e){case l.error:return 3;case l.warning:return 2;case l.info:return 1;default:return 0}}createLogHandler(){return(e,...t)=>{const i=new Date,s=`TypeX >> [${`${i.getFullYear()}-${L(i.getMonth()+1)}-${L(i.getDate())} ${L(i.getHours())}:${L(i.getMinutes())}:${L(i.getSeconds())}.${i.getMilliseconds()}`}]`;switch(e){case l.error:console.error(s,"[ERR]",...t);break;case l.warning:console.warn(s,"[WARN]",...t);break;case l.info:console.info(s,"[INFO]",...t);break;default:console.log(s,...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(l.info,...e)}warn(...e){this.log(l.warning,...e)}error(...e){this.log(l.error,...e)}}class I{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(E.FEED_LIST_UPDATED,{list:this.feedCache.getAll(),is_sync_completed:this.feedCache.isSyncCompleted()})}processCreateFeed(e){this.feedCache.unshift(e.content),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,s=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null===s)return;let o=!1;const r={};if(i.message_kind_id!==n.system&&i.sender_id!==t){o=!0;const e=new Set(s.unread_message_ids);e.add(i.id),r.unread_message_ids=[...e],r.badge=e.size}s.last_message_position<i.position&&(o=!0,r.last_message_id=i.id,r.last_message_position=i.position,r.last_message_sender_id=i.sender_id,r.last_message_send_at=i.send_at,r.last_message_kind_id=i.message_kind_id,r.last_message_type_id=i.message_type_id,r.last_message=i.content,r.last_message_operation=i.operation,r.last_message_operation_user_id=i.operation_user_id),o&&(this.feedCache.unshift({...s,...r}),this.emitFeedListUpdated()),this.emitter.emit(E.MESSAGE_RECEIVED,{feed_id:s.id,message:i})}processUpdateMessage(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==i&&null!=t.operation){let e=!1;const s={};if(t.operation===a.recall){if(null!=i.unread_message_ids&&i.unread_message_ids.includes(t.id)){e=!0;const n=new Set(i.unread_message_ids);n.delete(t.id),s.unread_message_ids=[...n],s.badge=s.unread_message_ids.length}i.last_message_id===t.id&&(e=!0,s.last_message=t.content??"{}",s.last_message_operation=t.operation,s.last_message_operation_user_id=t.operation_user_id??"0")}e&&(this.feedCache.unshift({...i,...s}),this.emitFeedListUpdated()),t.operation===a.recall&&this.emitter.emit(E.MESSAGE_RECALLED,{message_ids:[t.id]})}}processPushLiveMessage(e){this.emitter.emit(E.ROOM_MESSAGE_RECEIVED,{content:e.content})}processPushSystemNotice(e){this.emitter.emit(E.SYSTEM_NOTICE_RECEIVED,{content:e.content})}processReadMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,i=e.content,s=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null===s)return;let n=!1;const o={};if(i.reader_ids.includes(t)&&i.message_ids.length>0){n=!0;const e=new Set(s.unread_message_ids);i.message_ids.forEach(t=>{e.delete(t)}),o.unread_message_ids=[...e],o.badge=e.size}n&&(this.feedCache.update({...s,...o}),this.emitFeedListUpdated()),this.emitter.emit(E.MESSAGE_RECEIPT_RECEIVED,{feed_id:s.id,message_ids:i.message_ids,reader_user_ids:i.reader_ids})}processKickOutDevice(){this.handleKickoff()}process(e){switch(this.logger.info("PushMessageProcessor process",e),e.type){case t.CREATE_FEED:this.processCreateFeed(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.PUSH_LIVE_MESSAGE:this.processPushLiveMessage(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()}}}class U{constructor(){Object.defineProperty(this,"obtained",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortLockObtain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.obtained=!1,this.abortLockObtain=null}async requestLock(){if(this.obtained)return!0;let e=()=>{};const t=new Promise(t=>{e=t}),i=new Promise(e=>{this.abortLockObtain=e});navigator.locks.request("typex-sdk",{ifAvailable:!0},async t=>{t?(this.obtained=!0,e(!0),await i):e(!1)});return await t}releaseLock(){this.obtained=!1,null!==this.abortLockObtain&&(this.abortLockObtain(),this.abortLockObtain=null)}}class k{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(k,"key",{enumerable:!0,configurable:!0,writable:!0,value:"__typex_sdk_data__"});class x{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 N 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,"singletonLock",{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}),this.context={isLogin:!1,loginUser:null,isReady:!1,deviceId:null},this.version=new x,this.singletonLock=new U,this.logger=new M,this.httpClient=new O({host:e.httpHost,context:this.context,logger:this.logger,developer:e.developer}),this.feedCache=new v,this.ws=new R({host:e.websocketHost,context:this.context,logger:this.logger}),this.pushMessageProcessor=new I({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()})}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;k.set({deviceId:e.deviceId})}loadContext(){const e=k.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(E.SDK_READY)):(this.ws.disconnect(),this.feedCache.reset(),this.singletonLock.releaseLock(),this.context.isReady=!1,this.emit(E.SDK_NOT_READY))}async loadFeedList(){const e=this.version.get(),t={refresh_at:null,feed_id:null};for(;;){const i=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(!i.ok)break;if(t.refresh_at=i.data.refresh_at,t.feed_id=i.data.last_feed_id,(i.data.feed_list??[]).forEach(e=>{this.feedCache.push(e)}),!i.data.has_more)break}this.version.check(e)&&(this.feedCache.markSyncComplete(),this.emit(E.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.singletonLock.requestLock())return this.logger.error("Another active TypeX SDK instance detected"),f(c.REQUEST_SINGLETON_LOCK_FAIL,"Another active TypeX SDK instance detected");if(await this.requestDeviceId(),!this.context.deviceId)return this.logger.error("Get deviceId failed"),f(c.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 this.singletonLock.releaseLock(),t;const i=h.get("sessionid");return i?(this.context.isLogin=!0,this.context.loginUser={userId:t.data.id,secretKey:t.data.key,sessionId:i},this.applyLoginStatus(),b(null)):(this.singletonLock.releaseLock(),f(c.SDK_ERROR,"Get sessionId failed"))}async logout(){if(!this.context.isLogin)return b(null);const e=await this.httpClient.get("/user/logout");return e.ok?(this.afterLogout(),b(null)):e}async afterLogout(){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 getFeedMessageList(e){const t=await this.getFeedDetail(e.feed_id);if(t.ok&&t.data){const i=t.data,{chat_id:s,first_position:n,last_message_position:o}=i,{positions:r,nextPosition:a,hasMore:l}=(e=>{const t=[];if(e.direction===d.up){let i=e.startPosition??e.maxPosition;for(;t.length<e.limit&&i>=e.minPosition;)t.push(i),i--;const s=i>=e.minPosition;let n;return s&&(n=i),{positions:t,nextPosition:n,hasMore:s}}{let i=e.startPosition??e.minPosition;for(;t.length<e.limit&&i<=e.maxPosition;)t.push(i),i++;const s=i<=e.maxPosition;let n;return s&&(n=i),{positions:t,nextPosition:n,hasMore:s}}})({maxPosition:o,minPosition:n,startPosition:e.message_position,limit:e.limit,direction:e.direction??d.up});if(r.length>0){const e=await this.httpClient.post("/message/get_by_position",{chat_position:{[s]:r}},{needSign:!1});if(e.ok&&e.data[s]){return b({has_more:l,list:e.data[s].reverse(),next_message_position:a})}}}return b({has_more:!1,list:[]})}createCustomMessage(e){if(null===this.context.loginUser)return f(c.SDK_ERROR,"not login");const t=this.feedCache.get(e.feed_id);if(null===t)return f(c.SDK_ERROR,"not found feed");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:(new Date).toISOString(),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)}))})}async sendMessageToFeed(e){if(e.message_type_id===o.custom){const t=C(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 f(c.SDK_ERROR,"not support")}async sendMessageReadReceipt(e){const t=this.feedCache.get(e.feed_id);return null===t?f(c.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 leaveRoom(e){return await this.httpClient.post("/liveshow/leave",{room_id:e})}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 G=new Map;const F={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:C};exports.ChatSDK=N,exports.create=function(e,t){let i=G.get(e);return void 0===i&&(i=new N(t),G.set(e,i)),i},exports.enums=g,exports.events=p,exports.interfaces=m,exports.utils=F;
1
+ "use strict";var e,t,i,s,n,r,o,a,d=require("axios"),c=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"}(i||(i={})),function(e){e[e.normal=0]="normal",e[e.thread=1]="thread"}(s||(s={})),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"}(r||(r={})),function(e){e[e.Owner=1]="Owner",e[e.Admin=2]="Admin",e[e.Common=3]="Common",e[e.Bot=4]="Bot"}(o||(o={})),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 l=["api-coco.typex.im","api-tx.typex-test.cn"];var h,_,u;!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.REQUEST_SINGLETON_LOCK_FAIL=-9997]="REQUEST_SINGLETON_LOCK_FAIL",e[e.SUCCESS=0]="SUCCESS"}(_||(_={})),function(e){e[e.up=0]="up",e[e.down=1]="down"}(u||(u={}));var g=Object.freeze({__proto__:null,get Bool(){return e},get ChatType(){return i},get FeedType(){return s},get GroupRole(){return o},get HttpClientResponseCode(){return _},get LogLevel(){return h},get MessageKind(){return n},get MessageOperation(){return a},get MessageType(){return r},get PushMessageType(){return t},RESOURCE_AUTH_DOMAINS:l,get RequestDirection(){return u}});const E={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",ROOM_MESSAGE_RECEIVED:"roomMessageReceived",SYSTEM_NOTICE_RECEIVED:"systemNoticeReceived"};var p=Object.freeze({__proto__:null,CHAT_SDK_EVENT:E}),m=Object.freeze({__proto__:null});function f(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}},C=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{}},T=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),A=e=>new RegExp(`https?:\\\\?/\\\\?/${T(e)}(?:\\\\.|[^"\\\\\\s])*`,"g"),y=(e,t,i)=>{if(!e||"string"!=typeof e)return e;const s=A(t);return e.replace(s,e=>{const t=(e=>{try{return JSON.parse(`"${e}"`)}catch{return e}})(e),s=i(t);return"string"!=typeof s||s===t?e:(n=s,JSON.stringify(n).slice(1,-1));var n})};class R{constructor(e){Object.defineProperty(this,"all",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.all=e||new Map}on(e,t){const i=this.all.get(e);return i?i.push(t):this.all.set(e,[t]),()=>{this.off(e,t)}}off(e,t){const i=this.all.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let i=this.all.get(e);i&&i.slice().map(e=>{e(t)}),i=this.all.get("*"),i&&i.slice().map(i=>{i(e,t)})}once(e,t){if("*"===e){const i=(e,s)=>{t(e,s),this.off("*",i)};this.on(e,i)}else{const i=s=>{t(s),this.off(e,i)};this.on(e,i)}}}class D extends R{constructor(e){super(),Object.defineProperty(this,"url",{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.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(this.url);this.ws=e,e.onopen=()=>{this.delaySendPing()},e.onerror=e=>{this.logger.info("ReConnectWebsocket error",e)},e.onmessage=e=>{try{const i=JSON.parse(e.data);if(i.type===t.PONG_MESSAGE?null!==this.pongTimeout&&(clearTimeout(this.pongTimeout),this.pongTimeout=null,this.delaySendPing()):this.sendAck(i.id),i.type===t.BIG_PACKAGE_PUSH)for(const e of i.content.big_push)this.emit("message",e);else this.emit("message",i)}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 v extends R{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(){if(null===this.context.loginUser)return void this.logger.warn("BusinessWebsocket try connect but not login");if(this.ws)return void this.logger.warn("BusinessWebsocket try connect but already connected");const e=`${this.host}/ws?token=${this.context.loginUser.sessionId}&platform=web`;this.ws=new D({url:e,logger:this.logger}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("kickoff",()=>{this.emit("kickoff")})}disconnect(){this.ws?(this.ws.destroy(),this.ws=null):this.logger.info("BusinessWebsocket already disconnected")}}class w{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 i=this.map.get(t);i&&e.push(i)}return e}get(e){return this.map.get(e)??null}getByChat(e,t){let i;return i=t&&"0"!==t?this.threadMap.get(t):this.chatMap.get(e),void 0!==i?this.get(i):null}getByTargetId(e){const t=this.targetMap.get(e);if(void 0===t)return[];const i=[];for(const e of t){const t=this.get(e);null!==t&&i.push(t)}return i}async waitFor(e){const t=this.get(e);if(t)return t;if(this.syncCompleted)return null;let i=this.waitMap.get(e);return i||(i=(()=>{let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}})(),this.waitMap.set(e,i)),await i.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===s.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===s.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 P(e,t){return window.crypto&&window.crypto.subtle?await async function(e,t){const i=O(t),s=O(e),n=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("HMAC",n,s);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e,t):function(e,t){return c.HmacSHA256(e,t).toString(c.enc.Hex)}(e,t)}const M=e=>{if(null==e)return"";if("object"!=typeof e||Array.isArray(e)){if(Array.isArray(e)){let t="";for(const i of e)t+=M(i);return t}return"string"==typeof e?e:String(e)}{const t=Object.keys(e).sort();let i="";for(const s of t)i+=M(e[s]);return i}};function L(){return f(_.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,...i}=e;if(i.headers||(i.headers={}),i.headers.platform="web",t&&"POST"===e.method?.toUpperCase()&&i.data){if(null===this.context.loginUser)return this.logger.warn("HttpClient needs make sign but not login"),L();try{const e=await(async(e,t)=>{const i=await M(e);return await P(i,t)})(i.data,this.context.loginUser.secretKey);i.headers.sign=e}catch(e){return this.logger.error("HttpClient make sign error",e),L()}}this.context.loginUser&&(i.headers["X-Sid"]=this.context.loginUser.sessionId);const s=await this.api(i),n=s.data;return n.code===_.SUCCESS?{ok:!0,data:n.data}:(this.logger.info("HttpClient server error",s),{ok:!1,code:n.code,msg:n.msg,msg_i18n:n.msg_i18n})}catch{return{ok:!1,code:_.NETWORK_ERROR,msg:"network error"}}}get(e,t,i){return this.request({url:e,method:"GET",params:t,...i})}post(e,t,i){return this.request({url:e,method:"POST",data:t,...i})}}function I(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 i=new Date,s=`TypeX >> [${`${i.getFullYear()}-${I(i.getMonth()+1)}-${I(i.getDate())} ${I(i.getHours())}:${I(i.getMinutes())}:${I(i.getSeconds())}.${i.getMilliseconds()}`}]`;switch(e){case h.error:console.error(s,"[ERR]",...t);break;case h.warning:console.warn(s,"[WARN]",...t);break;case h.info:console.info(s,"[INFO]",...t);break;default:console.log(s,...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(E.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,i=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===i)return;const s={...i,...t};this.feedCache.update(s),this.emitFeedListUpdated()}processDeleteFeed(e){this.feedCache.remove(e.content.id)&&this.emitFeedListUpdated()}processAddMessage(t){if(null===this.context.loginUser)return;const i=this.context.loginUser.userId,s=t.content;if(s.hide_ids.includes(i))return;const r=this.feedCache.getByChat(s.chat_id,s.thread_id);if(null!==r){if(s.no_last_msg!==e.yes){let t=!1,o=!1;const a={};if(s.message_kind_id!==n.system&&s.sender_id!==i&&s.no_read!==e.yes){t=!0;const e=new Set(r.unread_message_ids);e.add(s.id),a.unread_message_ids=[...e],a.badge=e.size}if(r.last_message_position<s.position&&(t=!0,o=!0,a.last_message_id=s.id,a.last_message_position=s.position,a.last_message_sender_id=s.sender_id,a.last_message_send_at=s.send_at,a.last_message_kind_id=s.message_kind_id,a.last_message_type_id=s.message_type_id,a.last_message=s.content,a.last_message_operation=s.operation,a.last_message_operation_user_id=s.operation_user_id),t){const e={...r,...a};o?this.feedCache.unshift(e):this.feedCache.update(e),this.emitFeedListUpdated()}}this.emitter.emit(E.MESSAGE_RECEIVED,{feed_id:r.id,message:s})}}processUpdateMessage(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null!==i&&null!=t.operation){let e=!1;const s={};if(t.operation===a.recall||t.operation===a.destroy){if(null!=i.unread_message_ids&&i.unread_message_ids.includes(t.id)){e=!0;const n=new Set(i.unread_message_ids);n.delete(t.id),s.unread_message_ids=[...n],s.badge=s.unread_message_ids.length}i.last_message_id===t.id&&(e=!0,s.last_message=t.content??"{}",s.last_message_operation=t.operation,s.last_message_operation_user_id=t.operation_user_id??"0")}else t.operation===a.edit&&i.last_message_id===t.id&&(e=!0,s.last_message_kind_id=t.message_kind_id,s.last_message_type_id=t.message_type_id,s.last_message=t.content,s.last_message_operation=t.operation,s.last_message_operation_user_id=t.operation_user_id);e&&(this.feedCache.update({...i,...s}),this.emitFeedListUpdated()),t.operation===a.recall?this.emitter.emit(E.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(E.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(E.MESSAGE_DESTROYED,{feed_id:i.id,message_ids:[t.id]})}}processDeleteMessage(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,t.thread_id);if(null===i)return;let s=!1;const n={};i.last_message_id===t.id&&(s=!0,n.last_message=t.content??"{}",n.last_message_operation=t.operation,n.last_message_operation_user_id=t.operation_user_id??"0"),s&&(this.feedCache.update({...i,...n}),this.emitFeedListUpdated()),this.emitter.emit(E.MESSAGE_DESTROYED,{feed_id:i.id,message_ids:[t.id]})}processPushLiveMessage(e){this.emitter.emit(E.ROOM_MESSAGE_RECEIVED,{room_id:e.content.room_id,content:e.content.message})}processPushSystemNotice(e){this.emitter.emit(E.SYSTEM_NOTICE_RECEIVED,{content:e.content})}processReadMessage(e){if(null===this.context.loginUser)return;const t=this.context.loginUser.userId,i=e.content,s=this.feedCache.getByChat(i.chat_id,i.thread_id);if(null===s)return;let n=!1;const r={};if(i.reader_ids.includes(t)&&i.message_ids.length>0){n=!0;const e=new Set(s.unread_message_ids);i.message_ids.forEach(t=>{e.delete(t)}),r.unread_message_ids=[...e],r.badge=e.size}n&&(this.feedCache.update({...s,...r}),this.emitFeedListUpdated()),this.emitter.emit(E.MESSAGE_RECEIPT_RECEIVED,{feed_id:s.id,message_ids:i.message_ids,reader_user_ids:i.reader_ids})}processKickOutDevice(){this.handleKickoff()}processGroupMember(e){const i=e.content,s=this.feedCache.getByChat(i.chat_id,"0");if(null===s)return;const n=new Set(s.chat_member),r=e.type===t.ADD_GROUP_MEMBER,o=e.type===t.DEL_GROUP_MEMBER;i.chat_member.forEach(e=>{r?n.add(e.chat_id):o&&n.delete(e.chat_id)}),this.feedCache.update({...s,chat_member:[...n]}),this.emitFeedListUpdated()}processUpdateGroup(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,"0");if(null===i)return;let s=!1;const n={};null!=t.avatar&&(s=!0,n.avatar=t.avatar),null!=t.name&&(s=!0,n.name=t.name),s&&(this.feedCache.update({...i,...n}),this.emitFeedListUpdated())}processUpdateUserData(e){const t=e.content,i=this.feedCache.getByTargetId(t.id);if(i.length>0){const e={};if(null!=t.avatar&&(e.avatar=t.avatar),null!=t.first_name||null!=t.last_name){let i=t.first_name??"";null!=t.last_name&&(i=i.length>0?`${i} ${t.last_name}`:t.last_name),e.name=i}for(const t of i)this.feedCache.update({...t,...e});this.emitFeedListUpdated()}}processUpdateMessageReaction(e){const t=e.content,i=this.feedCache.getByChat(t.chat_id,t.thread_id);null!==i&&this.emitter.emit(E.MESSAGE_REACTION_UPDATED,{feed_id:i.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.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 x{constructor(){Object.defineProperty(this,"obtained",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortLockObtain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.obtained=!1,this.abortLockObtain=null}async requestLock(){if(this.obtained)return!0;let e=()=>{};const t=new Promise(t=>{e=t}),i=new Promise(e=>{this.abortLockObtain=e});navigator.locks.request("typex-sdk",{ifAvailable:!0},async t=>{t?(this.obtained=!0,e(!0),await i):e(!1)});return await t}releaseLock(){this.obtained=!1,null!==this.abortLockObtain&&(this.abortLockObtain(),this.abortLockObtain=null)}}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__"});class F{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 K extends R{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,"singletonLock",{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}),this.context={isLogin:!1,loginUser:null,isReady:!1,deviceId:null},this.version=new F,this.singletonLock=new x,this.logger=new k,this.httpClient=new U({host:e.httpHost,context:this.context,logger:this.logger,developer:e.developer}),this.feedCache=new w,this.ws=new v({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()})}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(E.SDK_READY)):(this.ws.disconnect(),this.feedCache.reset(),this.singletonLock.releaseLock(),this.context.isReady=!1,this.emit(E.SDK_NOT_READY))}async loadFeedList(){const e=this.version.get(),t={refresh_at:null,feed_id:null};for(;;){const i=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(!i.ok||null===i.data)break;if(t.refresh_at=i.data.refresh_at,t.feed_id=i.data.last_feed_id,(i.data.feed_list??[]).forEach(e=>{this.feedCache.push(e)}),!i.data.has_more)break}this.version.check(e)&&(this.feedCache.markSyncComplete(),this.emit(E.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.singletonLock.requestLock())return this.logger.error("Another active TypeX SDK instance detected"),f(_.REQUEST_SINGLETON_LOCK_FAIL,"Another active TypeX SDK instance detected");if(await this.requestDeviceId(),!this.context.deviceId)return this.logger.error("Get deviceId failed"),f(_.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});return t.ok?(this.context.isLogin=!0,this.context.loginUser={userId:t.data.id,secretKey:t.data.key,sessionId:e.user_code},this.applyLoginStatus(),b(null)):(this.singletonLock.releaseLock(),t)}async logout(){if(!this.context.isLogin)return b(null);const e=await this.httpClient.get("/user/logout");return e.ok?(this.afterLogout(),b(null)):e}async afterLogout(){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([])}getDomain(e){const[t,i]=l,s=A(t),n=A(i);for(const r of e){if(s.test(r.content))return t;if(n.test(r.content))return i}}appendXsid(e){if(!this.context.loginUser?.sessionId)return e;const t=this.context.loginUser.sessionId,i=this.getDomain(e);return i?e.map(e=>{const s=y(e.content,i,e=>((e,t,i)=>{const s=encodeURIComponent(t),n=encodeURIComponent(i),r=e.indexOf("#"),o=r>=0?e.slice(0,r):e,a=r>=0?e.slice(r):"",d=new RegExp(`([?&])${T(s)}=[^&#]*`);if(d.test(o))return o.replace(d,`$1${s}=${n}`)+a;const c=o.includes("?")?"&":"?";return`${o}${c}${s}=${n}${a}`})(e,"xsid",t));return{...e,content:s}}):e}async markFeedMessageAsRead(t){const i=this.feedCache.get(t);if(!i)return b(!1);if(!(await this.httpClient.post("/feed/update",{id:i.id,mark_unread:e.yes})).ok)return b(!1);return(await this.httpClient.post("/message/read",{chat_id:i.chat_id,thread_id:i.thread_id})).ok?b(!0):b(!1)}async getMessagesByIds(e,t){const i=this.feedCache.get(e);if(!i||!Array.isArray(t)||0===t.length)return b([]);const s=await this.httpClient.post("/message/get_by_msgid",{chat_msg_id_map:{[i.chat_id]:t}});if(s.ok){return b(this.appendXsid(s.data[i.chat_id]))}return b([])}async getFeedMessageList(e){const t=await this.getFeedDetail(e.feed_id);if(t.ok&&t.data){const i=t.data,{chat_id:s,first_position:n,last_message_position:r}=i,{positions:o,nextPosition:a,hasMore:d}=(e=>{const t=[];if(e.direction===u.up){let i=e.startPosition??e.maxPosition;for(;t.length<e.limit&&i>=e.minPosition;)t.push(i),i--;const s=i>=e.minPosition;let n;return s&&(n=i),{positions:t,nextPosition:n,hasMore:s}}{let i=e.startPosition??e.minPosition;for(;t.length<e.limit&&i<=e.maxPosition;)t.push(i),i++;const s=i<=e.maxPosition;let n;return s&&(n=i),{positions:t,nextPosition:n,hasMore:s}}})({maxPosition:r,minPosition:n,startPosition:e.message_position,limit:e.limit,direction:e.direction??u.up});if(o.length>0){const e=await this.httpClient.post("/message/get_by_position",{chat_position:{[s]:o}},{needSign:!1});if(e.ok&&e.data[s]){return b({has_more:d,list:this.appendXsid(e.data[s].reverse()),next_message_position:a})}}}return b({has_more:!1,list:[]})}createCustomMessage(e){if(null===this.context.loginUser)return f(_.SDK_ERROR,"not login");const t=this.feedCache.get(e.feed_id);if(null===t)return f(_.SDK_ERROR,"not found feed");const i=(new Date).toISOString();var s;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:r.custom,send_at:i,edited_at:i,reader_ids:[],unreader_ids:[],hide_ids:[],operation:a.normal,operation_user_id:"0",content:(s={client_msg_id:e.client_msg_id,content:e.content},JSON.stringify({client_msg_id:s.client_msg_id,content:JSON.stringify(s.content)})),reactions:[]})}async sendMessageToFeed(e){if(e.message_type_id===r.custom){const t=C(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 f(_.SDK_ERROR,"not support")}async sendMessageReadReceipt(e){const t=this.feedCache.get(e.feed_id);return null===t?f(_.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 i=await this.httpClient.post("/feed/update",{id:t.feedId,is_mute:t.isMute?e.yes:e.no});return i.ok?i.data:null}async leaveRoom(e){return await this.httpClient.post("/liveshow/leave",{room_id:e})}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 j=new Map;const H={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:C};exports.ChatSDK=K,exports.create=function(e,t){let i=j.get(e);return void 0===i&&(i=new K(t),j.set(e,i)),i},exports.enums=g,exports.events=p,exports.interfaces=m,exports.utils=H;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typexim/web-sdk",
3
- "version": "0.0.4-alpha.9",
3
+ "version": "0.0.5-alpha.10",
4
4
  "private": false,
5
5
  "repository": "git@github.com:secure-typex/typex-web-sdk.git",
6
6
  "license": "MIT",
@@ -26,14 +26,12 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "axios": "1.11.0",
29
- "crypto-js": "4.2.0",
30
- "js-cookie": "3.0.5"
29
+ "crypto-js": "4.2.0"
31
30
  },
32
31
  "devDependencies": {
33
32
  "@rollup/plugin-terser": "0.4.4",
34
33
  "@rollup/plugin-typescript": "12.1.4",
35
34
  "@types/crypto-js": "4.2.2",
36
- "@types/js-cookie": "3.0.6",
37
35
  "cross-env": "10.0.0",
38
36
  "rollup": "4.50.1",
39
37
  "rollup-plugin-delete": "3.0.1"
package/rollup.config.js CHANGED
@@ -33,7 +33,7 @@ function createConfig() {
33
33
  }),
34
34
  IS_BUILD && terser(),
35
35
  ].filter(Boolean),
36
- external: ['js-cookie', 'axios', 'crypto-js'],
36
+ external: ['axios', 'crypto-js'],
37
37
  };
38
38
  }
39
39