easemob-websdk 5.1.2 → 5.1.3
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/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-manager.d.ts +11 -3
- package/cache/cache-types.d.ts +13 -2
- package/chat-client.d.ts +6 -0
- package/chunks/{chat-manager-BFd2Z4oY.cjs → chat-manager-BI-6bEor.cjs} +1 -1
- package/chunks/{chat-manager-CId_M_e5.js → chat-manager-nXOTpJ01.js} +2 -2
- package/chunks/{common-BvlDAw4a.js → common-DHQukb7J.js} +1 -1
- package/chunks/{event-system-B62vbKqG.js → event-system-DguqwFpc.js} +1 -1
- package/chunks/{group-user-info-resolver-DMccCqez.js → group-user-info-resolver-D6AQAHEE.js} +1 -1
- package/chunks/{index-BBFJYOM8.js → index-CneY58NJ.js} +1 -1
- package/chunks/index-DxjmfFL7.js +1 -0
- package/chunks/push-manager-CSIKhoPe.js +1 -0
- package/chunks/push-manager-D7RDsKuv.cjs +1 -0
- package/chunks/session-list-query-C3iQvQxK.cjs +1 -0
- package/chunks/session-list-query-Cdpiw_IZ.js +1 -0
- package/chunks/{user-info-AlshAvdy.js → user-info-7QzMa7bR.js} +1 -1
- package/core/session-list-sync/session-list-message-events.d.ts +9 -0
- package/index.cjs +1 -1
- package/index.js +2 -2
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-thread/index.js +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.js +1 -1
- package/managers/user-info/index.js +1 -1
- package/message/message-snapshot.d.ts +8 -0
- package/package.json +1 -1
- package/protocol/msync/codec.d.ts +1 -21
- package/protocol/msync/message-identity.d.ts +2 -0
- package/protocol/msync/message-payload-decoder.d.ts +35 -0
- package/protocol/session-list/gateway.d.ts +8 -1
- package/protocol/session-list/payload-decoder.d.ts +12 -0
- package/types/conversation.d.ts +27 -20
- package/utils/session-message-recipient.d.ts +11 -0
- package/chunks/index-l_BUKi77.js +0 -1
- package/chunks/session-list-query-Cvr6rlme.js +0 -1
- package/chunks/session-list-query-Dslj2k3t.cjs +0 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Message, MessageBody } from '../types';
|
|
2
|
+
import type { MessageProfileVersionSidecar } from '../core/message/profile-sync/profile-version-sidecar';
|
|
3
|
+
/** @internal Validated serializable fields shared by realtime projections and both cache formats. */
|
|
4
|
+
export declare const projectMessageMetadata: (value: unknown) => Omit<Partial<Message>, "body"> & MessageProfileVersionSidecar;
|
|
5
|
+
/** @internal Stable comparison for message snapshots; object key order has no business meaning. */
|
|
6
|
+
export declare const messageSnapshotSignature: (value: unknown) => string;
|
|
7
|
+
/** @internal A shallow serializable body projection without expanding combined-message details. */
|
|
8
|
+
export declare const projectMessageBody: (body: MessageBody | Record<string, unknown>) => Record<string, unknown>;
|
package/package.json
CHANGED
|
@@ -55,7 +55,7 @@ export declare class MsyncCodec {
|
|
|
55
55
|
private compressionFailureCount;
|
|
56
56
|
private readonly maxCompressionFailures;
|
|
57
57
|
private useReplacedMessageContents;
|
|
58
|
-
private readonly
|
|
58
|
+
private readonly payloadDecoder;
|
|
59
59
|
constructor(options: MsyncContextOptions);
|
|
60
60
|
updateToken(token: string): void;
|
|
61
61
|
updateResource(resource: string | undefined): void;
|
|
@@ -152,9 +152,6 @@ export declare class MsyncCodec {
|
|
|
152
152
|
private resolveProfileVersionTime;
|
|
153
153
|
private isPublicMessageType;
|
|
154
154
|
private resolveMessageIsOnline;
|
|
155
|
-
private decodeStreamMeta;
|
|
156
|
-
private mapStreamStatus;
|
|
157
|
-
private resolveContentText;
|
|
158
155
|
private buildContent;
|
|
159
156
|
private decodeContent;
|
|
160
157
|
private resolveChatType;
|
|
@@ -171,23 +168,6 @@ export declare class MsyncCodec {
|
|
|
171
168
|
private resolveRouteType;
|
|
172
169
|
private resolveBroadcast;
|
|
173
170
|
private resolvePriority;
|
|
174
|
-
private resolveContentReplaced;
|
|
175
|
-
private resolveMessageMetaPayload;
|
|
176
|
-
private resolvePeerRead;
|
|
177
|
-
private resolveGroupReadCount;
|
|
178
|
-
private resolveModifiedInfo;
|
|
179
|
-
private resolveChatThreadMessageContext;
|
|
180
|
-
private resolveChatThreadOverview;
|
|
181
|
-
private resolveChatThreadOverviewLastMessage;
|
|
182
|
-
private resolveThreadLastMessagePayload;
|
|
183
|
-
private mapThreadMessageType;
|
|
184
|
-
private normalizeThreadLastMessageBody;
|
|
185
|
-
private readString;
|
|
186
|
-
private numberField;
|
|
187
|
-
private parseMetaPayload;
|
|
188
|
-
private toFiniteNumber;
|
|
189
|
-
private resolveReactions;
|
|
190
|
-
private normalizeMetaPayload;
|
|
191
171
|
private mapPriorityToTag;
|
|
192
172
|
private getRequestedCompressTypes;
|
|
193
173
|
private configureCompression;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Message, MessageBody, MessageModifiedInfo, StreamMessageMeta, StreamMessageStatus } from '../../types';
|
|
2
|
+
import type { ChatConversationType } from '../../types/chat-manager';
|
|
3
|
+
import type { ChatThreadMessageContext, ChatThreadOverview } from '../../types/chat-thread';
|
|
4
|
+
export declare const readMessageContent: (body: Record<string, unknown>) => Record<string, unknown> | undefined;
|
|
5
|
+
/** @internal Shared message payload mapping for realtime and session-list protocols. */
|
|
6
|
+
export declare class MessagePayloadDecoder {
|
|
7
|
+
private readonly userId;
|
|
8
|
+
private readonly useCustomAttachmentUpload;
|
|
9
|
+
constructor(userId: string, useCustomAttachmentUpload?: boolean);
|
|
10
|
+
decodeMetadata(body: Record<string, unknown>, conversationType: ChatConversationType, direct: Message['direct'], fallbackMeta?: unknown): Omit<Partial<Message>, 'body'>;
|
|
11
|
+
decodeContent(content: Record<string, unknown>): {
|
|
12
|
+
type: Message['type'];
|
|
13
|
+
body: MessageBody;
|
|
14
|
+
} | null;
|
|
15
|
+
decodeStreamMeta(rawStream: unknown, content: Record<string, unknown> | undefined): StreamMessageMeta | undefined;
|
|
16
|
+
mapStreamStatus(rawStatus: number, errorType: number): StreamMessageStatus;
|
|
17
|
+
resolveContentText(content: Record<string, unknown> | undefined): string;
|
|
18
|
+
resolveContentReplaced(metaPayload: unknown): boolean | undefined;
|
|
19
|
+
resolveMessageMetaPayload(primaryPayload: unknown, fallbackPayload: unknown): unknown;
|
|
20
|
+
resolvePeerRead(metaPayload: unknown, conversationType: ChatConversationType, direct: Message['direct']): boolean | undefined;
|
|
21
|
+
resolveGroupReadCount(metaPayload: unknown, conversationType: ChatConversationType): number | undefined;
|
|
22
|
+
resolveModifiedInfo(metaPayload: unknown): MessageModifiedInfo | undefined;
|
|
23
|
+
resolveChatThreadMessageContext(metaPayload: unknown): ChatThreadMessageContext | undefined;
|
|
24
|
+
resolveChatThreadOverview(metaPayload: unknown): ChatThreadOverview | undefined;
|
|
25
|
+
resolveChatThreadOverviewLastMessage(rawLastMessage: unknown, chatThreadId: string): ChatThreadOverview['lastMessage'] | undefined;
|
|
26
|
+
resolveThreadLastMessagePayload(rawLastMessage: Record<string, unknown>): Record<string, unknown> | null;
|
|
27
|
+
mapThreadMessageType(rawType: string | undefined): Message['type'];
|
|
28
|
+
normalizeThreadLastMessageBody(type: Message['type'], firstBody: Record<string, unknown> | null, rawLastMessage: Record<string, unknown>): MessageBody;
|
|
29
|
+
readString(value: unknown): string | undefined;
|
|
30
|
+
numberField<Key extends string>(key: Key, value: unknown): Record<Key, number> | object;
|
|
31
|
+
parseMetaPayload(metaPayload: unknown): Record<string, unknown> | null;
|
|
32
|
+
toFiniteNumber(value: unknown): number | undefined;
|
|
33
|
+
resolveReactions(metaPayload: unknown): Message['reactions'];
|
|
34
|
+
normalizeMetaPayload(payload: unknown): Uint8Array | null;
|
|
35
|
+
}
|
|
@@ -14,6 +14,13 @@ export declare const toSessionMessageSnippet: (meta: SessionListMeta | undefined
|
|
|
14
14
|
readonly conversationId: string;
|
|
15
15
|
readonly conversationType: ConversationItem["conversationType"];
|
|
16
16
|
readonly currentUserId: string;
|
|
17
|
+
readonly ext?: Record<string, unknown>;
|
|
18
|
+
readonly payload?: Record<string, unknown> | null;
|
|
19
|
+
readonly useCustomAttachmentUpload?: boolean;
|
|
20
|
+
readonly org: string;
|
|
21
|
+
readonly app: string;
|
|
17
22
|
readonly singleChatPeerDisplay?: Pick<ConversationItem, "conversationName" | "conversationAvatar">;
|
|
18
23
|
}) => SessionMessageSnippet | null;
|
|
19
|
-
export declare const toSessionListItems: (response: SessionListResponse, currentUserId: string
|
|
24
|
+
export declare const toSessionListItems: (response: SessionListResponse, currentUserId: string, org: string, app: string, options?: {
|
|
25
|
+
readonly useCustomAttachmentUpload?: boolean;
|
|
26
|
+
}) => ReadonlyArray<ConversationItem>;
|
|
@@ -1 +1,13 @@
|
|
|
1
|
+
import type { SessionMessageSnippet } from '../../types/conversation';
|
|
2
|
+
export declare const decodeSessionListPayload: (payload?: Uint8Array) => {
|
|
3
|
+
readonly body: Record<string, unknown>;
|
|
4
|
+
readonly ext: Record<string, unknown>;
|
|
5
|
+
};
|
|
6
|
+
export declare const decodeSessionListPayloadRecord: (payload?: Uint8Array) => Record<string, unknown> | null;
|
|
7
|
+
export declare const mapSessionListPayload: (decoded: Record<string, unknown> | null, options: {
|
|
8
|
+
readonly currentUserId: string;
|
|
9
|
+
readonly conversationType: NonNullable<SessionMessageSnippet["conversationType"]>;
|
|
10
|
+
readonly from: string;
|
|
11
|
+
readonly useCustomAttachmentUpload?: boolean;
|
|
12
|
+
}) => Partial<SessionMessageSnippet>;
|
|
1
13
|
export declare const decodeSessionListPayloadBody: (payload?: Uint8Array) => Record<string, unknown>;
|
package/types/conversation.d.ts
CHANGED
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
* [zh-CN] Conversation 公开类型定义。
|
|
3
3
|
* [en-US] Public conversation type definitions.
|
|
4
4
|
*/
|
|
5
|
-
import type {
|
|
6
|
-
import type { Message, MessageDirect, MessageModifiedInfo, MessageSendStatus, MessageType } from './index';
|
|
5
|
+
import type { Message } from './index';
|
|
7
6
|
export type { Sender } from './sender';
|
|
8
7
|
export declare const CONVERSATION_TYPE: {
|
|
9
8
|
readonly SINGLE_CHAT: "singleChat";
|
|
@@ -205,38 +204,46 @@ export interface RefreshSessionListParams {
|
|
|
205
204
|
*/
|
|
206
205
|
export type SessionListRemindType = 'DEFAULT' | 'ALL' | 'AT' | 'NONE';
|
|
207
206
|
/**
|
|
208
|
-
* [zh-CN]
|
|
209
|
-
* [en-US]
|
|
207
|
+
* [zh-CN] 会话列表最后消息快照。
|
|
208
|
+
* [en-US] Last-message snapshot used by the conversation list.
|
|
209
|
+
*
|
|
210
|
+
* @remarks
|
|
211
|
+
* [zh-CN] 字段类型复用 Message,保留可获得的正文和元信息。历史摘要可能不完整,因此可选字段保持可选,body 保留对象类型以兼容旧缓存;新解析正文与 MessageBody 一致,不应将历史摘要强制转换为完整 Message。
|
|
212
|
+
* [en-US] Field types are shared with Message and preserve available content and metadata. Legacy snippets can be incomplete, so optional fields remain optional and body keeps an object type for compatibility. Newly decoded content matches MessageBody; legacy snippets should not be cast to complete Message objects.
|
|
213
|
+
* [zh-CN] 从旧版缓存升级时,最后消息可能缺少参与者和方向。若无法从同会话、同消息的记录恢复,`from`、`sender.userId` 及无法确定的单聊 `to` 为空字符串,`direct` 为 `undefined`。UI 应省略未知发送者资料和依赖方向的展示,不能默认认定对端发送。同步服务可用时重新同步会话列表,或等待新消息更新,可补齐能够获得的信息;保留旧消息正文,不通过清空缓存恢复身份。
|
|
214
|
+
* [en-US] After upgrading from a legacy cache, the last message may lack participant and direction data. If it cannot be recovered from a record for the same conversation and message, `from`, `sender.userId`, and an undetermined one-to-one `to` are empty strings, while `direct` is `undefined`. The UI should omit unknown sender details and direction-dependent rendering instead of assuming an incoming message. Re-syncing the conversation list when the sync service is available, or receiving a new message, can populate available information. Legacy message content is retained; clearing the cache does not recover identities.
|
|
210
215
|
*/
|
|
211
|
-
export interface SessionMessageSnippet {
|
|
216
|
+
export interface SessionMessageSnippet extends Readonly<Partial<Omit<Message, 'body'>>> {
|
|
212
217
|
/** [zh-CN] 服务端消息 ID。 [en-US] Message ID on the server. */
|
|
213
|
-
readonly msgServerId:
|
|
214
|
-
/** [zh-CN] 消息发送者的用户 ID
|
|
215
|
-
readonly from:
|
|
216
|
-
/** [zh-CN]
|
|
217
|
-
readonly to:
|
|
218
|
-
/** [zh-CN]
|
|
219
|
-
readonly sender:
|
|
218
|
+
readonly msgServerId: Message['msgServerId'];
|
|
219
|
+
/** [zh-CN] 消息发送者的用户 ID;无法恢复的旧缓存身份为空字符串。 [en-US] Sender user ID; empty when identity cannot be recovered from a legacy cache. */
|
|
220
|
+
readonly from: Message['from'];
|
|
221
|
+
/** [zh-CN] 实际接收方 ID:单聊为接收者用户 ID,群聊为群组 ID,聊天室为聊天室 ID;无法确定的旧缓存单聊接收者为空字符串。 [en-US] Actual recipient ID: recipient user ID for one-to-one chat, group ID for group chat, or chat room ID for chat room; empty when a legacy one-to-one recipient is undetermined. */
|
|
222
|
+
readonly to: Message['to'];
|
|
223
|
+
/** [zh-CN] 发送者信息;无法恢复的旧缓存中 userId 为空字符串。 [en-US] Sender information; userId is empty when legacy identity cannot be recovered. */
|
|
224
|
+
readonly sender: Message['sender'];
|
|
220
225
|
/** [zh-CN] 会话 ID。 [en-US] Conversation ID. */
|
|
221
|
-
readonly conversationId?:
|
|
226
|
+
readonly conversationId?: Message['conversationId'];
|
|
222
227
|
/** [zh-CN] 会话类型。 [en-US] Conversation type. */
|
|
223
|
-
readonly conversationType?:
|
|
228
|
+
readonly conversationType?: Message['conversationType'];
|
|
224
229
|
/** [zh-CN] 消息类型。 [en-US] Message type. */
|
|
225
|
-
readonly type?:
|
|
230
|
+
readonly type?: Message['type'];
|
|
226
231
|
/** [zh-CN] 消息发送状态。 [en-US] Message sending status. */
|
|
227
|
-
readonly sendStatus?:
|
|
232
|
+
readonly sendStatus?: Message['sendStatus'];
|
|
228
233
|
/** [zh-CN] 消息时间戳(毫秒)。 [en-US] Message timestamp, in milliseconds. */
|
|
229
234
|
readonly timestamp: number;
|
|
230
|
-
/** [zh-CN]
|
|
231
|
-
readonly direct?:
|
|
235
|
+
/** [zh-CN] 消息方向:发送或接收;仅在有可靠记录时提供,未知时为 undefined,不根据发送者推测。 [en-US] Message direction: outgoing or incoming; provided only from a reliable record, undefined when unknown, and never inferred from the sender. */
|
|
236
|
+
readonly direct?: Message['direct'];
|
|
232
237
|
/** [zh-CN] 消息修改信息;当最后一条消息被编辑后,此字段可能存在。 [en-US] Message modification information; present when the last message has been edited. */
|
|
233
|
-
readonly modifiedInfo?:
|
|
238
|
+
readonly modifiedInfo?: Message['modifiedInfo'];
|
|
234
239
|
/** [zh-CN] 发送者用户资料的版本时间戳(秒),用于资料补全。 [en-US] User profile version timestamp (in seconds) of the message sender, used for profile hydration. */
|
|
235
240
|
readonly userInfoUpdateTime?: number;
|
|
236
241
|
/** [zh-CN] 群成员名片的版本时间戳(秒),仅群聊会话的最后一条消息可能存在此字段。 [en-US] The version timestamp (in seconds) of the Group member name card. This field may only exist for the last message in group chat conversations. */
|
|
237
242
|
readonly namecardUpdateTime?: number;
|
|
238
|
-
/** [zh-CN]
|
|
243
|
+
/** [zh-CN] 与 MessageBody 一致的消息正文,不包含 type;为兼容历史不完整摘要,保留对象类型。 [en-US] Message content matching MessageBody without type; an object type is retained for incomplete legacy snippets. */
|
|
239
244
|
readonly body: Record<string, unknown>;
|
|
245
|
+
/** [zh-CN] 消息扩展字段,与 onMessage 的 ext 一致;旧缓存可能缺失。 [en-US] Message extension fields, matching onMessage ext; may be absent in legacy caches. */
|
|
246
|
+
readonly ext?: Message['ext'];
|
|
240
247
|
}
|
|
241
248
|
/**
|
|
242
249
|
* [zh-CN] 公开的会话列表项,来自本地会话列表缓存的投影数据。
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { MessageDirect } from '../types';
|
|
2
|
+
import type { ConversationType } from '../types/conversation';
|
|
3
|
+
/** 会话摘要仅暴露接收者用户 ID,完整 Message 继续保留设备路由信息。 */
|
|
4
|
+
export declare const resolveSessionMessageTo: (options: {
|
|
5
|
+
readonly conversationId: string;
|
|
6
|
+
readonly conversationType: ConversationType;
|
|
7
|
+
readonly currentUserId: string;
|
|
8
|
+
readonly from: string;
|
|
9
|
+
readonly to?: string;
|
|
10
|
+
readonly direct?: MessageDirect;
|
|
11
|
+
}) => string;
|
package/chunks/index-l_BUKi77.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{i as e}from"./cache-utils-B99glc0H.js";import{p as t,V as r,E as o,S as s,A as n,a4 as a,l as i,n as u,aG as p,e as d,f as c,B as m,aH as l,h,m as g,j as I}from"./common-BvlDAw4a.js";import{a as y}from"./profile-version-DLMz8lqW.js";import{m as f,g as _,r as w,a as G}from"./group-user-info-resolver-DMccCqez.js";import{G as b}from"./event-system-B62vbKqG.js";import{c as v}from"./query-params-Bu3Xq4b6.js";import{b as R,a as S,n as A}from"./user-info-AlshAvdy.js";import{l as U}from"./light-DImBnNes.js";import{L as E,a as C,b as O}from"./reflection-proto-codec-7r8Sei3y.js";const T=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],M=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),D=e=>({userId:e}),N=(e,t,r)=>{const o={userId:r};for(const s of T){const r=t?.[s]??e?.[s];void 0!==r&&(o[s]=r)}return o},L=async(e,t)=>{const r=(e=>{const t=[],r=/* @__PURE__ */new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),o=/* @__PURE__ */new Map;if(0===r.length)return o;const s=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const a of s)o.set(a.userId,M(a));const n=r.filter(e=>!o.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)o.set(t.userId,t)}for(const a of r)o.has(a)||o.set(a,D(a));return o},F=t=>e(t)?t:null,P=e=>{if("string"==typeof e)return e},$=e=>{const t=P(e)?.trim();return t||void 0},j=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},x=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},k=e=>{const t=F(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},J=e=>{const t=F(e);return t?F(t.data)?t.data:t:null},q=(e,t)=>{const r=F(e),o=r&&F(r.params),s=o?.[t];if(Array.isArray(s)&&0!==s.length)return j(s[0])},B=(e,t)=>{const r=(e=>{const t=F(e);return t?j(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},H=e=>$(e.groupId)??$(e.groupid)??$(e.id)??"",V=e=>P(e.name)??P(e.groupname)??P(e.groupName)??"",K=e=>{const t=k(e),r=F(t[0])??J(e)??{},o=(e=>{const t=F(e);if(!t)return null;const r=H(t);return r?{groupId:r,name:V(t),description:P(t.description),memberCount:j(t.memberCount)??j(t.affiliations_count),public:x(t.public),joinApprovalRequired:x(t.joinApprovalRequired)??x(t.approval)??x(t.membersonly)??x(t.members_only),allowInvites:x(t.allowInvites)??x(t.allowinvites)??x(t.allow_user_invites),maxMembers:j(t.maxMembers)??j(t.maxusers),role:$(t.role)??$(t.permission),disabled:x(t.disabled)}:null})(r)??{groupId:H(r),name:V(r)},s=$(r.owner)??$(r.admin)??$(r.member),n=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>F(e)).filter(e=>null!==e).map(e=>j(e.joined_time)).find(e=>void 0!==e);return{...o,owner:s?D(s):void 0,inviteNeedConfirm:x(r.inviteNeedConfirm)??x(r.invite_need_confirm),muteAllMembers:x(r.mute),ext:P(r.ext)??P(r.custom),createdAt:j(r.createdAt)??j(r.created),joinedAt:n,avatarUrl:P(r.avatar),messageBlocked:x(r.messageBlocked)??x(r.isMessageBlocked)??x(r.shieldgroup)}},z=e=>D(e),W=e=>k(e).map(e=>$(e)).filter(e=>Boolean(e)).map(e=>z(e)),Q=e=>{const t=F(e);if(!t)return null;const r=$(t.fileId)??$(t.file_id);if(!r)return null;const o=P(t.fileName)??P(t.file_name)??r,s=$(t.fileOwner)??$(t.file_owner);return{fileId:r,fileName:o,fileOwner:s?z(s):void 0,fileSize:j(t.fileSize)??j(t.file_size),createdAt:j(t.createdAt)??j(t.created)}},Y=100,X=3e3,Z=e=>({...e}),ee=e=>"object"==typeof e&&null!==e,te=e=>"DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e?e:"mentionOnly"===e?"AT":"mute"===e?"NONE":"default"===e?"DEFAULT":2===e?"AT":3===e?"NONE":0===e?"DEFAULT":1===e?"ALL":void 0;class re{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:Y,serverLimit:X,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:Y,serverLimit:X,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return ee(t=e)&&"string"==typeof t.groupId&&0!==t.groupId.length?{groupId:t.groupId,name:"string"==typeof t.name?t.name:"",description:"string"==typeof t.description?t.description:void 0,memberCount:"number"==typeof t.memberCount?t.memberCount:void 0,role:"owner"===t.role||"admin"===t.role||"member"===t.role?t.role:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,ownerId:"string"==typeof t.ownerId?t.ownerId:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:void 0,muteAllMembers:"boolean"==typeof t.muteAllMembers?t.muteAllMembers:void 0,muteExpiration:"number"==typeof t.muteExpiration?t.muteExpiration:void 0,remindType:te(t.remindType),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,updatedAt:"number"==typeof t.updatedAt?t.updatedAt:void 0,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null;var t}).filter(e=>null!==e):[];this.items=t.slice(0,Y),this.meta=(e=>{const t=ee(e)?e:{};return{integrity:"synced"===t.integrity||"limited"===t.integrity||"incomplete"===t.integrity||"unknown"===t.integrity?t.integrity:"preview",limited:!0===t.limited,storageLimit:"number"==typeof t.storageLimit?t.storageLimit:Y,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:X,source:"localPreview",lastSyncFinishedTs:"number"==typeof t.lastSyncFinishedTs?t.lastSyncFinishedTs:void 0,lastSuccessfulAt:"number"==typeof t.lastSuccessfulAt?t.lastSuccessfulAt:void 0,reason:"string"==typeof t.reason?t.reason:void 0}})(e.meta)}setSnapshot(e){this.items=e.items.map(e=>Z(e)).slice(0,Y),this.meta={...e.meta,source:"localPreview",storageLimit:Y,serverLimit:X,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>Z(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>Z(e)),meta:{...this.meta,source:"localPreview"}}}}class oe{constructor(e,t){this.groupId=e,this.manager=t}getSummary(){return this.manager.getGroupSummaryForHandle(this.groupId)}getDetail(){return this.manager.getGroupDetailForHandle(this.groupId)}refresh(){return this.manager.refreshGroupDetailForHandle(this.groupId)}updateInfo(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}updateConfigs(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}changeOwner(e){return this.manager.changeGroupOwner({groupId:this.groupId,newOwner:e.newOwner})}destroy(){return this.manager.destroyGroup(this.toTarget())}leave(){return this.manager.leaveGroup(this.toTarget())}getMembers(e={}){return this.manager.getGroupMemberList({groupId:this.groupId,...e})}removeMembers(e){return this.manager.removeGroupMembers(this.toUserBatchParams(e))}getAdmins(){return this.manager.getGroupAdminList(this.toTarget())}addAdmin(e){return this.manager.addGroupAdmin({groupId:this.groupId,userId:e.userId})}removeAdmin(e){return this.manager.removeGroupAdmin({groupId:this.groupId,userId:e.userId})}getMuteList(e){return this.manager.getGroupMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteGroupMembers({groupId:this.groupId,userIds:e.userIds,muteDuration:e.muteDuration})}unmuteMembers(e){return this.manager.unmuteGroupMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllGroupMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllGroupMembers(this.toTarget())}getBlocklist(e){return this.manager.getGroupBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockGroupMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockGroupMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getGroupAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToGroupAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromGroupAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInGroupAllowList({groupId:this.groupId})}checkIfInMuteList(){return this.manager.checkIfInGroupMuteList(this.toTarget())}getAnnouncement(){return this.manager.getGroupAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateGroupAnnouncement({groupId:this.groupId,announcement:e.announcement})}getSharedFileList(e={}){return this.manager.getGroupSharedFileList({groupId:this.groupId,...e})}uploadSharedFile(e){return this.manager.uploadGroupSharedFile({groupId:this.groupId,...e})}deleteSharedFile(e){return this.manager.deleteGroupSharedFile({groupId:this.groupId,fileId:e.fileId})}downloadSharedFile(e){return this.manager.downloadGroupSharedFile({groupId:this.groupId,...e})}setMemberAttributes(e){return this.manager.setGroupMemberAttributes({groupId:this.groupId,userId:e.userId,memberAttributes:e.memberAttributes})}getMembersAttributes(e){return this.manager.getGroupMembersAttributes({groupId:this.groupId,userIds:e.userIds,keys:e.keys})}toTarget(){return{groupId:this.groupId}}toUserBatchParams(e){return{groupId:this.groupId,userIds:e.userIds}}}const se=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},ne=e=>new r(`${e} is required`,{code:o.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),ae=(e,t)=>new r(t,{code:o.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),ie=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw ne(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,s)=>{if("string"!=typeof e)throw ae(`${t}[${s}]`,`${t}[${s}] must be a string`);const n=e.trim();n&&!o.has(n)&&(o.add(n),r.push(n))}),0===r.length)throw ne(t);return r},ue=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw ne(t);return e.trim()},pe=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw ae(t,`${t} must be a string`);return e}},de=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw ae(t,`${t} must be a boolean`);return e}},ce=(e,t)=>`/${e.orgName}/${e.appName}${t}`,me=/* @__PURE__ */new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),le=e=>{const t=v();"number"==typeof e?.pageNum&&t.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize));const r=t.toString();return r?`?${r}`:""},he=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups?resource=${o.encodedResource}`);return(e=>{const t=k(e),r=F(t[0]),o=J(e)??r;return{groupId:o&&H(o)||r&&H(r)||""}})(await e.post(s,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?ie(r.memberIds,"params.memberIds"):[],public:r.public,approval:r.joinApprovalRequired,allowinvites:r.allowInvites,invite_need_confirm:r.inviteNeedConfirm,maxusers:r.maxMembers,custom:r.ext,avatar:r.avatar},{operation:"createGroup"}))},ge=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=ce(o,`/chatgroups/${encodeURIComponent(s)}?joined_time=true&version=v3`),a=await e.get(n,{operation:"getGroupInfo"});return K(a)},Ie=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n={},a=pe(r.name,"params.name"),i=pe(r.description,"params.description"),u=pe(r.avatar,"params.avatar"),p=pe(r.ext,"params.ext"),d=de(r.public,"params.public"),c=de(r.joinApprovalRequired,"params.joinApprovalRequired"),m=de(r.allowInvites,"params.allowInvites"),l=de(r.inviteNeedConfirm,"params.inviteNeedConfirm"),h=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw ae(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==a&&(n.groupname=a),void 0!==i&&(n.description=i),void 0!==u&&(n.avatar=u),void 0!==p&&(n.custom=p),void 0!==d&&(n.public=d),void 0!==c&&(n.membersonly=c),void 0!==m&&(n.allowinvites=m),void 0!==l&&(n.invite_need_confirm=l),void 0!==h&&(n.maxusers=h),0===Object.keys(n).length)throw ne("params");const g=ce(o,`/chatgroups/${encodeURIComponent(s)}?resource=${o.encodedResource}&version=v3`);await e.put(g,n,{operation:"updateGroupInfo"})},ye=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/users${(e=>{const t=v();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const n of k(e)){const e=F(n);if(!e)continue;const r=$(e.owner),o=$(e.admin),s=$(e.member),a=r??o??s;if(!a)continue;const i=j(e.joinedAt)??j(e.joined_time);t.push({user:z(a),role:r?"owner":o?"admin":"member",...void 0===i?{}:{joinedAt:i}})}const r=q(e,"pagenum"),o=q(e,"pagesize"),s=B(e,o);return{items:t,pageNum:r,pageSize:o,...void 0===s?{}:{hasMore:s}}})(await e.get(s,{operation:"getGroupMemberList"}))},fe=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin`),n=await e.get(s,{operation:"getGroupAdminList"});return W(n)},_e=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=le(r),a=n?"&":"",i=ce(o,`/chatgroups/${encodeURIComponent(s)}/mute?version=v3${a}${n.replace("?","")}`);return(e=>{const t=[];for(const r of k(e)){const e=$(r);if(e){t.push({user:z(e)});continue}const o=F(r);if(!o)continue;const s=$(o.user);if(!s)continue;const n=j(o.expire);t.push({user:z(s),...void 0===n?{}:{muteExpire:n}})}return t})(await e.get(i,{operation:"getGroupMuteList"}))},we=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=le(r),a=n?"&":"",i=ce(o,`/chatgroups/${encodeURIComponent(s)}/blocks/users?version=v3${a}${n.replace("?","")}`),u=await e.get(i,{operation:"getGroupBlocklist"});return W(u).map(e=>({user:e}))},Ge=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users`),n=await e.get(s,{operation:"getGroupAllowlist"});return W(n).map(e=>({user:e}))},be=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=J(e)??{};return{announcement:P(t.announcement)??""}})(await e.get(s,{operation:"getGroupAnnouncement"}))},ve=async(e,t,r)=>{const o=se(t),s=v();s.set("pagenum",String(r.pageNum??1)),s.set("pagesize",String(r.pageSize??20));const n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/share_files?${s.toString()}`);return(e=>{const t=q(e,"pagenum"),r=q(e,"pagesize"),o=B(e,r);return{items:k(e).map(e=>Q(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===o?{}:{hasMore:o}}})(await e.get(n,{operation:"getGroupSharedFileList"}))},Re=(e,t)=>{const r=se(e);return ce(r,`/chatgroups/${encodeURIComponent(ue(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(ue(t.fileId,"params.fileId"))}`)},Se=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=ue(r.userId,"params.userId"),a=((e,t,r)=>{if(t!==e.userId)return null;const o=Object.entries(r);if(0===o.length)return null;let s;for(const[n,a]of o){if(!me.has(n)||"string"!=typeof a)return null;if(void 0!==s){if(s!==a)return null}else s=a}return void 0===s?null:{nameCard:s}})(t,n,r.memberAttributes);if(a){const t=ce(o,`/sdk/chatgroups/${encodeURIComponent(s)}/nameCard`);return await e.put(t,a,{operation:"setGroupMemberAttributes"})}const i=ce(o,`/sdk/metadata/chatgroup/${encodeURIComponent(s)}/user/${encodeURIComponent(n)}?resource=${o.encodedResource}`);return await e.put(i,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},Ae=async(e,t,r)=>{const o=se(t),s=ce(o,`/sdk/metadata/chatgroup/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/get`);return(e=>{const t=J(e)??{},r=F(t.data)??t,o={};for(const[s,n]of Object.entries(r)){const e=F(n);e&&(o[s]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:o}})(await e.post(s,{targets:ie(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},Ue=t=>{const r=e(t)?t:{},o=r.data,s=e(o)?o.data:void 0,n=Array.isArray(o)?o:Array.isArray(s)?s:null;if(Array.isArray(n))return Ee(n);const a=e(o)?o:r,i=e(a.namecards)?a.namecards:a,u={};for(const[p,d]of Object.entries(i)){if("string"==typeof d){u[p]={namecard:d};continue}if(!e(d))continue;const t=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof t&&(u[p]={namecard:t,namecardUpdateTime:Ce(d)})}return u},Ee=t=>{const r={};return t.forEach(t=>{if(!e(t))return;const o=t.username??t.userId??t.userid??t.user_id,s=t.name_card??t.namecard??t.nameCard??t.groupNamecard??t.group_namecard??t.group_name_card;"string"==typeof o&&o.trim()&&"string"==typeof s&&(r[o.trim()]={namecard:s,namecardUpdateTime:Ce(t)})}),r},Ce=e=>y("number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.timestamp?e.timestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0),Oe=t=>{if(e(t))return y("number"==typeof t.timestamp?t.timestamp:"number"==typeof t.update_timestamp?t.update_timestamp:"number"==typeof t.updateTimestamp?t.updateTimestamp:"number"==typeof t.lastModified?t.lastModified:"number"==typeof t.last_modified?t.last_modified:void 0)};class Te{constructor(e){this.repository=e}applyPatch(e){e.shouldMarkStale&&this.repository.markStale(e.groupId);const t=this.repository.getDetailSnapshot(e.groupId);if(!e.groupPatch)return t;const r=t??{groupId:e.groupId,name:e.groupPatch.name??e.groupName??""};return this.repository.mergeDetail({...r,...e.groupPatch,groupId:e.groupId})}}const Me=e=>({...e}),De=e=>({...e,owner:e.owner?{...e.owner}:void 0});class Ne{constructor(e){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null,this.groupId=e}mergeSummary(e){e.groupId===this.groupId&&(this.summarySnapshot=Me({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=De({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=Me(this.toSummaryFromDetail(this.detailSnapshot)),this.loadedSummary=!0,this.loadedDetail=!0,this.stale=!1,this.lastPatchedAt=Date.now(),this.lastHydratedAt=Date.now())}markStale(){this.stale=!0,this.lastPatchedAt=Date.now()}clear(){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null}getSummarySnapshot(){return this.summarySnapshot?Me(this.summarySnapshot):this.detailSnapshot?Me(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?De(this.detailSnapshot):null}isStale(){return this.stale}hasLoadedSummary(){return this.loadedSummary}hasLoadedDetail(){return this.loadedDetail}getLastPatchedAt(){return this.lastPatchedAt}getLastHydratedAt(){return this.lastHydratedAt}toSummaryFromDetail(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,public:e.public,joinApprovalRequired:e.joinApprovalRequired,allowInvites:e.allowInvites,maxMembers:e.maxMembers,role:e.role,disabled:e.disabled}}}class Le{toSummary(e){const t=e.getSummarySnapshot();return t?(e=>({...e}))(t):null}toDetail(e){const t=e.getDetailSnapshot();return t?(e=>({...e,owner:e.owner?{...e.owner}:void 0}))(t):null}}class Fe{constructor(){this.groups=/* @__PURE__ */new Map,this.joinedGroupById=/* @__PURE__ */new Map,this.removedJoinedGroupIds=/* @__PURE__ */new Set,this.snapshotMapper=new Le,this.joinedGroupSnapshot=null,this.sessionKey=null}ensureSession(e){return this.sessionKey!==e&&(this.sessionKey=e,this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null,!0)}getSessionKey(){return this.sessionKey}getOrCreate(e){const t=this.groups.get(e);if(t)return t;const r=new Ne(e);return this.groups.set(e,r),r}mergeSummary(e){return this.getOrCreate(e.groupId).mergeSummary(e),this.getSummarySnapshot(e.groupId)??{...e}}mergeSummaries(e){return e.map(e=>this.mergeSummary(e))}applyJoinedGroupSnapshot(e){const t=e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId));this.joinedGroupSnapshot={items:t.map(e=>({...e})),meta:{...e.meta}},this.joinedGroupById.clear();for(const r of t){const e={...r};this.joinedGroupById.set(e.groupId,e),this.mergeSummary(this.toGroupSummary(e))}}getJoinedGroupSnapshot(e){return this.joinedGroupSnapshot?{items:this.joinedGroupSnapshot.items.map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}}:e?{items:e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId)).map(e=>({...e})),meta:{...e.meta}}:{items:[],meta:{integrity:"unknown",limited:!1,storageLimit:100,serverLimit:3e3,source:"sync"}}}getJoinedGroupSummarySnapshot(e,t){const r=this.joinedGroupById.get(e);if(r)return{...r};if(this.removedJoinedGroupIds.has(e))return null;const o=t?.items.find(t=>t.groupId===e);return o?{...o}:null}addJoinedGroupIfAbsent(e,t){const r=this.getJoinedGroupSnapshot(t);return r.items.some(t=>t.groupId===e.groupId)?null:(this.removedJoinedGroupIds.delete(e.groupId),this.applyJoinedGroupSnapshot({items:[{...e},...r.items],meta:{...r.meta}}),this.getJoinedGroupSnapshot())}mergeJoinedGroupSummary(e,t){const r=this.joinedGroupById.get(e);if(!r||!this.joinedGroupSnapshot)return null;const o={...r,...t,groupId:e};return this.joinedGroupById.set(e,o),this.mergeSummary(this.toGroupSummary(o)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...o}:{...t}),meta:{...this.joinedGroupSnapshot.meta}},this.getJoinedGroupSnapshot()}mergeDetail(e){const t=this.mergeJoinedGroupFieldsIntoDetail(e);return this.getOrCreate(t.groupId).mergeDetail(t),this.getDetailSnapshot(t.groupId)??{...t}}mergeDetails(e){return e.map(e=>this.mergeDetail(e))}getSummarySnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toSummary(t):null}getDetailSnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toDetail(t):null}hasFreshDetail(e){const t=this.groups.get(e);return Boolean(t&&t.hasLoadedDetail()&&!t.isStale())}markStale(e){this.getOrCreate(e).markStale()}delete(e){this.groups.delete(e),this.joinedGroupById.delete(e),this.joinedGroupSnapshot&&(this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.filter(t=>t.groupId!==e).map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}})}markJoinedGroupRemoved(e){this.removedJoinedGroupIds.add(e),this.delete(e)}clear(){this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null}mergeJoinedGroupFieldsIntoDetail(e){const t=this.joinedGroupById.get(e.groupId);return t&&void 0===e.joinedAt&&void 0!==t.joinedAt?{...e,joinedAt:t.joinedAt}:e}toGroupSummary(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,role:e.role,disabled:e.disabled}}}const Pe=0,$e=5,je=12,xe=13,ke=0,Je=1,qe=2,Be=0,He=1,Ve=2,Ke=3,ze=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(o=e.role,o===ke?"owner":o===Je?"admin":o===qe?"member":void 0),disabled:e.disabled,ownerId:e.group_owner,avatarUrl:e.group_avatar,muteAllMembers:e.mute_all,muteExpiration:e.mute_expiration,remindType:(r=e.remind_type,r===Be?"DEFAULT":r===He?"ALL":r===Ve?"AT":r===Ke?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,o},We=e=>e.updatedAt??0,Qe=(e,t)=>{if(!e)return!0;return We(t)>=We(e)},Ye={nested:{easemob:{nested:{joinedgroups:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},GetJoinedGroupsRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},cursor:{type:"string",id:7}}},GroupItem:{fields:{group_id:{type:"string",id:1},group_name:{type:"string",id:2},group_owner:{type:"string",id:3},members_count:{type:"int64",id:4},mute_all:{type:"bool",id:5},disabled:{type:"bool",id:6},description:{type:"string",id:7},group_avatar:{type:"string",id:8},role:{type:"uint32",id:9},mute_expiration:{type:"int64",id:10},remind_type:{type:"int32",id:11},create_at:{type:"uint64",id:12},update_at:{type:"uint64",id:13},joined_timestamp:{type:"int64",id:14}}},GetJoinedGroupsResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},groups:{rule:"repeated",type:"GroupItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5},cursor:{type:"string",id:6}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let Xe=null,Ze=!1;const et=()=>Xe||(Ze||(U.util.Long=E,U.configure(),Ze=!0),C(),Xe=U.Root.fromJSON(Ye),O(Xe),Xe),tt=e=>et().lookupType(e),rt=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if(E.isLong(e))return e.toNumber();if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},ot=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:rt(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:rt(t.protocol_version)??rt(t.protocolVersion)??0}};class st{constructor(){this.requestType=tt("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=tt("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=tt("easemob.joinedgroups.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,cursor:e.cursor});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const o=this.tryDecodeRequest(e);return o||{type:Pe}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==je?null:{type:r,header:ot(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:rt(t.last_sync_time)??rt(t.lastSyncTime)??0,cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==xe?null:{type:r,header:ot(t.header),groups:Array.isArray(t.groups)?t.groups.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{group_id:"string"==typeof t.group_id?t.group_id:"string"==typeof t.groupId?t.groupId:void 0,group_name:"string"==typeof t.group_name?t.group_name:"string"==typeof t.groupName?t.groupName:void 0,group_owner:"string"==typeof t.group_owner?t.group_owner:"string"==typeof t.groupOwner?t.groupOwner:void 0,members_count:rt(t.members_count)??rt(t.membersCount),mute_all:"boolean"==typeof t.mute_all?t.mute_all:"boolean"==typeof t.muteAll?t.muteAll:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,description:"string"==typeof t.description?t.description:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:"string"==typeof t.groupAvatar?t.groupAvatar:void 0,role:rt(t.role),mute_expiration:rt(t.mute_expiration)??rt(t.muteExpiration),remind_type:rt(t.remind_type)??rt(t.remindType),create_at:rt(t.create_at)??rt(t.createAt),update_at:rt(t.update_at)??rt(t.updateAt),joined_timestamp:rt(t.joined_timestamp)??rt(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:rt(t.last_sync_finished_ts)??rt(t.lastSyncFinishedTs),cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==$e?null:{type:r,header:ot(t.header),code:rt(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class nt{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==xe)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new s("Joined groups response received after completion",o.REST_BUSINESS_UNKNOWN,{details:{stage:"response_decode",requestId:this.requestId}});if(this.batches.push(e),e.cursor&&(this.latestCursor=e.cursor),e.isLastBatch){if("number"!=typeof e.lastSyncFinishedTs)throw new s("Joined groups final batch missing lastSyncFinishedTs",o.REST_BUSINESS_UNKNOWN,{details:{stage:"completion_meta",requestId:this.requestId}});this.done=!0,this.lastSyncFinishedTs=e.lastSyncFinishedTs}return{done:this.done}}buildResult(){return{batches:this.batches.map(e=>({...e,groups:e.groups.map(e=>({...e}))})),lastSyncFinishedTs:this.lastSyncFinishedTs}}}const at=e=>e.type===xe,it=e=>e.type===$e;class ut{constructor(e){this.codec=new st,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new nt(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,t,r){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:t,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,t,r.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:at(t)||it(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(at(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(it(e))throw(e=>{const t=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new s(e.message,o.VALIDATION_REQUIRED,{details:t("request_send",!1)});case 1602:return new s(e.message,o.REST_BUSINESS_UNKNOWN,{details:t("batch_merge",!0)});case 1002:return new n(e.message,{code:o.AUTH_UNAUTHORIZED,details:t("auth",!1)});case 1003:return new s(e.message,o.SERVICE_LIMIT_EXCEEDED,{details:t("server_limit",!0)});default:return new s(e.message,o.REST_BUSINESS_UNKNOWN,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof s?t:new s("Joined groups frame decode failed",o.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:t instanceof Error?t.message:String(t)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class pt{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const r=await this.dependencies.getSyncUrls();if(0===r.length)throw new s("Group sync websocket urls are unavailable",o.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const n=this.buildRequest(),u=await new ut(this.dependencies.getSharedSyncSession()).sync({urls:r,request:n}),p=u.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=ze(r);e&&t.push(e)}return t})(e.groups)),d=this.dependencies.getRuntimeSnapshot(),c=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=/* @__PURE__ */new Map;for(const s of e.incomingItems){const e=r.get(s.groupId)??t.get(s.groupId);Qe(e,s)?r.set(s.groupId,{...e??{},...s,groupId:s.groupId}):e&&r.set(s.groupId,{...e})}const o=r.size>=X;return{items:Array.from(o?e.existingItems.map(e=>({...e})):r.values()).sort((e,t)=>{const r=(t.joinedAt??0)-(e.joinedAt??0);return 0!==r?r:e.groupId.localeCompare(t.groupId)}),meta:{integrity:o?"limited":"synced",limited:o,storageLimit:Y,serverLimit:X,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:d?.items??[],incomingItems:p,lastSyncFinishedTs:u.lastSyncFinishedTs}),m=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(c);const l=this.dependencies.getRuntimeSnapshot()??c;try{await m.commitJoinedGroupPreviewSnapshot(l);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(l,e)&&await m.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw d&&this.dependencies.applyRuntimeSnapshot(d),new a("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}i.warn("Group sync finished",{durationMs:Date.now()-e,itemCount:c.items.length,limited:c.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof s?e:new s("Group sync failed",o.REST_BUSINESS_UNKNOWN,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},n=r.serverCode;return{dataType:"group",code:t.code,stage:(a=r.stage,"config"===a||"socket_connect"===a||"request_send"===a||"response_decode"===a||"batch_merge"===a||"preview_persist"===a||"completion_meta"===a||"auth"===a||"server_limit"===a||"cancelled"===a?a:"socket_connect"),message:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof n||"string"==typeof n?n:void 0};var a})(t);i.warn("Group sync failed",{durationMs:Date.now()-e,stage:r.stage,code:r.code,serverCode:r.serverCode}),this.dependencies.onFinish({status:"failed",error:r})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:r,appName:o}=t(e.appKey);return{type:je,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:r,app:o,username:e.userId,lastSyncTime:0}}}const dt=g(I,{common:{},apis:{createGroup:{range:"4,110,204,608",errors:{invalid_parameter:{code:110,httpStatus:400,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:4,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1,aliases:["INVALID_GROUP_NAME"]},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]}}},getJoinedGroupList:{range:"",errors:{}},getGroupInfo:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupInfoList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupInfo:{range:"110,603,606,607,608",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},forbidden_op:{code:603,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:110,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},changeGroupOwner:{range:"603,606",errors:{forbidden_op:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},destroyGroup:{range:"603,606,607",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},leaveGroup:{range:"602,603,606",errors:{not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},owner_cannot_leave:{code:603,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"owner can not quit group"},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},joinGroup:{range:"600-607,613",errors:{group_invalid_id:{code:600,retryable:!1,aliases:["GROUP_INVALID_ID"]},already_joined:{code:601,retryable:!1,aliases:["ALREADY_JOINED","GROUP_ALREADY_JOINED","group_already_joined"]},not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},group_authorization:{code:603,httpStatus:403,retryable:!1,aliases:["NEED_APPROVAL","GROUP_PERMISSION_DENIED"]},group_full:{code:604,httpStatus:403,retryable:!1,aliases:["GROUP_FULL","GROUP_MEMBERS_FULL"],matchField:"error_description",matchPattern:"member list is full"},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["GROUP_NOT_FOUND","service_resource_not_found"]},group_disabled:{code:607,retryable:!1,aliases:["GROUP_DISABLED"]},group_user_in_blocklist:{code:613,httpStatus:403,retryable:!1,aliases:["GROUP_USER_IN_BLOCKLIST"],matchField:"error_description",matchPattern:"is in the blacklist"}}},inviteUsersToGroup:{range:"204,603,606,607",errors:{group_authorization:{code:603,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]},group_not_found:{code:606,retryable:!1,aliases:["GROUP_NOT_FOUND"]},group_disabled:{code:607,retryable:!1}}},acceptGroupJoinRequest:{range:"",errors:{}},rejectGroupJoinRequest:{range:"",errors:{}},acceptInvitation:{range:"",errors:{}},rejectInvitation:{range:"",errors:{}},removeGroupMembers:{range:"",errors:{}},addGroupAdmin:{range:"",errors:{}},removeGroupAdmin:{range:"",errors:{}},muteGroupMembers:{range:"",errors:{}},unmuteGroupMembers:{range:"",errors:{}},muteAllGroupMembers:{range:"",errors:{}},unmuteAllGroupMembers:{range:"",errors:{}},blockGroupMembers:{range:"",errors:{}},unblockGroupMembers:{range:"",errors:{}},addUsersToGroupAllowlist:{range:"",errors:{}},removeUsersFromGroupAllowlist:{range:"",errors:{}},checkIfInGroupAllowList:{range:"",errors:{}},getGroupMemberList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},getGroupAdminList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},checkIfInGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupBlocklist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAllowlist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAnnouncement:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupAnnouncement:{range:"110",errors:{announcement_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce into length exceeds limit"},announcement_info_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce info length exceeds limit"}}},getGroupSharedFileList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["RestGroupFeignException"]}}},deleteGroupSharedFile:{range:"603,605,606",errors:{group_authorization:{code:603,retryable:!1},file_not_found:{code:605,retryable:!1,aliases:["GROUP_SHARED_FILE_INVALID_ID"]},resource_not_found:{code:606,retryable:!1}}},setGroupMemberAttributes:{range:"4,210,302,305,602,609-612",errors:{attributes_reach_limit:{code:609,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT"],matchField:"error_code",matchValue:60006},attributes_update_failed:{code:610,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED"],matchField:"error_code",matchValue:60005},attributes_key_reach_limit:{code:611,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT"],matchField:"error_code",matchValue:60009},attributes_value_reach_limit:{code:612,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT"],matchField:"error_code",matchValue:600010},not_joined:{code:602,httpStatus:404,retryable:!1,matchField:"error_code",matchValue:60003},permission_denied:{code:210,httpStatus:401,retryable:!1,matchField:"error_code",matchValue:60001},permission_denied_403:{code:210,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60002},exceed_service_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60007},service_disabled:{code:305,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60004}}},getGroupMembersAttributes:{range:"606",errors:{resource_not_found:{code:606,retryable:!1}}},getGroupNamecards:{range:"",errors:{}}}}),ct=class{constructor(){this.capabilities=["rawNotify:group","group:namecard"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.groupRegistry=/* @__PURE__ */new Map,this.groupRepository=null,this.groupEventSync=null}bind(e,t){this.client=e,this.eventContext=t??null,this.groupRegistry.clear(),this.groupRepository=new Fe,this.groupEventSync=new Te(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,o=await this.buildIncomingEventPayload(r,t);if(!o)return;if(this.eventContext?.dispatch?.(r,o),r!==b.GROUP_MEMBER_ATTRIBUTE_CHANGED)return;if(!("attribute"in o)||!("user"in o))return;const s=this.extractGroupNamecard(o.attribute);if(void 0===s||!o.user?.userId)return;const n=this.client?.getCurrentUserId();o.user.userId!==n&&(this.getCacheManager()?.setGroupNamecards([{groupId:o.groupId,userId:o.user.userId,namecard:s,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(b.USER_GROUP_NAMECARD_UPDATED,{groupId:o.groupId,userId:o.user.userId,namecard:s}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await he(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const t=e.trim();if(0===t.length)throw new r("groupId is required",{code:o.VALIDATION_REQUIRED,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const s=this.groupRegistry.get(t);if(s)return s;this.getGroupSummaryForHandle(t),this.getGroupRepository().getOrCreate(t);const n=new oe(t,this);return this.groupRegistry.set(t,n),n}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await ge(this.getRestClient(t),t,e),o=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(o)})}async getGroupInfoList(t){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const r=this.getRestContextOrThrow(),o=await(async(t,r,o)=>{const s=se(r),n=ie(o.groupIds,"params.groupIds"),a=ce(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),i=await t.get(a,{operation:"getGroupInfoList"});return(e(i)&&Array.isArray(i.data)?i.data:[]).map(e=>K({data:[e]}))})(this.getRestClient(r),r,t),s=await this.hydrateGroupDetailsUsers(o);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,o=e===b.GROUP_DESTROYED?this.resolveLocalGroupName(r.groupId):void 0,s=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,s),e){case b.INVITATION_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,s),reason:r.reason};case b.REQUEST_TO_JOIN_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,s),reason:r.reason};case b.REQUEST_TO_JOIN_ACCEPTED:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,s)};case b.REQUEST_TO_JOIN_DECLINED:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,s),applicant:this.pickEventUser(r.applicantId,s),reason:r.reason};case b.INVITATION_ACCEPTED:case b.INVITATION_DECLINED:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,s),reason:r.reason};case b.USER_REMOVED:return{groupId:r.groupId,groupName:r.groupName};case b.GROUP_DESTROYED:return{groupId:r.groupId,groupName:r.groupName??o};case b.AUTO_ACCEPT_INVITATION:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,s),inviteMessage:r.reason};case b.MUTE_LIST_ADDED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,s),muteExpire:r.muteExpire};case b.MUTE_LIST_REMOVED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,s)};case b.ALLOW_LIST_ADDED:case b.ALLOW_LIST_REMOVED:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,s)};case b.ALL_MEMBER_MUTE_STATE_CHANGED:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case b.ADMIN_ADDED:case b.ADMIN_REMOVED:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,s)};case b.OWNER_CHANGED:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,s),oldOwner:this.pickEventUser(r.oldOwnerId,s)};case b.MEMBERS_JOINED:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,s)};case b.MEMBERS_EXITED:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,s)};case b.ANNOUNCEMENT_CHANGED:return{groupId:r.groupId,announcement:r.announcement??""};case b.SHARED_FILE_ADDED:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,s)};case b.SHARED_FILE_DELETED:return{groupId:r.groupId,fileId:r.fileId??""};case b.GROUP_INFO_CHANGED:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case b.GROUP_DISABLED_CHANGED:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case b.GROUP_MEMBER_ATTRIBUTE_CHANGED:return{groupId:r.groupId,user:this.pickEventUser(r.userId,s),attribute:r.attribute??{},from:r.from,source:r.source};default:return null}}async resolveGroupDetailForEvent(e){this.ensureRepositorySession();const t=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},r=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:t,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(s){i.warn("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:s})}if(r)return r;const o=this.getGroupRepository().getDetailSnapshot(e.groupId);return o||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await Ie(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}?resource=${o.encodedResource}`);await e.put(s,{newowner:ue(r.newOwner,"params.newOwner")},{operation:"changeGroupOwner"})})(this.getRestClient(t),t,e)})}async destroyGroup(e){return this.runOperation("destroyGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}?version=v3&resource=${o.encodedResource}`);await e.delete(s,{operation:"destroyGroup"})})(this.getRestClient(t),t,e),await this.requireClient().handleGroupDestroyedConversation(e.groupId),await this.removeJoinedGroupLocal(e.groupId)})}async leaveGroup(e){return this.runOperation("leaveGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/quit?resource=${o.encodedResource}`);await e.delete(s,{operation:"leaveGroup"})})(this.getRestClient(t),t,e),await this.removeJoinedGroupLocal(e.groupId)})}async joinGroup(e){return this.runOperation("joinGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply?resource=${o.encodedResource}`);await e.post(s,{message:r.message??""},{operation:"joinGroup"})})(this.getRestClient(t),t,e)})}async inviteUsersToGroup(e){return this.runOperation("inviteUsersToGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"inviteUsersToGroup"})})(this.getRestClient(t),t,e)})}async acceptGroupJoinRequest(e){return this.runOperation("acceptGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:ue(r.userId,"params.userId"),verifyResult:!0},{operation:"acceptGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async rejectGroupJoinRequest(e){return this.runOperation("rejectGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:ue(r.userId,"params.userId"),verifyResult:!1,reason:r.reason},{operation:"rejectGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async acceptInvitation(e){return this.runOperation("acceptInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!0},{operation:"acceptInvitation"})})(this.getRestClient(t),t,e)})}async rejectInvitation(e){return this.runOperation("rejectInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await ye(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await fe(this.getRestClient(t),t,e);return this.hydrateUserInfos(e.groupId,r)})}async addGroupAdmin(e){return this.runOperation("addGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin?resource=${o.encodedResource}`);await e.post(s,{newadmin:r.userId},{operation:"addGroupAdmin"})})(this.getRestClient(t),t,e)})}async removeGroupAdmin(e){return this.runOperation("removeGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${o.encodedResource}`);await e.delete(s,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await _e(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async muteGroupMembers(e){return this.runOperation("muteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/mute?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds"),mute_duration:r.muteDuration},{operation:"muteGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteGroupMembers(e){return this.runOperation("unmuteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllGroupMembers(e){return this.runOperation("unmuteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await we(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async blockGroupMembers(e){return this.runOperation("blockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/blocks/users?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"blockGroupMembers"})})(this.getRestClient(t),t,e)})}async unblockGroupMembers(e){return this.runOperation("unblockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await Ge(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async addUsersToGroupAllowlist(e){return this.runOperation("addUsersToGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"addUsersToGroupAllowlist"})})(this.getRestClient(t),t,e)})}async removeUsersFromGroupAllowlist(e){return this.runOperation("removeUsersFromGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(t){return this.runOperation("checkIfInGroupAllowList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=se(r),n=ce(s,`/chatgroups/${encodeURIComponent(ue(o.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof a?a:e(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async checkIfInGroupMuteList(t){return this.runOperation("checkIfInGroupMuteList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=se(r),n=ce(s,`/sdk/chatgroups/${encodeURIComponent(ue(o.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof a?a:e(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return be(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/announcement?resource=${o.encodedResource}`);await e.post(s,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await ve(this.getRestClient(t),t,e),o=await this.resolveGroupContextUserInfoMap(e.groupId,r.items.map(e=>e.fileOwner).filter(e=>void 0!==e));return{...r,items:r.items.map(e=>({...e,fileOwner:e.fileOwner?.userId?o.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const t=this.getRestContextOrThrow(),r=Re(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),n=u({file:e.file}),a=m({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=a?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const u=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[d]:c()},source:n.source,timeoutMs:p,onProgress:e.onFileUploadProgress}));if(!u)throw new Error("platform upload adapter is unavailable");if(u.status<200||u.status>=300)throw new s("uploadGroupSharedFile failed",o.REST_HTTP_ERROR,{details:{status:u.status}});i?.finish({code:u.status,success:!0}),a?.finish({code:0,success:!0}),e.onFileUploadComplete?.(u.body)}catch(l){const t=f(l);throw i?.finish({code:t.code,success:!1,description:t.message}),a?.finish({code:t.code,success:!1,description:t.message}),t.code===o.UPLOAD_ABORTED&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(t),t}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(ue(r.fileId,"params.fileId"))}?resource=${o.encodedResource}`);await e.delete(s,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let t,r;try{const n=this.getRestContextOrThrow(),a=`${n.restBaseUrl}${Re(n,e)}`;t=m({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:a});const i=this.requireClient().getRequestAdapter();if(!i)throw new s("downloadGroupSharedFile request adapter is unavailable",o.REST_NETWORK_ERROR);const u=await i.request({url:a,method:"GET",headers:{Authorization:`Bearer ${n.token}`,...e.secret?{"Share-Secret":e.secret}:{},[d]:c()},responseType:"arraybuffer",timeoutMs:l});if(u.status<200||u.status>=300)throw r?.finish({code:u.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:u.status,success:!1,description:"downloadGroupSharedFile failed"}),new s("downloadGroupSharedFile failed",o.REST_HTTP_ERROR);r?.finish({code:u.status,success:!0}),t?.finish({code:0,success:!0});const p="undefined"!=typeof Blob?new Blob([u.data]):u.data;e.onFileDownloadComplete?.(p)}catch(n){const a=n instanceof s?n.code:o.REST_NETWORK_ERROR,i=n instanceof Error?n.message:String(n);throw r?.finish({code:a,success:!1,description:i}),t?.finish({code:a,success:!1,description:i}),e.onFileDownloadError?.(n),n}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await Se(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return Ae(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,t){0!==t.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const r=this.getRestContextOrThrow(),o=t.map(e=>e.userId),s=await(async(e,t,r)=>{const o=se(t),s=ce(o,`/sdk/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/nameCard/batch/get`),n=await e.post(s,{members:ie(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:Ue(n),responseTimestamp:Oe(n)}})(this.getRestClient(r),r,{groupId:e,userIds:o}),n=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),a=[],u=/* @__PURE__ */new Set;for(const[t,i]of Object.entries(s.items))u.add(t),a.push({groupId:e,userId:t,namecard:i.namecard,namecardUpdateTime:n.get(t)??i.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const p=o.filter(e=>!u.has(e));p.length>0&&"number"==typeof s.responseTimestamp&&a.push(...p.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:s.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(a);for(const e of a)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(b.USER_GROUP_NAMECARD_UPDATED,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});p.length>0&&"number"!=typeof s.responseTimestamp&&i.warn("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:o,missingUserIds:p})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw i.warn(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof s?t:t instanceof Error?new s(`GroupManager ${e} failed: ${t.message}`,o.UNKNOWN):new s(`GroupManager ${e} failed`,o.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new h(e.restBaseUrl,{errorMap:dt,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new s("GroupManager is not bound to client",o.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new Fe),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new Te(this.getGroupRepository())),this.groupEventSync}ensureRepositorySession(){this.getGroupRepository().ensureSession(this.resolveRepositorySessionKey())&&this.groupRegistry.clear()}resolveRepositorySessionKey(){if(!this.client)return null;const e=this.client.getCurrentUserId();if(!e)return null;try{const e=this.client.getRestContext();return`${e.restBaseUrl}:${e.userId}:${e.token}:${e.clientResource}`}catch{return`pending:${e}`}}getCacheManager(){return this.client?.getCacheManager()??null}loadJoinedGroupPreviewSnapshot(){const e=this.getCacheManager();if(e&&"function"==typeof e.loadJoinedGroupPreviewSnapshot)return e.loadJoinedGroupPreviewSnapshot()}resolveLocalGroupName(e){const t=this.getGroupRepository(),r=t.getSummarySnapshot(e)?.name;if(r)return r;const o=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return o||void 0}async resolveMembersJoinedGroupName(e){const t=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(t)return t;const r=this.resolveUsableGroupName(e.groupName,e.groupId);if(r)return r;const o=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await ge(this.getRestClient(t),t,{groupId:e.groupId}),s=this.getGroupRepository();if(s.getSessionKey()!==o)return;return s.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(s){return void i.warn("Members joined group detail enrichment failed",{groupId:e.groupId,error:s})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,t,r){if(t.userId!==e)return;const o=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof o)return;const s=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof s&&i.warn("Group member attributes update response missing server update time",{groupId:t.groupId,userId:t.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:t.groupId,userId:t.userId,namecard:o,namecardUpdateTime:s,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const o of r){const e=y("number"==typeof o?o:Number(o));if("number"==typeof e)return e}}collectUpdateTimeCandidates(t,r,o){if(!e(t))return;o.push(t.lastModified,t.last_modified,t.timestamp,t.updateTime,t.update_time,t.updatedAt,t.updated_at);const s=t.data;if(e(s)){this.collectUpdateTimeCandidates(s,r,o);const t=s[r];e(t)&&this.collectUpdateTimeCandidates(t,r,o)}const n=t.lastModified??t.last_modified;e(n)&&o.push(n[r])}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return L(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return i.warn("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],o=[],s=/* @__PURE__ */new Set;for(const n of r){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return N(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>N(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:N(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case b.ALL_MEMBER_MUTE_STATE_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case b.OWNER_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case b.REQUEST_TO_JOIN_ACCEPTED:case b.AUTO_ACCEPT_INVITATION:return void this.addCurrentUserJoinedGroupFromEvent(t);case b.MEMBERS_JOINED:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case b.MEMBERS_EXITED:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case b.USER_REMOVED:case b.GROUP_DESTROYED:return void(await this.removeJoinedGroupLocal(t.groupId));case b.MUTE_LIST_ADDED:case b.MUTE_LIST_REMOVED:case b.ALLOW_LIST_ADDED:case b.ALLOW_LIST_REMOVED:case b.ADMIN_ADDED:case b.ADMIN_REMOVED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case b.MEMBERS_JOINED:case b.MEMBERS_EXITED:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const o=this.getGroupRepository().getDetailSnapshot(e);return!(!o||"number"!=typeof o.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,o.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(o){return i.warn("Joined group detail enrichment skipped",{groupId:e.groupId,error:o}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(o){return i.warn("Joined group detail enrichment failed",{groupId:e.groupId,error:o}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const o=await ge(this.getRestClient(r),r,{groupId:e}),s=this.getGroupRepository();if(s.getSessionKey()!==t)return!1;s.mergeDetail(o);const n=s.getJoinedGroupSummarySnapshot(e);if(!n)return!1;const a=s.mergeJoinedGroupSummary(e,{...n.name||!o.name?{}:{name:o.name},...void 0!==n.description||void 0===o.description?{}:{description:o.description},...void 0!==n.memberCount||void 0===o.memberCount?{}:{memberCount:o.memberCount},...void 0!==n.role||void 0===o.role?{}:{role:o.role},...void 0!==n.disabled||void 0===o.disabled?{}:{disabled:o.disabled},...n.ownerId||!o.owner?.userId?{}:{ownerId:o.owner.userId},...void 0!==n.avatarUrl||void 0===o.avatarUrl?{}:{avatarUrl:o.avatarUrl},...void 0!==n.muteAllMembers||void 0===o.muteAllMembers?{}:{muteAllMembers:o.muteAllMembers},...void 0!==n.createdAt||void 0===o.createdAt?{}:{createdAt:o.createdAt},...void 0!==n.joinedAt||void 0===o.joinedAt?{}:{joinedAt:o.joinedAt}});if(a){this.persistJoinedGroupSnapshot(a);const t=s.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:o.name||t.name,avatarUrl:o.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void i.warn("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{i.warn("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=R(e),o=await this.getRestClient(t).request(S(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return A(o,r.targets)}async hydrateEntriesWithUsers(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t.map(e=>e.user));return t.map(e=>({...e,user:r.get(e.user.userId)??e.user}))}extractGroupNamecard(e){return e.groupNamecard??e.group_namecard??e.group_name_card??e.namecard}async hydrateGroupDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveGroupContextUserInfoMap(e.groupId,[e.owner]);return{...e,owner:t.get(e.owner.userId)??e.owner}}async hydrateGroupDetailsUsers(e){const t=e.filter(e=>Boolean(e.owner?.userId)).map(e=>({groupId:e.groupId,user:e.owner}));if(0===t.length)return e;const r=await this.resolveGroupUserInfoContexts(t);return e.map(e=>e.owner?.userId?{...e,owner:r.get(_(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),o=await w({groupId:e,users:t,includeNameCard:r,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return r&&this.dispatchFetchedUserInfoUpdates(o.fetchedUserInfos),o.usersById}async resolveGroupUserInfoContexts(e){const t=this.isGroupNamecardEnhancementEnabled(),r=await G({contexts:e,includeNameCard:t,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return t&&this.dispatchFetchedUserInfoUpdates(r.fetchedUserInfos),r.usersByContextKey}async fetchGroupUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}isGroupNamecardEnhancementEnabled(){const e=this.requireClient(),t=e.isUserInfoSyncEnabled;return"function"==typeof t&&t.call(e)}dispatchFetchedUserInfoUpdates(e){if(0===e.length)return;const t=this.requireClient(),r=t.getCurrentUserId(),o=e.find(e=>e.userId===r),s=e.filter(e=>e.userId!==r);o&&t.dispatchOwnInfoUpdated?.(o),t.dispatchUserInfoUpdated?.(s),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new pt(e)}};ct.key="groupManager";let mt=ct;export{oe as G,re as J,mt as a,Q as n};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{V as e,E as s}from"./common-BvlDAw4a.js";const t=t=>new e(`${t} must be a local paging cursor returned by SDK`,{code:s.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),n=(e,s,t)=>{const n=e+s;return n<t?String(n):""},a=e=>({...e}),r=e=>{const s=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),t=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:s,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:t,lastUpdate:t}},i=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,o=a=>{if(!Number.isInteger(a.pageSize)||a.pageSize<=0)throw new e("pageSize must be a positive integer",{code:s.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const r=((e,s)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw t(s);const n=Number.parseInt(e,10);if(!Number.isSafeInteger(n)||n<0)throw t(s);return n})(a.cursor,"cursor"),o=[];for(const e of a.items){if("chatRoom"===e.conversationType)continue;const s=i(e.remindType);s&&o.push({conversationId:e.conversationId,conversationType:e.conversationType,remindType:s})}return{conversations:o.slice(r,r+a.pageSize),cursor:n(r,a.pageSize,o.length)}},d=(e,s)=>e.marks.includes(s);export{r as a,d as h,o as q,a as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const e=require("./common-tHGz9VBk.cjs"),t=t=>new e.ValidationError(`${t} must be a local paging cursor returned by SDK`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),s=(e,t,s)=>{const n=e+t;return n<s?String(n):""},n=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null;exports.hasSessionMark=(e,t)=>e.marks.includes(t),exports.queryMutedConversationsFromSessionList=r=>{if(!Number.isInteger(r.pageSize)||r.pageSize<=0)throw new e.ValidationError("pageSize must be a positive integer",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const o=((e,s)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw t(s);const n=Number.parseInt(e,10);if(!Number.isSafeInteger(n)||n<0)throw t(s);return n})(r.cursor,"cursor"),i=[];for(const e of r.items){if("chatRoom"===e.conversationType)continue;const t=n(e.remindType);t&&i.push({conversationId:e.conversationId,conversationType:e.conversationType,remindType:t})}return{conversations:i.slice(o,o+r.pageSize),cursor:s(o,r.pageSize,i.length)}},exports.toConversationItem=e=>({...e}),exports.toConversationSummary=e=>{const t=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),s=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:s,lastUpdate:s}};
|