easemob-websdk 5.1.3 → 5.2.0

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.
Files changed (81) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/cache/cache-types.d.ts +2 -2
  3. package/chat-client.d.ts +17 -2
  4. package/chunks/chat-manager-BB7wYWYG.js +2 -0
  5. package/chunks/chat-manager-auF_3s3R.cjs +1 -0
  6. package/chunks/common-Cg-lTASK.cjs +1 -0
  7. package/chunks/common-gbNWJrBc.js +1 -0
  8. package/chunks/{group-user-info-resolver-B-dyr__b.cjs → group-user-info-resolver-BNwtC7dY.cjs} +1 -1
  9. package/chunks/{group-user-info-resolver-D6AQAHEE.js → group-user-info-resolver-rs5Fnr0l.js} +1 -1
  10. package/chunks/index-BUNbI8gf.cjs +1 -0
  11. package/chunks/index-BxMCMoWN.js +1 -0
  12. package/chunks/index-C7fO2X0x.cjs +1 -0
  13. package/chunks/index-C_EMU0-3.js +1 -0
  14. package/chunks/index-CsqE2tfH.js +1 -0
  15. package/chunks/index-DeJuR3uW.cjs +1 -0
  16. package/chunks/index-Dknccp9Q.js +1 -0
  17. package/chunks/index-P1vnLSK2.cjs +1 -0
  18. package/chunks/multibody-content-BHb-Au8Q.js +1 -0
  19. package/chunks/multibody-content-BmdQukoX.cjs +1 -0
  20. package/chunks/{push-manager-CSIKhoPe.js → push-manager-BO3xq-7O.js} +1 -1
  21. package/chunks/{push-manager-D7RDsKuv.cjs → push-manager-DMI0G9v9.cjs} +1 -1
  22. package/chunks/reflection-proto-codec-B1apL0ws.js +1 -0
  23. package/chunks/reflection-proto-codec-CYglS_mx.cjs +1 -0
  24. package/chunks/session-list-query-DMe2GZ4v.cjs +1 -0
  25. package/chunks/session-list-query-Inseic9m.js +1 -0
  26. package/chunks/{user-info-DH3aE1gm.cjs → user-info-B5St7axd.cjs} +1 -1
  27. package/chunks/{user-info-7QzMa7bR.js → user-info-BkqJHgja.js} +1 -1
  28. package/core/index.d.ts +1 -1
  29. package/core/message/attachment-downloader.d.ts +4 -1
  30. package/core/message/message-sender.d.ts +19 -4
  31. package/core/message/prepare-text-translation.d.ts +7 -0
  32. package/index.cjs +1 -1
  33. package/index.d.ts +3 -2
  34. package/index.js +2 -2
  35. package/managers/chat/index.cjs +1 -1
  36. package/managers/chat/index.js +1 -1
  37. package/managers/chat-manager.d.ts +128 -7
  38. package/managers/chat-thread/index.cjs +1 -1
  39. package/managers/chat-thread/index.js +1 -1
  40. package/managers/chatroom/index.cjs +1 -1
  41. package/managers/chatroom/index.js +1 -1
  42. package/managers/contact/index.cjs +1 -1
  43. package/managers/contact/index.js +1 -1
  44. package/managers/group/index.cjs +1 -1
  45. package/managers/group/index.js +1 -1
  46. package/managers/presence/index.cjs +1 -1
  47. package/managers/presence/index.js +1 -1
  48. package/managers/push/index.cjs +1 -1
  49. package/managers/push/index.js +1 -1
  50. package/managers/user-info/index.cjs +1 -1
  51. package/managers/user-info/index.js +1 -1
  52. package/message/combine-payload-codec.d.ts +2 -2
  53. package/message/combine-payload-file.d.ts +11 -0
  54. package/message/create-message.d.ts +16 -4
  55. package/message/create-multibody-message.d.ts +31 -0
  56. package/message/message-snapshot.d.ts +2 -1
  57. package/message/multibody-content.d.ts +35 -0
  58. package/message/translations.d.ts +7 -0
  59. package/package.json +1 -1
  60. package/platform/image/miniapp-image-processor.d.ts +10 -6
  61. package/protocol/msync/codec.d.ts +3 -0
  62. package/protocol/msync/message-payload-decoder.d.ts +5 -1
  63. package/protocol/session-list/payload-decoder.d.ts +2 -2
  64. package/types/chat-manager.d.ts +2 -2
  65. package/types/conversation.d.ts +2 -2
  66. package/types/index.d.ts +33 -9
  67. package/types/message-create.d.ts +130 -2
  68. package/upload/attachment-uploader.d.ts +8 -0
  69. package/validators/message-create.d.ts +25 -2
  70. package/chunks/chat-manager-BI-6bEor.cjs +0 -1
  71. package/chunks/chat-manager-nXOTpJ01.js +0 -2
  72. package/chunks/common-DHQukb7J.js +0 -1
  73. package/chunks/common-tHGz9VBk.cjs +0 -1
  74. package/chunks/index-CneY58NJ.js +0 -1
  75. package/chunks/index-DJPAjXAp.cjs +0 -1
  76. package/chunks/index-DtWkVcfb.cjs +0 -1
  77. package/chunks/index-DxjmfFL7.js +0 -1
  78. package/chunks/reflection-proto-codec-7r8Sei3y.js +0 -1
  79. package/chunks/reflection-proto-codec-CwrIKT1L.cjs +0 -1
  80. package/chunks/session-list-query-C3iQvQxK.cjs +0 -1
  81. package/chunks/session-list-query-Cdpiw_IZ.js +0 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/chat-manager-BI-6bEor.cjs");exports.ChatManager=e.ChatManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/chat-manager-auF_3s3R.cjs");exports.ChatManager=e.ChatManager;
@@ -1 +1 @@
1
- import{C as a}from"../../chunks/chat-manager-nXOTpJ01.js";export{a as ChatManager};
1
+ import{C as a}from"../../chunks/chat-manager-BB7wYWYG.js";export{a as ChatManager};
@@ -4,7 +4,7 @@
4
4
  import type { ChatClient } from '../chat-client';
5
5
  import type { ConversationFilter, ConversationItem, ConversationMarkParams, ConversationMarkMutationResult, ConversationMutationResult, DeleteConversationParams, GetPinnedMessageListParams, PinnedMessageListResult, PinMessageParams, RefreshSessionListParams, SetConversationPinnedParams } from '../types/conversation';
6
6
  import type { ChatEventHandlerMap, EventHandlerId } from '../types/event-system';
7
- import type { ChatActionResult, CreateCmdMessageParams, CreateCombineMessageParams, CreateCustomMessageParams, CreateFileMessageParams, CreateImageMessageParams, CreateLocationMessageParams, ClearConversationUnreadMessageCountParams, ConversationLocator, CreateTextMessageParams, CreateVideoMessageParams, CreateVoiceMessageParams, DownloadCombineMessageInput, DownloadAttachmentParams, GetGroupMessageReadReceiptsParams, GetHistoryMessagesParams, GetReactionDetailParams, GetReactionListParams, GroupMessageReadUsersParams, GroupMessageReadUsersResult, Message, MessageAttachmentDownloadResult, MessageHistoryPage, MessageReadReceiptDetail, MessageReactionDetailPage, MessageReactionListItem, MessageTranslationResult, RecallMessageParams, ReactionOperationParams, RemoveHistoryMessagesParams, SearchMessagesParams, SearchMessagesResult, SendMessageReadReceiptsParams, SendMessageOptions, TranslationLanguage, TranslateMessageParams, UpdateMessageParams, VoiceMessageBody, VoiceParams, VoiceSourceFile, VoiceToTextResult } from '../types';
7
+ import type { ChatActionResult, CreateCmdMessageParams, CreateCombineMessageParams, CreateCustomMessageParams, CreateFileMessageParams, CreateImageMessageParams, CreateLocationMessageParams, ClearConversationUnreadMessageCountParams, ConversationLocator, CreateTextMessageParams, CreateVideoMessageParams, CreateVoiceMessageParams, CreateMultiBodyMessageParams, CreateCustomMessageBodyParams, CreateFileMessageBodyParams, CreateImageMessageBodyParams, CreateLocationMessageBodyParams, CreateTextMessageBodyParams, CreateVideoMessageBodyParams, CreateVoiceMessageBodyParams, MultiBodySegment, DownloadCombineMessageInput, DownloadAttachmentParams, GetGroupMessageReadReceiptsParams, GetHistoryMessagesParams, GetReactionDetailParams, GetReactionListParams, GroupMessageReadUsersParams, GroupMessageReadUsersResult, Message, MessageAttachmentDownloadResult, MessageHistoryPage, MessageReadReceiptDetail, MessageReactionDetailPage, MessageReactionListItem, MessageTranslationResult, RecallMessageParams, ReactionOperationParams, RemoveHistoryMessagesParams, SearchMessagesParams, SearchMessagesResult, SendMessageReadReceiptsParams, SendMessageOptions, TranslationLanguage, TranslateMessageParams, UpdateMessageParams, VoiceMessageBody, VoiceParams, VoiceSourceFile, VoiceToTextResult } from '../types';
8
8
  import type { ManagerBase, ManagerEventContext } from '../types/manager';
9
9
  /**
10
10
  * ChatManager 负责消息域动作、查询与事件订阅
@@ -38,11 +38,14 @@ export declare class ChatManager implements ManagerBase<ChatClient> {
38
38
  * 事件触发:接收方(含发送方的其他设备)会收到 `onMessage` 事件。
39
39
  * 附件类消息(图片/文件/语音/视频)会先自动上传到服务器,上传成功后再发送。
40
40
  *
41
+ * 文本消息指定非空 `body.targetLanguages` 时,先调用翻译服务,再发送原文与 `body.translations`;翻译失败则不发送,并通过 Promise 与 `onFailed` 返回翻译错误。发送结果和回调包含译文,传入消息对象不被修改。未指定语言时不调用翻译服务。
41
42
  * [en-US] Sends a created message. Text, image, file, voice, video, location, command, custom, and combined messages are all sent via this API.
42
43
  *
43
44
  * Event triggered: Recipients (including the sender's other logged-in devices) receive the `onMessage` event.
44
45
  * For attachment messages such as image, file, voice, and video messages, the SDK automatically uploads the attachment before sending the message.
45
46
  *
47
+ * Text messages with non-empty `body.targetLanguages` are translated before sending the original text and `body.translations`. Translation failure prevents sending and is reported through the Promise and `onFailed`. Results and callbacks contain translations without mutating the input message. No translation request is made when target languages are omitted.
48
+ *
46
49
  * @example
47
50
  * ```ts
48
51
  * const message = chatManager.createTextMessage({
@@ -218,6 +221,120 @@ export declare class ChatManager implements ManagerBase<ChatClient> {
218
221
  * @returns [zh-CN] 合并消息对象。 [en-US] The combined message object.
219
222
  */
220
223
  createCombineMessage(params: CreateCombineMessageParams): Message;
224
+ /**
225
+ * [zh-CN] 创建复合消息的文本分段。返回的对象必须原样放进 `createMultiBodyMessage`。
226
+ * [en-US] Creates a text segment for a multi_body message. Pass the returned object unchanged to `createMultiBodyMessage`.
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * const text = chatManager.createTextMessageBody({ content: '请看资料' });
231
+ * ```
232
+ *
233
+ * @param params - [zh-CN] 文本分段参数。 [en-US] Text segment parameters.
234
+ * @returns [zh-CN] 带 `type: 'text'` 的分段。 [en-US] A segment with `type: 'text'`.
235
+ */
236
+ createTextMessageBody(params: CreateTextMessageBodyParams): MultiBodySegment;
237
+ /**
238
+ * [zh-CN] 创建复合消息的图片分段。本地文件挂在返回对象上,不能复制后再组装。
239
+ * [en-US] Creates an image segment. A local file stays attached to the returned object and the object must not be copied before assembly.
240
+ *
241
+ * @example
242
+ * ```ts
243
+ * const image = chatManager.createImageMessageBody({ originalUrl: 'https://example.com/a.jpg' });
244
+ * ```
245
+ *
246
+ * @param params - [zh-CN] 图片分段参数。`data` 与 `originalUrl` 至少传一个。 [en-US] Image segment parameters. Either `data` or `originalUrl` is required.
247
+ * @returns [zh-CN] 带 `type: 'image'` 的分段。 [en-US] A segment with `type: 'image'`.
248
+ */
249
+ createImageMessageBody(params: CreateImageMessageBodyParams): MultiBodySegment;
250
+ /**
251
+ * [zh-CN] 创建复合消息的文件分段。
252
+ * [en-US] Creates a file segment for a multi_body message.
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * const file = chatManager.createFileMessageBody({ originalUrl: 'https://example.com/a.txt' });
257
+ * ```
258
+ *
259
+ * @param params - [zh-CN] 文件分段参数。`data` 与 `originalUrl` 至少传一个。 [en-US] File segment parameters. Either `data` or `originalUrl` is required.
260
+ * @returns [zh-CN] 带 `type: 'file'` 的分段。 [en-US] A segment with `type: 'file'`.
261
+ */
262
+ createFileMessageBody(params: CreateFileMessageBodyParams): MultiBodySegment;
263
+ /**
264
+ * [zh-CN] 创建复合消息的语音分段。
265
+ * [en-US] Creates a voice segment for a multi_body message.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * const voice = chatManager.createVoiceMessageBody({
270
+ * originalUrl: 'https://example.com/a.amr',
271
+ * duration: 3,
272
+ * });
273
+ * ```
274
+ *
275
+ * @param params - [zh-CN] 语音分段参数。 [en-US] Voice segment parameters.
276
+ * @returns [zh-CN] 带 `type: 'voice'` 的分段。 [en-US] A segment with `type: 'voice'`.
277
+ */
278
+ createVoiceMessageBody(params: CreateVoiceMessageBodyParams): MultiBodySegment;
279
+ /**
280
+ * [zh-CN] 创建复合消息的视频分段。
281
+ * [en-US] Creates a video segment for a multi_body message.
282
+ *
283
+ * @example
284
+ * ```ts
285
+ * const video = chatManager.createVideoMessageBody({
286
+ * originalUrl: 'https://example.com/a.mp4',
287
+ * duration: 8,
288
+ * });
289
+ * ```
290
+ *
291
+ * @param params - [zh-CN] 视频分段参数。 [en-US] Video segment parameters.
292
+ * @returns [zh-CN] 带 `type: 'video'` 的分段。 [en-US] A segment with `type: 'video'`.
293
+ */
294
+ createVideoMessageBody(params: CreateVideoMessageBodyParams): MultiBodySegment;
295
+ /**
296
+ * [zh-CN] 创建复合消息的位置分段。
297
+ * [en-US] Creates a location segment for a multi_body message.
298
+ *
299
+ * @example
300
+ * ```ts
301
+ * const location = chatManager.createLocationMessageBody({ latitude: 39.9, longitude: 116.4 });
302
+ * ```
303
+ *
304
+ * @param params - [zh-CN] 位置分段参数。 [en-US] Location segment parameters.
305
+ * @returns [zh-CN] 带 `type: 'location'` 的分段。 [en-US] A segment with `type: 'location'`.
306
+ */
307
+ createLocationMessageBody(params: CreateLocationMessageBodyParams): MultiBodySegment;
308
+ /**
309
+ * [zh-CN] 创建复合消息的自定义分段。
310
+ * [en-US] Creates a custom segment for a multi_body message.
311
+ *
312
+ * @example
313
+ * ```ts
314
+ * const custom = chatManager.createCustomMessageBody({ event: 'gift', params: { id: '1' } });
315
+ * ```
316
+ *
317
+ * @param params - [zh-CN] 自定义分段参数。 [en-US] Custom segment parameters.
318
+ * @returns [zh-CN] 带 `type: 'custom'` 的分段。 [en-US] A segment with `type: 'custom'`.
319
+ */
320
+ createCustomMessageBody(params: CreateCustomMessageBodyParams): MultiBodySegment;
321
+ /**
322
+ * [zh-CN] 把 2 到 20 段内容组装成一条复合消息。分段必须是工厂返回的同一对象。少于 2 段、超过 20 段,或含命令、合并、复合消息、流式内容时抛出校验错误,且不挪走本地文件。
323
+ * [en-US] Assembles 2 to 20 segments into one multi_body message. Segments must be the same objects returned by the factories. Fewer than two segments, more than 20 segments, or command, combined, multi_body, or stream content, throws a validation error and does not move local files.
324
+ *
325
+ * @example
326
+ * ```ts
327
+ * const message = chatManager.createMultiBodyMessage({
328
+ * conversationId: 'user_2',
329
+ * conversationType: 'singleChat',
330
+ * bodies: [text, image],
331
+ * });
332
+ * ```
333
+ *
334
+ * @param params - [zh-CN] 复合消息参数。`bodies` 为 2 到 20 项。 [en-US] MultiBody message parameters. `bodies` must contain 2 to 20 segments.
335
+ * @returns [zh-CN] 类型为 `multi_body` 的消息。 [en-US] A message whose type is `multi_body`.
336
+ */
337
+ createMultiBodyMessage(params: CreateMultiBodyMessageParams): Message;
221
338
  /**
222
339
  * [zh-CN] 从本地会话列表缓存中获取会话,支持通过 filter 过滤。
223
340
  * [en-US] Retrieves conversations from the local conversation list cache, with support for filtering via a `filter`.
@@ -563,12 +680,12 @@ export declare class ChatManager implements ManagerBase<ChatClient> {
563
680
  */
564
681
  recallMessage(params: RecallMessageParams): Promise<ChatActionResult>;
565
682
  /**
566
- * [zh-CN] 编辑一条消息内容。当前仅支持文本消息和自定义消息。
683
+ * [zh-CN] 编辑一条消息内容。文本消息可修改 `content` 和 `ext`;`body.targetLanguages` 非空时先翻译再编辑,译文写入 `body.translations`,翻译失败则抛出异常且不发送编辑。自定义消息可修改 `event`、`params` 和 `ext`;图片、语音、视频、文件、位置和合并消息仅可修改 `ext`。命令消息和复合消息不支持编辑。
567
684
  *
568
685
  * 事件触发:除当前操作设备外,会话成员及编辑者的其他设备会收到 `onMessageUpdated`;当前操作设备通过 Promise 处理成功结果。
569
686
  * 注意:最多编辑 10 次;编辑后消息漫游有效期重新计算。
570
687
  *
571
- * [en-US] Edits the content of a sent message. Currently, only text messages and custom messages are supported.
688
+ * [en-US] Edits the content of a sent message. Text messages can change `content` and `ext`. Non-empty `body.targetLanguages` are translated before the edit, stored in `body.translations`, and a translation failure throws without sending the edit. Custom messages can change `event`, `params`, and `ext`. Image, voice, video, file, location, and combined messages can change `ext` only. Command and multi_body messages cannot be edited.
572
689
  *
573
690
  * Event triggered: Conversation members and the editor's other devices, except the operating device, receive `onMessageUpdated`. The operating device handles success through the Promise.
574
691
  * Note: Each message can be edited up to 10 times. After a message is edited, the validity period of message roaming is recalculated.
@@ -627,8 +744,8 @@ export declare class ChatManager implements ManagerBase<ChatClient> {
627
744
  */
628
745
  searchMessages(params: SearchMessagesParams): Promise<SearchMessagesResult>;
629
746
  /**
630
- * [zh-CN] 下载消息附件,适用于图片、语音、视频和文件等附件消息。
631
- * [en-US] Downloads a message attachment. This method applies to attachment messages such as image, voice, video, and file messages.
747
+ * [zh-CN] 下载消息附件,适用于图片、语音、视频、文件和复合消息。复合消息会按分段顺序下载全部图片、语音、视频和文件。
748
+ * [en-US] Downloads a message attachment. This applies to image, voice, video, file, and multi_body messages. A multi_body message downloads every image, voice, video, and file segment in order.
632
749
  *
633
750
  * @example
634
751
  * ```ts
@@ -636,9 +753,9 @@ export declare class ChatManager implements ManagerBase<ChatClient> {
636
753
  * ```
637
754
  *
638
755
  * @param params - [zh-CN] 附件下载参数。 [en-US] Parameters for downloading an attachment.
639
- * @returns [zh-CN] 附件下载结果。 [en-US] Attachment download result.
756
+ * @returns [zh-CN] 普通附件消息返回单个下载结果。复合消息返回全部附件下载结果。 [en-US] Returns one download result for a regular attachment message, or every attachment result for a multi_body message.
640
757
  */
641
- downloadAttachment(params: DownloadAttachmentParams): Promise<MessageAttachmentDownloadResult>;
758
+ downloadAttachment(params: DownloadAttachmentParams): Promise<MessageAttachmentDownloadResult | ReadonlyArray<MessageAttachmentDownloadResult>>;
642
759
  /**
643
760
  * [zh-CN] 下载并解析合并消息内容,返回合并消息中的子消息列表。
644
761
  * [en-US] Downloads and parses a combined message, returning the original messages within it.
@@ -810,8 +927,11 @@ export declare class ChatManager implements ManagerBase<ChatClient> {
810
927
  getSupportedTranslationLanguages(): Promise<ReadonlyArray<TranslationLanguage>>;
811
928
  /**
812
929
  * [zh-CN] 翻译文本消息内容到一个或多个目标语言。
930
+ * 适用于发送前或收到后的普通文本消息;仅返回翻译结果,不修改传入消息、不更新业务消息缓存。调用方可将 `result.translations` 转成语言到译文的映射用于展示。自动发送翻译请在创建消息时指定 `targetLanguages`。
813
931
  * [en-US] Translates the content of a text message into one or more target languages.
814
932
  *
933
+ * Supports ordinary text messages before sending or after receipt. Only returns translation results; it does not mutate the input message or update application message caches. Callers can map `result.translations` by language for display. Set `targetLanguages` when creating a message to translate automatically on send.
934
+ *
815
935
  * @example
816
936
  * ```ts
817
937
  * const result = await chatManager.translateMessage({
@@ -867,6 +987,7 @@ export declare class ChatManager implements ManagerBase<ChatClient> {
867
987
  private buildValidationError;
868
988
  private getEventContextOrThrow;
869
989
  private getClientOrThrow;
990
+ private prepareEditedTextBody;
870
991
  private getRestContextOrThrow;
871
992
  private getRestClient;
872
993
  private requireConnectedClient;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-tHGz9VBk.cjs"),t=require("../../chunks/cache-utils-gowrxNr8.cjs"),r=require("../../chunks/query-params-BHyPuD2k.cjs");class a{constructor(e,t){this.chatThreadId=e,this.manager=t}getInfo(){return this.manager.getChatThreadInfo({chatThreadId:this.chatThreadId})}refresh(){return this.getInfo()}join(){return this.manager.joinChatThread({chatThreadId:this.chatThreadId})}leave(){return this.manager.leaveChatThread({chatThreadId:this.chatThreadId})}destroy(){return this.manager.destroyChatThread({chatThreadId:this.chatThreadId})}updateName(e){return this.manager.updateChatThreadName({chatThreadId:this.chatThreadId,name:e.name})}getMemberList(e={}){return this.manager.getChatThreadMemberList({chatThreadId:this.chatThreadId,...e})}removeMember(e){return this.manager.removeChatThreadMember({chatThreadId:this.chatThreadId,memberId:e.memberId})}}const s=t=>new e.ValidationError(`${t} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),o=(t,r)=>new e.ValidationError(r,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:r,rule:"invalid_format"}]}}),n=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw s(t);return e.trim()},i=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw o(t,`${t} must be a string`);return e},d=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw o(t,`${t} must be an integer between 1 and 50`);return e},h=t=>{const{orgName:r,appName:a}=e.parseAppKey(t.appKey);return{orgName:r,appName:a,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},u=e=>t.isRecord(e)?e:null,c=e=>{const t=u(e);return t?.data??e},l=e=>{const t=u(e);if(Array.isArray(t?.entities))return t.entities;const r=c(e);if(Array.isArray(r))return r;const a=u(r);return Array.isArray(a?.entities)?a.entities:Array.isArray(a?.affiliations)?a.affiliations:[]},p=e=>{const t=u(e),r=u(t?.data),a=u(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof a?.cursor?a.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},m=e=>{const r=u(e);if(!r)return null;const a=("string"==typeof r.id?r.id:void 0)??("string"==typeof r.msgId?r.msgId:void 0);if(!a)return null;const s="number"==typeof r.timestamp?r.timestamp:0,o=r.payload,n="string"==typeof o?t.safeJsonParse(o,{}):u(o)??{},i=Array.isArray(n.bodies)?n.bodies:[],d=u(i[0])??{};return{msgId:a,type:("string"==typeof d.type?d.type:void 0)??("string"==typeof n.type?n.type:void 0)??"",body:d,timestamp:s}},g=e=>{const t=u(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0)??("string"==typeof t.chatThreadId?t.chatThreadId:void 0),a=("string"==typeof t.parentId?t.parentId:void 0)??("string"==typeof t.groupId?t.groupId:void 0)??("string"==typeof t.group_id?t.group_id:void 0),s="string"==typeof t.name?t.name:"";return r&&a&&s?{chatThreadId:r,parentId:a,name:s,ownerId:"string"==typeof t.owner?t.owner:void 0,memberCount:"number"==typeof t.affiliationsCount?t.affiliationsCount:"number"==typeof t.affiliations_count?t.affiliations_count:void 0,messageCount:"number"==typeof t.messageCount?t.messageCount:"number"==typeof t.message_count?t.message_count:void 0,createdAt:"number"==typeof t.created?t.created:"number"==typeof t.createTimestamp?t.createTimestamp:void 0,lastMessage:m(t.lastMessage??t.last_message)}:null},_=e=>({items:l(e).map(e=>g(e)).filter(e=>null!==e),cursor:p(e)}),y=async(e,t,r)=>{const a=h(t),s=n(r,"chatThreadId");return(e=>{const t=c(e),r=Array.isArray(t)?t[0]:t,a=g(r);if(!a)throw o("response.data","response.data is invalid");return a})(await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}`,{operation:"getChatThreadInfo"}))},T=async(e,t,a)=>{const s=h(t),o=n(a.chatThreadId,"params.chatThreadId"),c=d(a.pageSize,"params.pageSize"),m=i(a.cursor,"params.cursor"),g=r.createQueryParams({limit:String(c),cursor:m}),_=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(o)}/users?${g.toString()}`,{operation:"getChatThreadMemberList"});return{items:l(y=_).map(e=>{if("string"==typeof e)return{memberId:e};const t=u(e);if(!t)return null;const r=("string"==typeof t.memberId?t.memberId:void 0)??("string"==typeof t.user?t.user:void 0)??("string"==typeof t.username?t.username:void 0);return r?{memberId:r,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null}).filter(e=>null!==e),cursor:p(y)};var y},v=async(e,t,r)=>{const a=h(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw s("params.chatThreadIds");if(r.chatThreadIds.length>20)throw o("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const i=r.chatThreadIds.map((e,t)=>n(e,`params.chatThreadIds[${t}]`)),d=await e.post(`/${a.orgName}/${a.appName}/thread/message`,{threadIds:i},{operation:"getChatThreadLastMessageList"});return{items:l(d).map(e=>{const t=u(e);if(!t)return null;const r=("string"==typeof t.chatThreadId?t.chatThreadId:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0);return r?{chatThreadId:r,lastMessage:m(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},f=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{createChatThread:{range:"4,110,201,210,301,303,606",localErrors:{createChatThread:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getJoinedChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getJoinedChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadInfo:{range:"110,201,210,301,303,606",localErrors:{getChatThreadInfo:{validation_invalid:{code:110,retryable:!1}},getInfo:{validation_invalid:{code:110,retryable:!1}},refresh:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},joinChatThread:{range:"4,110,201,210,301,303,606",localErrors:{joinChatThread:{validation_invalid:{code:110,retryable:!1}},join:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},leaveChatThread:{range:"110,201,210,301,303,606",localErrors:{leaveChatThread:{validation_invalid:{code:110,retryable:!1}},leave:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},destroyChatThread:{range:"110,201,210,301,303,606",localErrors:{destroyChatThread:{validation_invalid:{code:110,retryable:!1}},destroy:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},updateChatThreadName:{range:"110,201,210,301,303,606",localErrors:{updateChatThreadName:{validation_invalid:{code:110,retryable:!1}},updateName:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadMemberList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadMemberList:{validation_invalid:{code:110,retryable:!1}},getMemberList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},removeChatThreadMember:{range:"110,201,210,301,303,606",localErrors:{removeChatThreadMember:{validation_invalid:{code:110,retryable:!1}},removeMember:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadLastMessageList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadLastMessageList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}}}}),b=class{constructor(){this.capabilities=["rawNotify:chatThread"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.registry=new Map}bind(e,t){this.client=e,this.eventContext=t??null,this.registry.clear()}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}handleRawNotify(e){if("chatThread"!==e.type)return;const t=this.buildChatThreadPublicEvent(e.payload);t&&this.eventContext?.dispatch?.(t.eventName,t.payload)}getChatThread(t){const r=t.trim();if(0===r.length)throw new e.ValidationError("chatThreadId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const s=this.registry.get(r);if(s)return s;const o=new a(r,this);return this.registry.set(r,o),o}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=h(t),s=n(r.parentId,"params.parentId"),i=n(r.name,"params.name"),d=n(r.messageId,"params.messageId"),l=await e.post(`/${a.orgName}/${a.appName}/thread?resource=${a.encodedResource}`,{name:i,msg_id:d,group_id:s,owner:t.userId},{operation:"createChatThread"}),p=u(c(l)),m="string"==typeof p?.thread_id?p.thread_id:void 0;if(!m)throw o("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:m}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,a)=>{const s=h(t),o=n(a.parentId,"params.parentId"),u=d(a.pageSize,"params.pageSize"),c=i(a.cursor,"params.cursor"),l=r.createQueryParams({limit:String(u),cursor:c}),p=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(o)}?${l.toString()}`,{operation:"getChatThreadList"});return _(p)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,a={})=>{const s=h(t),o=d(a.pageSize,"params.pageSize"),n=i(a.cursor,"params.cursor"),u=r.createQueryParams({limit:String(o),cursor:n}),c="string"==typeof a.parentId&&a.parentId.trim().length>0?`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(a.parentId.trim())}/user/${s.encodedUserId}?${u.toString()}`:`/${s.orgName}/${s.appName}/threads/user/${s.encodedUserId}?${u.toString()}`,l=await e.get(c,{operation:"getJoinedChatThreadList"});return _(l)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return y(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=h(t),s=n(r,"chatThreadId");await e.post(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/user/${a.encodedUserId}/join?resource=${a.encodedResource}`,void 0,{operation:"joinChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async leaveChatThread(e){return this.runOperation("leaveChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=h(t),s=n(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/user/${a.encodedUserId}/quit?resource=${a.encodedResource}`,{operation:"leaveChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async destroyChatThread(e){return this.runOperation("destroyChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=h(t),s=n(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{operation:"destroyChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async updateChatThreadName(e){return this.runOperation("updateChatThreadName",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=h(t),s=n(r.chatThreadId,"params.chatThreadId"),o=n(r.name,"params.name");await e.put(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{name:o},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return T(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=h(t),s=n(r.chatThreadId,"params.chatThreadId"),o=n(r.memberId,"params.memberId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/users/${encodeURIComponent(o)}?resource=${a.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return v(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new e.ValidationError("ChatThreadManager is not bound to client",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.client",message:"ChatThreadManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getEventContextOrThrow(){if(!this.eventContext)throw new e.ValidationError("ChatThreadManager is not bound to event context",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:f,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}async runOperation(t,r){try{return await r()}catch(a){if(a instanceof e.SDKError)throw a;const r=a instanceof Error?a.message:String(a);throw new e.SDKError(`ChatThreadManager ${t} failed: ${r}`,e.ERROR_CODES.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",a="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!a)return null;const s="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,o="string"==typeof t.name?t.name:void 0,n="number"==typeof t.message_count?t.message_count:void 0,i=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,d="number"==typeof t.timestamp?t.timestamp:0,h="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:a,name:o??"",messageId:s,messageCount:n,lastMessage:i};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:o,messageId:s,thread:u,timestamp:d}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:o,messageId:s,messageCount:n,lastMessage:i,thread:u,timestamp:d}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:a,operatorId:h,timestamp:d}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:a,operatorId:h,memberId:t.userIds?.[0],timestamp:d}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};b.key="chatThreadManager";let C=b;exports.ChatThread=a,exports.ChatThreadManager=C;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-BUNbI8gf.cjs");exports.ChatThread=e.ChatThread,exports.ChatThreadManager=e.ChatThreadManager;
@@ -1 +1 @@
1
- import{p as e,V as t,E as r,R as a,S as s,m as o,C as n}from"../../chunks/common-DHQukb7J.js";import{i,s as d}from"../../chunks/cache-utils-B99glc0H.js";import{c as h}from"../../chunks/query-params-Bu3Xq4b6.js";class u{constructor(e,t){this.chatThreadId=e,this.manager=t}getInfo(){return this.manager.getChatThreadInfo({chatThreadId:this.chatThreadId})}refresh(){return this.getInfo()}join(){return this.manager.joinChatThread({chatThreadId:this.chatThreadId})}leave(){return this.manager.leaveChatThread({chatThreadId:this.chatThreadId})}destroy(){return this.manager.destroyChatThread({chatThreadId:this.chatThreadId})}updateName(e){return this.manager.updateChatThreadName({chatThreadId:this.chatThreadId,name:e.name})}getMemberList(e={}){return this.manager.getChatThreadMemberList({chatThreadId:this.chatThreadId,...e})}removeMember(e){return this.manager.removeChatThreadMember({chatThreadId:this.chatThreadId,memberId:e.memberId})}}const c=e=>new t(`${e} is required`,{code:r.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),l=(e,a)=>new t(a,{code:r.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:a,rule:"invalid_format"}]}}),p=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw c(t);return e.trim()},m=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw l(t,`${t} must be a string`);return e},g=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw l(t,`${t} must be an integer between 1 and 50`);return e},_=t=>{const{orgName:r,appName:a}=e(t.appKey);return{orgName:r,appName:a,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},y=e=>i(e)?e:null,T=e=>{const t=y(e);return t?.data??e},v=e=>{const t=y(e);if(Array.isArray(t?.entities))return t.entities;const r=T(e);if(Array.isArray(r))return r;const a=y(r);return Array.isArray(a?.entities)?a.entities:Array.isArray(a?.affiliations)?a.affiliations:[]},f=e=>{const t=y(e),r=y(t?.data),a=y(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof a?.cursor?a.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},b=e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const a="number"==typeof t.timestamp?t.timestamp:0,s=t.payload,o="string"==typeof s?d(s,{}):y(s)??{},n=Array.isArray(o.bodies)?o.bodies:[],i=y(n[0])??{};return{msgId:r,type:("string"==typeof i.type?i.type:void 0)??("string"==typeof o.type?o.type:void 0)??"",body:i,timestamp:a}},I=e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0)??("string"==typeof t.chatThreadId?t.chatThreadId:void 0),a=("string"==typeof t.parentId?t.parentId:void 0)??("string"==typeof t.groupId?t.groupId:void 0)??("string"==typeof t.group_id?t.group_id:void 0),s="string"==typeof t.name?t.name:"";return r&&a&&s?{chatThreadId:r,parentId:a,name:s,ownerId:"string"==typeof t.owner?t.owner:void 0,memberCount:"number"==typeof t.affiliationsCount?t.affiliationsCount:"number"==typeof t.affiliations_count?t.affiliations_count:void 0,messageCount:"number"==typeof t.messageCount?t.messageCount:"number"==typeof t.message_count?t.message_count:void 0,createdAt:"number"==typeof t.created?t.created:"number"==typeof t.createTimestamp?t.createTimestamp:void 0,lastMessage:b(t.lastMessage??t.last_message)}:null},C=e=>({items:v(e).map(e=>I(e)).filter(e=>null!==e),cursor:f(e)}),N=async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");return(e=>{const t=T(e),r=Array.isArray(t)?t[0]:t,a=I(r);if(!a)throw l("response.data","response.data is invalid");return a})(await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}`,{operation:"getChatThreadInfo"}))},w=async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=g(r.pageSize,"params.pageSize"),n=m(r.cursor,"params.cursor"),i=h({limit:String(o),cursor:n}),d=await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/users?${i.toString()}`,{operation:"getChatThreadMemberList"});return{items:v(u=d).map(e=>{if("string"==typeof e)return{memberId:e};const t=y(e);if(!t)return null;const r=("string"==typeof t.memberId?t.memberId:void 0)??("string"==typeof t.user?t.user:void 0)??("string"==typeof t.username?t.username:void 0);return r?{memberId:r,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null}).filter(e=>null!==e),cursor:f(u)};var u},S=async(e,t,r)=>{const a=_(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw c("params.chatThreadIds");if(r.chatThreadIds.length>20)throw l("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const s=r.chatThreadIds.map((e,t)=>p(e,`params.chatThreadIds[${t}]`)),o=await e.post(`/${a.orgName}/${a.appName}/thread/message`,{threadIds:s},{operation:"getChatThreadLastMessageList"});return{items:v(o).map(e=>{const t=y(e);if(!t)return null;const r=("string"==typeof t.chatThreadId?t.chatThreadId:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0);return r?{chatThreadId:r,lastMessage:b(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},R=o(n,{common:{},apis:{createChatThread:{range:"4,110,201,210,301,303,606",localErrors:{createChatThread:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getJoinedChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getJoinedChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadInfo:{range:"110,201,210,301,303,606",localErrors:{getChatThreadInfo:{validation_invalid:{code:110,retryable:!1}},getInfo:{validation_invalid:{code:110,retryable:!1}},refresh:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},joinChatThread:{range:"4,110,201,210,301,303,606",localErrors:{joinChatThread:{validation_invalid:{code:110,retryable:!1}},join:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},leaveChatThread:{range:"110,201,210,301,303,606",localErrors:{leaveChatThread:{validation_invalid:{code:110,retryable:!1}},leave:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},destroyChatThread:{range:"110,201,210,301,303,606",localErrors:{destroyChatThread:{validation_invalid:{code:110,retryable:!1}},destroy:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},updateChatThreadName:{range:"110,201,210,301,303,606",localErrors:{updateChatThreadName:{validation_invalid:{code:110,retryable:!1}},updateName:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadMemberList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadMemberList:{validation_invalid:{code:110,retryable:!1}},getMemberList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},removeChatThreadMember:{range:"110,201,210,301,303,606",localErrors:{removeChatThreadMember:{validation_invalid:{code:110,retryable:!1}},removeMember:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadLastMessageList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadLastMessageList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}}}}),O=class{constructor(){this.capabilities=["rawNotify:chatThread"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.registry=/* @__PURE__ */new Map}bind(e,t){this.client=e,this.eventContext=t??null,this.registry.clear()}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}handleRawNotify(e){if("chatThread"!==e.type)return;const t=this.buildChatThreadPublicEvent(e.payload);t&&this.eventContext?.dispatch?.(t.eventName,t.payload)}getChatThread(e){const a=e.trim();if(0===a.length)throw new t("chatThreadId is required",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const s=this.registry.get(a);if(s)return s;const o=new u(a,this);return this.registry.set(a,o),o}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=_(t),s=p(r.parentId,"params.parentId"),o=p(r.name,"params.name"),n=p(r.messageId,"params.messageId"),i=await e.post(`/${a.orgName}/${a.appName}/thread?resource=${a.encodedResource}`,{name:o,msg_id:n,group_id:s,owner:t.userId},{operation:"createChatThread"}),d=y(T(i)),h="string"==typeof d?.thread_id?d.thread_id:void 0;if(!h)throw l("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:h}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=_(t),s=p(r.parentId,"params.parentId"),o=g(r.pageSize,"params.pageSize"),n=m(r.cursor,"params.cursor"),i=h({limit:String(o),cursor:n}),d=await e.get(`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(s)}?${i.toString()}`,{operation:"getChatThreadList"});return C(d)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const a=_(t),s=g(r.pageSize,"params.pageSize"),o=m(r.cursor,"params.cursor"),n=h({limit:String(s),cursor:o}),i="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${a.encodedUserId}?${n.toString()}`:`/${a.orgName}/${a.appName}/threads/user/${a.encodedUserId}?${n.toString()}`,d=await e.get(i,{operation:"getJoinedChatThreadList"});return C(d)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return N(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.post(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/user/${a.encodedUserId}/join?resource=${a.encodedResource}`,void 0,{operation:"joinChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async leaveChatThread(e){return this.runOperation("leaveChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/user/${a.encodedUserId}/quit?resource=${a.encodedResource}`,{operation:"leaveChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async destroyChatThread(e){return this.runOperation("destroyChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{operation:"destroyChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async updateChatThreadName(e){return this.runOperation("updateChatThreadName",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=p(r.name,"params.name");await e.put(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{name:o},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return w(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=_(t),s=p(r.chatThreadId,"params.chatThreadId"),o=p(r.memberId,"params.memberId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/users/${encodeURIComponent(o)}?resource=${a.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return S(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new t("ChatThreadManager is not bound to client",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.client",message:"ChatThreadManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getEventContextOrThrow(){if(!this.eventContext)throw new t("ChatThreadManager is not bound to event context",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new a(e.restBaseUrl,{errorMap:R,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}async runOperation(e,t){try{return await t()}catch(a){if(a instanceof s)throw a;const t=a instanceof Error?a.message:String(a);throw new s(`ChatThreadManager ${e} failed: ${t}`,r.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",a="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!a)return null;const s="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,o="string"==typeof t.name?t.name:void 0,n="number"==typeof t.message_count?t.message_count:void 0,i=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,d="number"==typeof t.timestamp?t.timestamp:0,h="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:a,name:o??"",messageId:s,messageCount:n,lastMessage:i};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:o,messageId:s,thread:u,timestamp:d}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:o,messageId:s,messageCount:n,lastMessage:i,thread:u,timestamp:d}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:a,operatorId:h,timestamp:d}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:a,operatorId:h,memberId:t.userIds?.[0],timestamp:d}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};O.key="chatThreadManager";let $=O;export{u as ChatThread,$ as ChatThreadManager};
1
+ import{m as a,n as r}from"../../chunks/index-Dknccp9Q.js";export{a as ChatThread,r as ChatThreadManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-tHGz9VBk.cjs"),t=require("../../chunks/event-system-TYhmgy4K.cjs"),r=require("../../chunks/query-params-BHyPuD2k.cjs"),o=require("../../chunks/cache-utils-gowrxNr8.cjs"),a=require("../../chunks/user-info-DH3aE1gm.cjs");class s{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const n=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],i=e=>{const t=[],r=new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},c=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),m=e=>({userId:e}),u=(e,t,r)=>{const o={userId:r};for(const a of n){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},h=async(e,t)=>{const r=i(e),o=new Map;if(0===r.length)return o;const a=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const n of a)o.set(n.userId,c(n));const s=r.filter(e=>!o.has(e));if(s.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:s});for(const t of e)o.set(t.userId,t)}for(const n of r)o.has(n)||o.set(n,m(n));return o},d=e=>o.isRecord(e)?e:null,l=e=>"string"==typeof e?e:void 0,R=e=>{const t=l(e)?.trim();return t||void 0},p=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}},g=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},I=e=>{const t=d(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},y=e=>{const t=d(e);return t?d(t.data)?t.data:t:null},C=(e,t)=>{const r=d(e),o=r&&d(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return p(a[0])},f=e=>R(e.chatRoomId)??R(e.chatroomid)??R(e.id)??"",b=e=>l(e.name)??l(e.title)??l(e.groupname)??"",_=e=>m(e),w=(e,t)=>{const r=(e=>{const t=l(e);return"owner"===t||"admin"===t||"member"===t||"none"===t?t:void 0})(e.permission);if(void 0!==r)return r;if(!t)return;if(R(e.owner)===t)return"owner";const o=Array.isArray(e.affiliations)?e.affiliations:[];for(const a of o){const e=d(a);if(e){if(R(e.owner)===t)return"owner";if(R(e.admin)===t)return"admin";if(R(e.member)===t)return"member"}}},A=(e,t)=>{const r=d(e);if(!r)return null;const o=f(r);if(!o)return null;const a=t?.stripOwnerAppKeyPrefix?(e=>{if(!e)return;const t=e.indexOf("_");return t<0?e:e.slice(t+1)})(R(r.owner)):R(r.owner);return{chatRoomId:o,name:b(r),owner:a?_(a):void 0,memberCount:p(r.memberCount)??p(r.affiliations_count),disabled:g(r.disabled)}},E=(e,t)=>{const r=(e=>{const t=d(e);return t?p(t.count):void 0})(e),o=I(e).map(e=>A(e,t)).filter(e=>null!==e),a=C(e,"pagenum"),s=C(e,"pagesize");return{items:o,pageNum:a,pageSize:s,total:r,hasMore:void 0!==r&&void 0!==a&&void 0!==s?a*s<r:void 0}},O=e=>I(e).map(e=>R(e)).filter(e=>Boolean(e)).map(e=>_(e)),v=(e,t)=>{const r=y(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=d(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:S(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},M=e=>{const t=d(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=d(e),r=(e=>{const t=d(e);if(!t)return null;const r=R(t.user),o=R(t.chatRoomId)??R(t.chatroomid)??R(t.id),a=l(t.action),s=g(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:_(r),action:a,reason:l(t.reason),...s?{}:{reason:l(t.reason)??"failed"}}:null})(e);if(!r||!t)return;g(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},S=t=>t.includes("is exceeding maximum limit")||t.includes("size of metadata")&&t.includes("exceeds")?e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED:t.includes("is not part of you")?e.ERROR_CODES.CHATROOM_PERMISSION_DENIED:t.includes("is not Legal")||t.includes("is not exist")?e.ERROR_CODES.VALIDATION_REQUIRED:e.ERROR_CODES.REST_BUSINESS_UNKNOWN,U=t=>{const{orgName:r,appName:o}=e.parseAppKey(t.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},T=t=>new e.ValidationError(`${t} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),D=(t,r)=>new e.ValidationError(r,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:r,rule:"invalid_format"}]}}),x=(e,t)=>`/${e.orgName}/${e.appName}${t}`,k=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw D(t,`${t} must be a string`);return e}},N=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw D(t,`${t} must be a number`);return e}},$=(e,t)=>{const o=r.createQueryParams();"number"==typeof e?.pageNum&&o.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&o.set("pagesize",String(e.pageSize));const a=o.toString();return a?`?${a}`:""},L=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw T(t);return e.trim()},F=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw T(t);const r=[],o=new Set;if(e.forEach((e,a)=>{if("string"!=typeof e)throw D(`${t}[${a}]`,`${t}[${a}] must be a string`);const s=e.trim();s&&!o.has(s)&&(o.add(s),r.push(s))}),0===r.length)throw T(t);return r},B=(e,t)=>F(e,t),z=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true&version=v3`);return((e,t)=>{const r=I(e),o=d(r[0])??y(e)??{},a=A(o)??{chatRoomId:f(o),name:b(o)},s=w(o,t);return{...a,description:l(o.description),maxMembers:p(o.maxMembers)??p(o.maxusers)??p(o.max_users),createdAt:p(o.createdAt)??p(o.created),ext:l(o.ext)??l(o.custom),muteAllMembers:g(o.mute),permissionType:s}})(await e.get(s,{operation:"getChatRoomInfo"}),t.userId)},j=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s={},n=k(r.name,"params.name"),i=k(r.description,"params.description"),c=N(r.maxMembers,"params.maxMembers");if(void 0!==n&&(s.groupname=n),void 0!==i&&(s.description=i),void 0!==c&&(s.maxusers=c),0===Object.keys(s).length)throw T("params");const m=x(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=y(e)??{};return{nameUpdated:g(t.groupname),descriptionUpdated:g(t.description),maxMembersUpdated:g(t.maxusers)}})(await e.put(m,s,{operation:"updateChatRoomInfo"}))},V=async(e,t,o)=>{const a=U(t),s=L(o.chatRoomId,"params.chatRoomId"),n=x(a,`/chatrooms/${encodeURIComponent(s)}/users${(e=>{const t=r.createQueryParams();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const o=t.toString();return o?`?${o}`:""})(o)}`);return(e=>{const t=[];for(const a of I(e)){const e=d(a);if(!e)continue;const r=R(e.owner),o=R(e.admin),s=R(e.member),n=r??o??s;n&&t.push({user:_(n),role:r?"owner":o?"admin":"member",joinedAt:p(e.joinedAt)??p(e.joined_time)})}const r=d(e),o=r?R(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(n,{operation:"getChatRoomMemberList"}))},q=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return O(n)},P=async(e,t,o)=>{const a=U(t),s=L(o.chatRoomId,"params.chatRoomId"),n=r.createQueryParams();n.set("version","v3"),"number"==typeof o.pageNum&&n.set("pagenum",String(o.pageNum)),"number"==typeof o.pageSize&&n.set("pagesize",String(o.pageSize));const i=x(a,`/chatrooms/${encodeURIComponent(s)}/mute?${n.toString()}`);return(e=>{const t=I(e);if(t.every(e=>"string"==typeof e))return O(e).map(e=>({user:e}));const r=[];for(const o of t){const e=d(o);if(!e)continue;const t=R(e.user)??R(e.member)??R(e.owner)??R(e.admin);t&&r.push({user:_(t),muteExpire:p(e.muteExpire)??p(e.expire)??p(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(i,{operation:"getChatRoomMuteList"}))},K=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=y(e)??{};return{muted:g(t.muted)??g(t.value)??Boolean(t.data),muteExpireAt:p(t.muteExpireAt)??p(t.expire)??p(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},H=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=$(r),n=s?"&":"",i=x(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return O(c).map(e=>({user:e}))},W=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return O(n).map(e=>({user:e}))},Q=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=y(e)??{};return g(t.value)??g(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},G=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=y(e)??{};return{announcement:l(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},X=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/metadata/chatroom/${encodeURIComponent(a)}`);return((e,t)=>{const r=y(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(s,{keys:r.keys?B(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},J=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw D(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw T(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw D(t,`${t} contains invalid key`);if("string"!=typeof r)throw D(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:n=!0,isForced:i=!1}=r,c=i?"/forced":"",m=x(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),u=await e.put(m,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return v(u,a)},Y={onChatRoomDestroyed:t.ChatRoomDispatchEventName.CHAT_ROOM_DESTROYED,onMembersJoined:t.ChatRoomDispatchEventName.MEMBERS_JOINED,onMembersExited:t.ChatRoomDispatchEventName.MEMBERS_EXITED,onRemovedFromChatRoom:t.ChatRoomDispatchEventName.REMOVED_FROM_CHAT_ROOM,onMuteListAdded:t.ChatRoomDispatchEventName.MUTE_LIST_ADDED,onMuteListRemoved:t.ChatRoomDispatchEventName.MUTE_LIST_REMOVED,onAllowListAdded:t.ChatRoomDispatchEventName.ALLOW_LIST_ADDED,onAllowListRemoved:t.ChatRoomDispatchEventName.ALLOW_LIST_REMOVED,onAllMemberMuteStateChanged:t.ChatRoomDispatchEventName.ALL_MEMBER_MUTE_STATE_CHANGED,onAdminAdded:t.ChatRoomDispatchEventName.ADMIN_ADDED,onAdminRemoved:t.ChatRoomDispatchEventName.ADMIN_REMOVED,onOwnerChanged:t.ChatRoomDispatchEventName.OWNER_CHANGED,onAnnouncementChanged:t.ChatRoomDispatchEventName.ANNOUNCEMENT_CHANGED,onChatRoomInfoChanged:t.ChatRoomDispatchEventName.CHAT_ROOM_INFO_CHANGED,onAttributesUpdate:t.ChatRoomDispatchEventName.ATTRIBUTES_UPDATE,onAttributesRemoved:t.ChatRoomDispatchEventName.ATTRIBUTES_REMOVED},Z=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},updateChatRoomInfo:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},destroyChatRoom:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},joinChatRoom:{range:"4,705,704,707",errors:{exceed_limit:{code:4,httpStatus:403,retryable:!1},members_full:{code:704,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"member list is full"},user_in_blocklist:{code:707,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"is in the blacklist"},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},leaveChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMemberList:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},addChatRoomMembers:{range:"110,204,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAdminList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAdmin:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomAdmin:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMuteList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteChatRoomMembers:{range:"110,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},isCurrentUserMutedInChatRoom:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["30005"]}}},getChatRoomBlocklist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},blockChatRoomMembers:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},unblockChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAllowlist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addUsersToChatRoomAllowlist:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeUsersFromChatRoomAllowlist:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},checkIfInChatRoomAllowList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAnnouncement:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomAnnouncement:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomSharedFileList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},deleteChatRoomSharedFile:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAttributes:{range:"110,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},setChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}}}}),ee=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=new Map}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){const r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{const r=Y[e];return r&&t?[[r,t]]:[]}));this.eventContext?.addEventHandler(e,r)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("chatroom"!==e.type)return;const t=e.payload,r=await this.buildIncomingEventPayload(t.eventName,t);if(!r)return;const o=Y[t.eventName];o&&this.eventContext?.dispatch?.(o,r)}async buildIncomingEventPayload(e,t){const r=t.payload,o=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(e){case"onChatRoomDestroyed":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName};case"onMembersJoined":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),o),ext:r.ext};case"onMembersExited":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),o)};case"onRemovedFromChatRoom":return{reason:r.reasonCode??0,chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,participant:this.pickEventUser(r.participantId,o)};case"onMuteListAdded":return{chatRoomId:r.chatRoomId,mutes:this.pickEventMuteEntries(r.userIds,r.muteExpire,o),muteExpire:r.muteExpire};case"onMuteListRemoved":return{chatRoomId:r.chatRoomId,mutes:this.pickEventUsers(r.userIds,o)};case"onAllowListAdded":case"onAllowListRemoved":return{chatRoomId:r.chatRoomId,allowlist:this.pickEventUsers(r.userIds,o)};case"onAllMemberMuteStateChanged":return{chatRoomId:r.chatRoomId,isMuted:Boolean(r.isMuted)};case"onAdminAdded":case"onAdminRemoved":return{chatRoomId:r.chatRoomId,admin:this.pickEventUser(r.adminId,o)};case"onOwnerChanged":return{chatRoomId:r.chatRoomId,newOwner:this.pickEventUser(r.newOwnerId,o),oldOwner:this.pickEventUser(r.oldOwnerId,o)};case"onAnnouncementChanged":return{chatRoomId:r.chatRoomId,announcement:r.announcement??""};case"onChatRoomInfoChanged":return{chatRoomId:r.chatRoomId,chatRoomInfo:await this.resolveChatRoomDetailForEvent(r)};case"onAttributesUpdate":return{chatRoomId:r.chatRoomId,attributes:r.attributes??{},from:this.pickEventUser(r.from,o)};case"onAttributesRemoved":return{chatRoomId:r.chatRoomId,keyList:r.keyList??[],from:this.pickEventUser(r.from,o)};default:return null}}async getChatRoomList(e={}){return this.runOperation("getChatRoomList",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r={})=>{const o=U(t),a=x(o,`/chatrooms${$(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return E(s)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(t){this.requireClient();const r=t.trim();if(0===r.length)throw new e.ValidationError("chatRoomId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const o=this.chatRoomRegistry.get(r);if(o)return o;const a=new s(r,this);return this.chatRoomRegistry.set(r,a),a}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await z(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return j(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=L(e.chatRoomId,"params.chatRoomId"),o=this.normalizeOptionalString(e.ext,"params.ext"),a=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");try{return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:o,leaveOtherRooms:a})).chatRoomInfo??{}}catch(s){throw this.remapChatRoomOperationError("joinChatRoom",s)}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=L(e.chatRoomId,"params.chatRoomId");try{await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})}catch(o){throw this.remapChatRoomOperationError("leaveChatRoom",o)}})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await V(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(r.items)}})}async removeMembers(e){return this.runOperation("removeMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return M(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await q(this.getRestClient(t),t,e);return this.hydrateUserInfos(r)})}async addAdmin(e){return this.runOperation("addAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=L(r.userId,"params.userId"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/admin?resource=${o.encodedResource}`);await e.post(n,{newadmin:s},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=L(r.userId,"params.userId"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/admin/${encodeURIComponent(s)}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await P(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async muteMembers(e){return this.runOperation("muteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=N(r.duration,"params.duration"),i=x(o,`/chatrooms/${encodeURIComponent(a)}/mute?resource=${o.encodedResource}`);await e.post(i,{usernames:s,mute_duration:n},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return K(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await H(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async blockMembers(e){return this.runOperation("blockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=1===s.length,i=x(o,n?`/chatrooms/${encodeURIComponent(a)}/blocks/users/${encodeURIComponent(s[0]??"")}?resource=${o.encodedResource}`:`/chatrooms/${encodeURIComponent(a)}/blocks/users?resource=${o.encodedResource}`),c=await e.post(i,n?void 0:{usernames:s},{operation:"blockChatRoomMembers"});return M(c)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async unblockMembers(e){return this.runOperation("unblockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return M(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await W(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async addUsersToAllowlist(e){return this.runOperation("addUsersToAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return M(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async removeUsersFromAllowlist(e){return this.runOperation("removeUsersFromAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return M(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return Q(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return G(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=k(r.announcement,"params.announcement");if(void 0===s)throw T("params.announcement");const n=x(o,`/chatrooms/${encodeURIComponent(a)}/announcement?resource=${o.encodedResource}`);await e.post(n,{announcement:s},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return X(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await J(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async removeAttributes(e){return this.runOperation("removeAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=B(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=x(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),m=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return v(m,a)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(t,r){try{return await r()}catch(o){const r=this.normalizeSdkError(t,o);throw e.logger.warn(`ChatRoomManager ${t} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(t,r){return r instanceof e.SDKError?r:r instanceof Error?new e.SDKError(`ChatRoomManager ${t} failed: ${r.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`ChatRoomManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}remapChatRoomOperationError(t,r){return r instanceof e.SDKError&&r.code===e.ERROR_CODES.GROUP_NOT_EXIST?new e.MessageSendError("Chat room does not exist",{code:e.ERROR_CODES.CHATROOM_NOT_EXIST,details:{...r.details,api:t,originalCode:r.code,canonicalCode:e.ERROR_CODES.CHATROOM_NOT_EXIST,retryable:!1}}):r}checkAttributeMutationResult(t){const r=Object.values(t.failedKeys);if(r.length>0&&0===t.appliedKeys.length){const[t]=r;if(t)throw new e.SDKError(t.message,t.code)}return t}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:Z,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}requireClient(){if(!this.client)throw new e.SDKError("ChatRoomManager is not bound to client",e.ERROR_CODES.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(t,r){if(void 0!==t){if("string"!=typeof t)throw new e.ValidationError(`${r} must be a string`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:`${r} must be a string`,rule:"invalid_format"}]}});return t}}normalizeOptionalBoolean(t,r){if(void 0!==t){if("boolean"!=typeof t)throw new e.ValidationError(`${r} must be a boolean`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:`${r} must be a boolean`,rule:"invalid_format"}]}});return t}}getCacheManager(){return this.client?.getCacheManager()??null}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(t){return h(t,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:t})=>{const r=this.getUserInfoManager();if(0===t.length)return[];if(!r)return await this.fetchUserInfosFromRest(t);try{return await r.getUserInfoByUserId({userIds:t})}catch(o){return e.logger.warn("ChatRoomManager user info fetch failed",{userIds:t,error:o}),[]}}})}async hydrateUserInfos(t){return(async(e,t)=>{const r=i(e),o=await h(r,t);return r.map(e=>u(void 0,o.get(e),e))})(t.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:t})=>{const r=this.getUserInfoManager();if(0===t.length)return[];if(!r)return await this.fetchUserInfosFromRest(t);try{return await r.getUserInfoByUserId({userIds:t})}catch(o){return e.logger.warn("ChatRoomManager hydrate users failed",{userIds:t,error:o}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=a.buildFetchUserInfoByUserIdRequest(e),o=await this.getRestClient(t).request(a.buildUserInfoFetchEndpoint(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return a.normalizeFetchedUserInfos(o,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],o=[],a=new Set;for(const s of r){if("string"!=typeof s)continue;const e=s.trim();e&&!a.has(e)&&(a.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return u(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>u(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(t){if(t.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:t.chatRoomId})}catch(r){e.logger.warn("ChatRoomManager event detail fetch failed",{chatRoomId:t.chatRoomId,error:r})}return{chatRoomId:t.chatRoomId,name:t.chatRoomPatch?.name??t.chatRoomName??"",...t.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:u(e.user,r.get(e.user.userId),e.user.userId)}))}async hydrateActionListResult(e){return{succeeded:await this.hydrateEntriesWithUsers(e.succeeded),failed:await this.hydrateEntriesWithUsers(e.failed)}}async hydrateSummaryOwners(e){const t=e.map(e=>e.owner?.userId).filter(e=>"string"==typeof e),r=await this.resolveUserInfoMap(t);return e.map(e=>e.owner?.userId?{...e,owner:u(e.owner,r.get(e.owner.userId),e.owner.userId)}:e)}async hydrateChatRoomDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveUserInfoMap([e.owner.userId]);return{...e,owner:u(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ee.key="chatRoomManager";let te=ee;exports.ChatRoom=s,exports.ChatRoomManager=te;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-Cg-lTASK.cjs"),t=require("../../chunks/event-system-TYhmgy4K.cjs"),r=require("../../chunks/query-params-BHyPuD2k.cjs"),o=require("../../chunks/cache-utils-gowrxNr8.cjs"),a=require("../../chunks/user-info-B5St7axd.cjs");class s{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const n=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],i=e=>{const t=[],r=new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},c=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),m=e=>({userId:e}),u=(e,t,r)=>{const o={userId:r};for(const a of n){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},h=async(e,t)=>{const r=i(e),o=new Map;if(0===r.length)return o;const a=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const n of a)o.set(n.userId,c(n));const s=r.filter(e=>!o.has(e));if(s.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:s});for(const t of e)o.set(t.userId,t)}for(const n of r)o.has(n)||o.set(n,m(n));return o},d=e=>o.isRecord(e)?e:null,l=e=>"string"==typeof e?e:void 0,R=e=>{const t=l(e)?.trim();return t||void 0},p=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}},g=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},I=e=>{const t=d(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},y=e=>{const t=d(e);return t?d(t.data)?t.data:t:null},C=(e,t)=>{const r=d(e),o=r&&d(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return p(a[0])},f=e=>R(e.chatRoomId)??R(e.chatroomid)??R(e.id)??"",b=e=>l(e.name)??l(e.title)??l(e.groupname)??"",_=e=>m(e),w=(e,t)=>{const r=(e=>{const t=l(e);return"owner"===t||"admin"===t||"member"===t||"none"===t?t:void 0})(e.permission);if(void 0!==r)return r;if(!t)return;if(R(e.owner)===t)return"owner";const o=Array.isArray(e.affiliations)?e.affiliations:[];for(const a of o){const e=d(a);if(e){if(R(e.owner)===t)return"owner";if(R(e.admin)===t)return"admin";if(R(e.member)===t)return"member"}}},A=(e,t)=>{const r=d(e);if(!r)return null;const o=f(r);if(!o)return null;const a=t?.stripOwnerAppKeyPrefix?(e=>{if(!e)return;const t=e.indexOf("_");return t<0?e:e.slice(t+1)})(R(r.owner)):R(r.owner);return{chatRoomId:o,name:b(r),owner:a?_(a):void 0,memberCount:p(r.memberCount)??p(r.affiliations_count),disabled:g(r.disabled)}},E=(e,t)=>{const r=(e=>{const t=d(e);return t?p(t.count):void 0})(e),o=I(e).map(e=>A(e,t)).filter(e=>null!==e),a=C(e,"pagenum"),s=C(e,"pagesize");return{items:o,pageNum:a,pageSize:s,total:r,hasMore:void 0!==r&&void 0!==a&&void 0!==s?a*s<r:void 0}},O=e=>I(e).map(e=>R(e)).filter(e=>Boolean(e)).map(e=>_(e)),v=(e,t)=>{const r=y(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=d(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:S(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},M=e=>{const t=d(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=d(e),r=(e=>{const t=d(e);if(!t)return null;const r=R(t.user),o=R(t.chatRoomId)??R(t.chatroomid)??R(t.id),a=l(t.action),s=g(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:_(r),action:a,reason:l(t.reason),...s?{}:{reason:l(t.reason)??"failed"}}:null})(e);if(!r||!t)return;g(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},S=t=>t.includes("is exceeding maximum limit")||t.includes("size of metadata")&&t.includes("exceeds")?e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED:t.includes("is not part of you")?e.ERROR_CODES.CHATROOM_PERMISSION_DENIED:t.includes("is not Legal")||t.includes("is not exist")?e.ERROR_CODES.VALIDATION_REQUIRED:e.ERROR_CODES.REST_BUSINESS_UNKNOWN,U=t=>{const{orgName:r,appName:o}=e.parseAppKey(t.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},T=t=>new e.ValidationError(`${t} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),D=(t,r)=>new e.ValidationError(r,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:r,rule:"invalid_format"}]}}),x=(e,t)=>`/${e.orgName}/${e.appName}${t}`,k=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw D(t,`${t} must be a string`);return e}},N=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw D(t,`${t} must be a number`);return e}},$=(e,t)=>{const o=r.createQueryParams();"number"==typeof e?.pageNum&&o.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&o.set("pagesize",String(e.pageSize));const a=o.toString();return a?`?${a}`:""},L=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw T(t);return e.trim()},F=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw T(t);const r=[],o=new Set;if(e.forEach((e,a)=>{if("string"!=typeof e)throw D(`${t}[${a}]`,`${t}[${a}] must be a string`);const s=e.trim();s&&!o.has(s)&&(o.add(s),r.push(s))}),0===r.length)throw T(t);return r},B=(e,t)=>F(e,t),z=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true&version=v3`);return((e,t)=>{const r=I(e),o=d(r[0])??y(e)??{},a=A(o)??{chatRoomId:f(o),name:b(o)},s=w(o,t);return{...a,description:l(o.description),maxMembers:p(o.maxMembers)??p(o.maxusers)??p(o.max_users),createdAt:p(o.createdAt)??p(o.created),ext:l(o.ext)??l(o.custom),muteAllMembers:g(o.mute),permissionType:s}})(await e.get(s,{operation:"getChatRoomInfo"}),t.userId)},j=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s={},n=k(r.name,"params.name"),i=k(r.description,"params.description"),c=N(r.maxMembers,"params.maxMembers");if(void 0!==n&&(s.groupname=n),void 0!==i&&(s.description=i),void 0!==c&&(s.maxusers=c),0===Object.keys(s).length)throw T("params");const m=x(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=y(e)??{};return{nameUpdated:g(t.groupname),descriptionUpdated:g(t.description),maxMembersUpdated:g(t.maxusers)}})(await e.put(m,s,{operation:"updateChatRoomInfo"}))},V=async(e,t,o)=>{const a=U(t),s=L(o.chatRoomId,"params.chatRoomId"),n=x(a,`/chatrooms/${encodeURIComponent(s)}/users${(e=>{const t=r.createQueryParams();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const o=t.toString();return o?`?${o}`:""})(o)}`);return(e=>{const t=[];for(const a of I(e)){const e=d(a);if(!e)continue;const r=R(e.owner),o=R(e.admin),s=R(e.member),n=r??o??s;n&&t.push({user:_(n),role:r?"owner":o?"admin":"member",joinedAt:p(e.joinedAt)??p(e.joined_time)})}const r=d(e),o=r?R(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(n,{operation:"getChatRoomMemberList"}))},q=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return O(n)},P=async(e,t,o)=>{const a=U(t),s=L(o.chatRoomId,"params.chatRoomId"),n=r.createQueryParams();n.set("version","v3"),"number"==typeof o.pageNum&&n.set("pagenum",String(o.pageNum)),"number"==typeof o.pageSize&&n.set("pagesize",String(o.pageSize));const i=x(a,`/chatrooms/${encodeURIComponent(s)}/mute?${n.toString()}`);return(e=>{const t=I(e);if(t.every(e=>"string"==typeof e))return O(e).map(e=>({user:e}));const r=[];for(const o of t){const e=d(o);if(!e)continue;const t=R(e.user)??R(e.member)??R(e.owner)??R(e.admin);t&&r.push({user:_(t),muteExpire:p(e.muteExpire)??p(e.expire)??p(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(i,{operation:"getChatRoomMuteList"}))},K=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=y(e)??{};return{muted:g(t.muted)??g(t.value)??Boolean(t.data),muteExpireAt:p(t.muteExpireAt)??p(t.expire)??p(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},H=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=$(r),n=s?"&":"",i=x(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return O(c).map(e=>({user:e}))},W=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return O(n).map(e=>({user:e}))},Q=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=y(e)??{};return g(t.value)??g(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},G=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=y(e)??{};return{announcement:l(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},X=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/metadata/chatroom/${encodeURIComponent(a)}`);return((e,t)=>{const r=y(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(s,{keys:r.keys?B(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},J=async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw D(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw T(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw D(t,`${t} contains invalid key`);if("string"!=typeof r)throw D(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:n=!0,isForced:i=!1}=r,c=i?"/forced":"",m=x(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),u=await e.put(m,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return v(u,a)},Y={onChatRoomDestroyed:t.ChatRoomDispatchEventName.CHAT_ROOM_DESTROYED,onMembersJoined:t.ChatRoomDispatchEventName.MEMBERS_JOINED,onMembersExited:t.ChatRoomDispatchEventName.MEMBERS_EXITED,onRemovedFromChatRoom:t.ChatRoomDispatchEventName.REMOVED_FROM_CHAT_ROOM,onMuteListAdded:t.ChatRoomDispatchEventName.MUTE_LIST_ADDED,onMuteListRemoved:t.ChatRoomDispatchEventName.MUTE_LIST_REMOVED,onAllowListAdded:t.ChatRoomDispatchEventName.ALLOW_LIST_ADDED,onAllowListRemoved:t.ChatRoomDispatchEventName.ALLOW_LIST_REMOVED,onAllMemberMuteStateChanged:t.ChatRoomDispatchEventName.ALL_MEMBER_MUTE_STATE_CHANGED,onAdminAdded:t.ChatRoomDispatchEventName.ADMIN_ADDED,onAdminRemoved:t.ChatRoomDispatchEventName.ADMIN_REMOVED,onOwnerChanged:t.ChatRoomDispatchEventName.OWNER_CHANGED,onAnnouncementChanged:t.ChatRoomDispatchEventName.ANNOUNCEMENT_CHANGED,onChatRoomInfoChanged:t.ChatRoomDispatchEventName.CHAT_ROOM_INFO_CHANGED,onAttributesUpdate:t.ChatRoomDispatchEventName.ATTRIBUTES_UPDATE,onAttributesRemoved:t.ChatRoomDispatchEventName.ATTRIBUTES_REMOVED},Z=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},updateChatRoomInfo:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},destroyChatRoom:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},joinChatRoom:{range:"4,705,704,707",errors:{exceed_limit:{code:4,httpStatus:403,retryable:!1},members_full:{code:704,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"member list is full"},user_in_blocklist:{code:707,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"is in the blacklist"},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},leaveChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMemberList:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},addChatRoomMembers:{range:"110,204,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAdminList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAdmin:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomAdmin:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMuteList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteChatRoomMembers:{range:"110,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},isCurrentUserMutedInChatRoom:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["30005"]}}},getChatRoomBlocklist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},blockChatRoomMembers:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},unblockChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAllowlist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addUsersToChatRoomAllowlist:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeUsersFromChatRoomAllowlist:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},checkIfInChatRoomAllowList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAnnouncement:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomAnnouncement:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomSharedFileList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},deleteChatRoomSharedFile:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAttributes:{range:"110,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},setChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}}}}),ee=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=new Map}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){const r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{const r=Y[e];return r&&t?[[r,t]]:[]}));this.eventContext?.addEventHandler(e,r)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("chatroom"!==e.type)return;const t=e.payload,r=await this.buildIncomingEventPayload(t.eventName,t);if(!r)return;const o=Y[t.eventName];o&&this.eventContext?.dispatch?.(o,r)}async buildIncomingEventPayload(e,t){const r=t.payload,o=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(e){case"onChatRoomDestroyed":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName};case"onMembersJoined":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),o),ext:r.ext};case"onMembersExited":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),o)};case"onRemovedFromChatRoom":return{reason:r.reasonCode??0,chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,participant:this.pickEventUser(r.participantId,o)};case"onMuteListAdded":return{chatRoomId:r.chatRoomId,mutes:this.pickEventMuteEntries(r.userIds,r.muteExpire,o),muteExpire:r.muteExpire};case"onMuteListRemoved":return{chatRoomId:r.chatRoomId,mutes:this.pickEventUsers(r.userIds,o)};case"onAllowListAdded":case"onAllowListRemoved":return{chatRoomId:r.chatRoomId,allowlist:this.pickEventUsers(r.userIds,o)};case"onAllMemberMuteStateChanged":return{chatRoomId:r.chatRoomId,isMuted:Boolean(r.isMuted)};case"onAdminAdded":case"onAdminRemoved":return{chatRoomId:r.chatRoomId,admin:this.pickEventUser(r.adminId,o)};case"onOwnerChanged":return{chatRoomId:r.chatRoomId,newOwner:this.pickEventUser(r.newOwnerId,o),oldOwner:this.pickEventUser(r.oldOwnerId,o)};case"onAnnouncementChanged":return{chatRoomId:r.chatRoomId,announcement:r.announcement??""};case"onChatRoomInfoChanged":return{chatRoomId:r.chatRoomId,chatRoomInfo:await this.resolveChatRoomDetailForEvent(r)};case"onAttributesUpdate":return{chatRoomId:r.chatRoomId,attributes:r.attributes??{},from:this.pickEventUser(r.from,o)};case"onAttributesRemoved":return{chatRoomId:r.chatRoomId,keyList:r.keyList??[],from:this.pickEventUser(r.from,o)};default:return null}}async getChatRoomList(e={}){return this.runOperation("getChatRoomList",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r={})=>{const o=U(t),a=x(o,`/chatrooms${$(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return E(s)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(t){this.requireClient();const r=t.trim();if(0===r.length)throw new e.ValidationError("chatRoomId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const o=this.chatRoomRegistry.get(r);if(o)return o;const a=new s(r,this);return this.chatRoomRegistry.set(r,a),a}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await z(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return j(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=L(e.chatRoomId,"params.chatRoomId"),o=this.normalizeOptionalString(e.ext,"params.ext"),a=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");try{return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:o,leaveOtherRooms:a})).chatRoomInfo??{}}catch(s){throw this.remapChatRoomOperationError("joinChatRoom",s)}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=L(e.chatRoomId,"params.chatRoomId");try{await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})}catch(o){throw this.remapChatRoomOperationError("leaveChatRoom",o)}})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await V(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(r.items)}})}async removeMembers(e){return this.runOperation("removeMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return M(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await q(this.getRestClient(t),t,e);return this.hydrateUserInfos(r)})}async addAdmin(e){return this.runOperation("addAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=L(r.userId,"params.userId"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/admin?resource=${o.encodedResource}`);await e.post(n,{newadmin:s},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=L(r.userId,"params.userId"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/admin/${encodeURIComponent(s)}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await P(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async muteMembers(e){return this.runOperation("muteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=N(r.duration,"params.duration"),i=x(o,`/chatrooms/${encodeURIComponent(a)}/mute?resource=${o.encodedResource}`);await e.post(i,{usernames:s,mute_duration:n},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=x(o,`/chatrooms/${encodeURIComponent(a)}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return K(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await H(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async blockMembers(e){return this.runOperation("blockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=1===s.length,i=x(o,n?`/chatrooms/${encodeURIComponent(a)}/blocks/users/${encodeURIComponent(s[0]??"")}?resource=${o.encodedResource}`:`/chatrooms/${encodeURIComponent(a)}/blocks/users?resource=${o.encodedResource}`),c=await e.post(i,n?void 0:{usernames:s},{operation:"blockChatRoomMembers"});return M(c)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async unblockMembers(e){return this.runOperation("unblockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return M(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await W(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async addUsersToAllowlist(e){return this.runOperation("addUsersToAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return M(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async removeUsersFromAllowlist(e){return this.runOperation("removeUsersFromAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=F(r.userIds,"params.userIds"),n=x(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return M(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return Q(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return G(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=k(r.announcement,"params.announcement");if(void 0===s)throw T("params.announcement");const n=x(o,`/chatrooms/${encodeURIComponent(a)}/announcement?resource=${o.encodedResource}`);await e.post(n,{announcement:s},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return X(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await J(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async removeAttributes(e){return this.runOperation("removeAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=U(t),a=L(r.chatRoomId,"params.chatRoomId"),s=B(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=x(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),m=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return v(m,a)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(t,r){try{return await r()}catch(o){const r=this.normalizeSdkError(t,o);throw e.logger.warn(`ChatRoomManager ${t} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(t,r){return r instanceof e.SDKError?r:r instanceof Error?new e.SDKError(`ChatRoomManager ${t} failed: ${r.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`ChatRoomManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}remapChatRoomOperationError(t,r){return r instanceof e.SDKError&&r.code===e.ERROR_CODES.GROUP_NOT_EXIST?new e.MessageSendError("Chat room does not exist",{code:e.ERROR_CODES.CHATROOM_NOT_EXIST,details:{...r.details,api:t,originalCode:r.code,canonicalCode:e.ERROR_CODES.CHATROOM_NOT_EXIST,retryable:!1}}):r}checkAttributeMutationResult(t){const r=Object.values(t.failedKeys);if(r.length>0&&0===t.appliedKeys.length){const[t]=r;if(t)throw new e.SDKError(t.message,t.code)}return t}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:Z,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}requireClient(){if(!this.client)throw new e.SDKError("ChatRoomManager is not bound to client",e.ERROR_CODES.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(t,r){if(void 0!==t){if("string"!=typeof t)throw new e.ValidationError(`${r} must be a string`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:`${r} must be a string`,rule:"invalid_format"}]}});return t}}normalizeOptionalBoolean(t,r){if(void 0!==t){if("boolean"!=typeof t)throw new e.ValidationError(`${r} must be a boolean`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:`${r} must be a boolean`,rule:"invalid_format"}]}});return t}}getCacheManager(){return this.client?.getCacheManager()??null}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(t){return h(t,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:t})=>{const r=this.getUserInfoManager();if(0===t.length)return[];if(!r)return await this.fetchUserInfosFromRest(t);try{return await r.getUserInfoByUserId({userIds:t})}catch(o){return e.logger.warn("ChatRoomManager user info fetch failed",{userIds:t,error:o}),[]}}})}async hydrateUserInfos(t){return(async(e,t)=>{const r=i(e),o=await h(r,t);return r.map(e=>u(void 0,o.get(e),e))})(t.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:t})=>{const r=this.getUserInfoManager();if(0===t.length)return[];if(!r)return await this.fetchUserInfosFromRest(t);try{return await r.getUserInfoByUserId({userIds:t})}catch(o){return e.logger.warn("ChatRoomManager hydrate users failed",{userIds:t,error:o}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=a.buildFetchUserInfoByUserIdRequest(e),o=await this.getRestClient(t).request(a.buildUserInfoFetchEndpoint(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return a.normalizeFetchedUserInfos(o,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],o=[],a=new Set;for(const s of r){if("string"!=typeof s)continue;const e=s.trim();e&&!a.has(e)&&(a.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return u(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>u(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(t){if(t.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:t.chatRoomId})}catch(r){e.logger.warn("ChatRoomManager event detail fetch failed",{chatRoomId:t.chatRoomId,error:r})}return{chatRoomId:t.chatRoomId,name:t.chatRoomPatch?.name??t.chatRoomName??"",...t.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:u(e.user,r.get(e.user.userId),e.user.userId)}))}async hydrateActionListResult(e){return{succeeded:await this.hydrateEntriesWithUsers(e.succeeded),failed:await this.hydrateEntriesWithUsers(e.failed)}}async hydrateSummaryOwners(e){const t=e.map(e=>e.owner?.userId).filter(e=>"string"==typeof e),r=await this.resolveUserInfoMap(t);return e.map(e=>e.owner?.userId?{...e,owner:u(e.owner,r.get(e.owner.userId),e.owner.userId)}:e)}async hydrateChatRoomDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveUserInfoMap([e.owner.userId]);return{...e,owner:u(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ee.key="chatRoomManager";let te=ee;exports.ChatRoom=s,exports.ChatRoomManager=te;