easemob-websdk 5.1.0 → 5.1.2

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 (100) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/chat-client.d.ts +42 -8
  3. package/chunks/{chat-manager-D_KF5qM1.cjs → chat-manager-BFd2Z4oY.cjs} +1 -1
  4. package/chunks/{chat-manager-DCqgMxLm.js → chat-manager-CId_M_e5.js} +1 -1
  5. package/chunks/common-BvlDAw4a.js +1 -0
  6. package/chunks/common-tHGz9VBk.cjs +1 -0
  7. package/chunks/event-system-B62vbKqG.js +1 -0
  8. package/chunks/{event-system-COBJFEIq.cjs → event-system-TYhmgy4K.cjs} +1 -1
  9. package/chunks/group-user-info-resolver-B-dyr__b.cjs +1 -0
  10. package/chunks/group-user-info-resolver-DMccCqez.js +1 -0
  11. package/chunks/index-BBFJYOM8.js +1 -0
  12. package/chunks/{index-Dvvh1nf6.cjs → index-DJPAjXAp.cjs} +1 -1
  13. package/chunks/index-DtWkVcfb.cjs +1 -0
  14. package/chunks/index-l_BUKi77.js +1 -0
  15. package/chunks/light-BcQg8h2W.cjs +1 -0
  16. package/chunks/light-DImBnNes.js +1 -0
  17. package/chunks/{reflection-proto-codec-CjRraw85.js → reflection-proto-codec-7r8Sei3y.js} +1 -1
  18. package/chunks/{reflection-proto-codec-BerStgkC.cjs → reflection-proto-codec-CwrIKT1L.cjs} +1 -1
  19. package/chunks/{session-list-query-rynxSxtv.js → session-list-query-Cvr6rlme.js} +1 -1
  20. package/chunks/{session-list-query-C4OQMvPf.cjs → session-list-query-Dslj2k3t.cjs} +1 -1
  21. package/chunks/{user-info-DfbCp80h.js → user-info-AlshAvdy.js} +1 -1
  22. package/chunks/{user-info-DsDDTJrw.cjs → user-info-DH3aE1gm.cjs} +1 -1
  23. package/config/timeouts.d.ts +11 -0
  24. package/core/connection/connection-manager.d.ts +18 -1
  25. package/core/connection/login-deadline.d.ts +22 -0
  26. package/core/events/event-hub.d.ts +1 -0
  27. package/core/index.d.ts +8 -1
  28. package/core/message/attachment-downloader.d.ts +1 -1
  29. package/core/session-list-sync/session-list-sync-controller.d.ts +5 -0
  30. package/index.cjs +1 -1
  31. package/index.d.ts +11 -9
  32. package/index.js +2 -2
  33. package/log.d.ts +27 -0
  34. package/managers/chat/index.cjs +1 -1
  35. package/managers/chat/index.js +1 -1
  36. package/managers/chat-thread/index.cjs +1 -1
  37. package/managers/chat-thread/index.js +1 -1
  38. package/managers/chatroom/chatroom.d.ts +1 -1
  39. package/managers/chatroom/index.cjs +1 -1
  40. package/managers/chatroom/index.js +1 -1
  41. package/managers/chatroom-manager.d.ts +6 -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.d.ts +2 -0
  50. package/managers/push/index.js +1 -1
  51. package/managers/push/native-push-controller.d.ts +62 -0
  52. package/managers/push/native-push-normalizer.d.ts +15 -0
  53. package/managers/push-manager.d.ts +63 -4
  54. package/managers/user-info/index.cjs +1 -1
  55. package/managers/user-info/index.js +1 -1
  56. package/managers/user-info-manager.d.ts +3 -2
  57. package/message/combine-payload-codec.d.ts +2 -1
  58. package/package.json +1 -1
  59. package/platform/index.d.ts +1 -1
  60. package/platform/request/default-request-adapter.d.ts +7 -0
  61. package/platform/socket/default-socket-adapter.d.ts +6 -0
  62. package/platform/types.d.ts +22 -2
  63. package/platform/upload/legacy-multipart-upload.d.ts +14 -0
  64. package/platform/upload/legacy-simple-upload.d.ts +3 -0
  65. package/protocol/msync/codec.d.ts +5 -0
  66. package/rest/client.d.ts +0 -4
  67. package/rest/contact-management.d.ts +1 -0
  68. package/rest/dns-config.d.ts +6 -1
  69. package/rest/error-maps/chatroom.d.ts +6 -0
  70. package/rest/error-maps/common.d.ts +3 -0
  71. package/rest/error-maps/contact.d.ts +8 -3
  72. package/rest/error-maps/push.d.ts +13 -1
  73. package/rest/error-maps/user-info.d.ts +51 -3
  74. package/rest/service-url.d.ts +6 -0
  75. package/types/chat-client.d.ts +16 -9
  76. package/types/chatroom.d.ts +3 -34
  77. package/types/event-system.d.ts +52 -1
  78. package/types/index.d.ts +5 -7
  79. package/types/log.d.ts +19 -0
  80. package/types/manager.d.ts +31 -0
  81. package/types/push.d.ts +77 -0
  82. package/upload/attachment-uploader.d.ts +1 -5
  83. package/upload/multipart-upload.d.ts +4 -14
  84. package/upload/simple-upload.d.ts +4 -3
  85. package/upload/types.d.ts +2 -1
  86. package/utils/error-codes.generated.d.ts +1 -0
  87. package/utils/log-reporter.d.ts +1 -7
  88. package/utils/logger.d.ts +28 -2
  89. package/validators/chat-client.d.ts +22 -50
  90. package/validators/message-create.d.ts +18 -18
  91. package/chunks/common-BIpcR2uQ.cjs +0 -1
  92. package/chunks/common-D_DfwSd3.js +0 -1
  93. package/chunks/event-system-D6IJA0C4.js +0 -1
  94. package/chunks/group-user-info-resolver-Ds35Z1Uf.cjs +0 -1
  95. package/chunks/group-user-info-resolver-lEtRdWli.js +0 -1
  96. package/chunks/index-BmwQgZ3E.js +0 -1
  97. package/chunks/index-BsIqq7LU.cjs +0 -1
  98. package/chunks/index-CFMcR5a_.js +0 -1
  99. package/chunks/light-Dg9A1Xmd.js +0 -1
  100. package/chunks/light-dJjIln5b.cjs +0 -1
@@ -1 +1 @@
1
- import{E as e,p as t,V as r,l as o,S as a,f as s,m as n,i}from"../../chunks/common-D_DfwSd3.js";import{b as c}from"../../chunks/event-system-D6IJA0C4.js";import{c as u}from"../../chunks/query-params-Bu3Xq4b6.js";import{i as m}from"../../chunks/cache-utils-B99glc0H.js";import{b as h,a as d,n as l}from"../../chunks/user-info-DfbCp80h.js";class p{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 R=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],g=e=>{const t=[],r=/* @__PURE__ */new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},I=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),y=e=>({userId:e}),f=(e,t,r)=>{const o={userId:r};for(const a of R){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},b=async(e,t)=>{const r=g(e),o=/* @__PURE__ */new Map;if(0===r.length)return o;const a=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const n of a)o.set(n.userId,I(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,y(n));return o},C=e=>m(e)?e:null,w=e=>"string"==typeof e?e:void 0,_=e=>{const t=w(e)?.trim();return t||void 0},A=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}},M=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},v=e=>{const t=C(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},U=e=>{const t=C(e);return t?C(t.data)?t.data:t:null},E=(e,t)=>{const r=C(e),o=r&&C(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return A(a[0])},S=e=>_(e.chatRoomId)??_(e.chatroomid)??_(e.id)??"",O=e=>w(e.name)??w(e.title)??w(e.groupname)??"",T=e=>y(e),x=(e,t)=>{const r=C(e);if(!r)return null;const o=S(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.owner)):_(r.owner);return{chatRoomId:o,name:O(r),owner:a?T(a):void 0,memberCount:A(r.memberCount)??A(r.affiliations_count),disabled:M(r.disabled)}},k=(e,t)=>{const r=(e=>{const t=C(e);return t?A(t.count):void 0})(e),o=v(e).map(e=>x(e,t)).filter(e=>null!==e),a=E(e,"pagenum"),s=E(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}},$=(e,t)=>{const r=v(e),o=C(r[0])??U(e)??{},a=x(o)??{chatRoomId:S(o),name:O(o)},s=((e,t)=>{if(!t)return;if(_(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const o of r){const e=C(o);if(e){if(_(e.owner)===t)return"owner";if(_(e.admin)===t)return"admin";if(_(e.member)===t)return"member"}}})(o,t),n=A(o.muteExpireAt)??A(o.mute_expire)??A(o.expire),i=M(o.inAllowlist)??M(o.white)??M(o.in_whitelist),c=M(o.muted);return{...a,description:w(o.description),maxMembers:A(o.maxMembers)??A(o.maxusers)??A(o.max_users),createdAt:A(o.createdAt)??A(o.created),ext:w(o.ext)??w(o.custom),announcement:w(o.announcement),permissionType:s,currentUserStatus:void 0!==i||void 0!==c||void 0!==n||void 0!==s?{inAllowlist:i,muted:c,muteExpireAt:n,permissionType:s}:void 0}},L=e=>v(e).map(e=>_(e)).filter(e=>Boolean(e)).map(e=>T(e)),N=(e,t)=>{const r=U(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=C(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:F(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},D=e=>{const t=C(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=C(e),r=(e=>{const t=C(e);if(!t)return null;const r=_(t.user),o=_(t.chatRoomId)??_(t.chatroomid)??_(t.id),a=w(t.action),s=M(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:T(r),action:a,reason:w(t.reason),...s?{}:{reason:w(t.reason)??"failed"}}:null})(e);if(!r||!t)return;M(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},F=t=>t.includes("is exceeding maximum limit")||t.includes("size of metadata")&&t.includes("exceeds")?e.SERVICE_LIMIT_EXCEEDED:t.includes("is not part of you")?e.CHATROOM_PERMISSION_DENIED:t.includes("is not Legal")||t.includes("is not exist")?e.VALIDATION_REQUIRED:e.REST_BUSINESS_UNKNOWN,B=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},z=t=>new r(`${t} is required`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),j=(t,o)=>new r(o,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:o,rule:"invalid_format"}]}}),V=(e,t)=>`/${e.orgName}/${e.appName}${t}`,q=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw j(t,`${t} must be a string`);return e}},P=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw j(t,`${t} must be a number`);return e}},W=(e,t)=>{const r=u();"number"==typeof e?.pageNum&&r.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&r.set("pagesize",String(e.pageSize));const o=r.toString();return o?`?${o}`:""},H=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw z(t);return e.trim()},K=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw z(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,a)=>{if("string"!=typeof e)throw j(`${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 z(t);return r},G=(e,t)=>K(e,t),Q=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s={},n=q(r.name,"params.name"),i=q(r.description,"params.description"),c=P(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 z("params");const u=V(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=U(e)??{};return{nameUpdated:M(t.groupname),descriptionUpdated:M(t.description),maxMembersUpdated:M(t.maxusers)}})(await e.put(u,s,{operation:"updateChatRoomInfo"}))},J=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/users${(e=>{const t=u();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const r=t.toString();return r?`?${r}`:""})(r)}`);return(e=>{const t=[];for(const a of v(e)){const e=C(a);if(!e)continue;const r=_(e.owner),o=_(e.admin),s=_(e.member),n=r??o??s;n&&t.push({user:T(n),role:r?"owner":o?"admin":"member",joinedAt:A(e.joinedAt)??A(e.joined_time)})}const r=C(e),o=r?_(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(s,{operation:"getChatRoomMemberList"}))},X=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return L(n)},Y=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=u();s.set("version","v3"),"number"==typeof r.pageNum&&s.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&s.set("pagesize",String(r.pageSize));const n=V(o,`/chatrooms/${encodeURIComponent(a)}/mute?${s.toString()}`);return(e=>{const t=v(e);if(t.every(e=>"string"==typeof e))return L(e).map(e=>({user:e}));const r=[];for(const o of t){const e=C(o);if(!e)continue;const t=_(e.user)??_(e.member)??_(e.owner)??_(e.admin);t&&r.push({user:T(t),muteExpire:A(e.muteExpire)??A(e.expire)??A(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(n,{operation:"getChatRoomMuteList"}))},Z=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=U(e)??{};return{muted:M(t.muted)??M(t.value)??Boolean(t.data),muteExpireAt:A(t.muteExpireAt)??A(t.expire)??A(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},ee=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=W(r),n=s?"&":"",i=V(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return L(c).map(e=>({user:e}))},te=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return L(n).map(e=>({user:e}))},re=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=U(e)??{};return M(t.value)??M(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},oe=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=U(e)??{};return{announcement:w(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},ae=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/metadata/chatroom/${encodeURIComponent(a)}`);return((e,t)=>{const r=U(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(s,{keys:r.keys?G(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},se=async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw j(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw z(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw j(t,`${t} contains invalid key`);if("string"!=typeof r)throw j(`${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":"",u=V(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),m=await e.put(u,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return N(m,a)},ne={onChatRoomDestroyed:c.CHAT_ROOM_DESTROYED,onMembersJoined:c.MEMBERS_JOINED,onMembersExited:c.MEMBERS_EXITED,onRemovedFromChatRoom:c.REMOVED_FROM_CHAT_ROOM,onMuteListAdded:c.MUTE_LIST_ADDED,onMuteListRemoved:c.MUTE_LIST_REMOVED,onAllowListAdded:c.ALLOW_LIST_ADDED,onAllowListRemoved:c.ALLOW_LIST_REMOVED,onAllMemberMuteStateChanged:c.ALL_MEMBER_MUTE_STATE_CHANGED,onAdminAdded:c.ADMIN_ADDED,onAdminRemoved:c.ADMIN_REMOVED,onOwnerChanged:c.OWNER_CHANGED,onAnnouncementChanged:c.ANNOUNCEMENT_CHANGED,onChatRoomInfoChanged:c.CHAT_ROOM_INFO_CHANGED,onAttributesUpdate:c.ATTRIBUTES_UPDATE,onAttributesRemoved:c.ATTRIBUTES_REMOVED},ie=n(i,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},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,httpStatus:404,retryable:!1}}},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,httpStatus:404,retryable:!1}}},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}}}}}),ce=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=/* @__PURE__ */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=ne[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=ne[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=B(t),a=V(o,`/chatrooms${W(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return k(s)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(t){this.requireClient();const o=t.trim();if(0===o.length)throw new r("chatRoomId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const a=this.chatRoomRegistry.get(o);if(a)return a;const s=new p(o,this);return this.chatRoomRegistry.set(o,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true`),n=await e.get(s,{operation:"getChatRoomInfo"});return $(n,t.userId)})(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return Q(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=H(e.chatRoomId,"params.chatRoomId"),o=this.normalizeOptionalString(e.ext,"params.ext"),a=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:o,leaveOtherRooms:a})).chatRoomInfo??{}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=H(e.chatRoomId,"params.chatRoomId");await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await J(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await X(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=H(r.userId,"params.userId"),n=V(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=H(r.userId,"params.userId"),n=V(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 Y(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=P(r.duration,"params.duration"),i=V(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=V(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 Z(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await ee(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=1===s.length,i=V(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 D(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await te(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return D(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=K(r.userIds,"params.userIds"),n=V(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return D(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return re(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return oe(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=q(r.announcement,"params.announcement");if(void 0===s)throw z("params.announcement");const n=V(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 ae(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await se(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=B(t),a=H(r.chatRoomId,"params.chatRoomId"),s=G(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=V(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),u=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return N(u,a)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw o.warn(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(t,r){return r instanceof a?r:r instanceof Error?new a(`ChatRoomManager ${t} failed: ${r.message}`,e.UNKNOWN):new a(`ChatRoomManager ${t} failed`,e.UNKNOWN)}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new a(e.message,e.code)}return e}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new s(e.restBaseUrl,{errorMap:ie,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new a("ChatRoomManager is not bound to client",e.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(t,o){if(void 0!==t){if("string"!=typeof t)throw new r(`${o} must be a string`,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:o,message:`${o} must be a string`,rule:"invalid_format"}]}});return t}}normalizeOptionalBoolean(t,o){if(void 0!==t){if("boolean"!=typeof t)throw new r(`${o} must be a boolean`,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:o,message:`${o} 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(e){return b(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return o.warn("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=g(e),o=await b(r,t);return r.map(e=>f(void 0,o.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return o.warn("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=h(e),o=await this.getRestClient(t).request(d(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return l(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=/* @__PURE__ */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 f(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>f(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){o.warn("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:f(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:f(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:f(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ce.key="chatRoomManager";let ue=ce;export{p as ChatRoom,ue as ChatRoomManager};
1
+ import{E as e,p as t,V as r,l as o,S as a,M as s,h as n,m as i,j as c}from"../../chunks/common-BvlDAw4a.js";import{c as m}from"../../chunks/event-system-B62vbKqG.js";import{c as u}from"../../chunks/query-params-Bu3Xq4b6.js";import{i as h}from"../../chunks/cache-utils-B99glc0H.js";import{b as d,a as l,n as p}from"../../chunks/user-info-AlshAvdy.js";class R{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 g=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],I=e=>{const t=[],r=/* @__PURE__ */new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},y=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),f=e=>({userId:e}),b=(e,t,r)=>{const o={userId:r};for(const a of g){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},C=async(e,t)=>{const r=I(e),o=/* @__PURE__ */new Map;if(0===r.length)return o;const a=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const n of a)o.set(n.userId,y(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,f(n));return o},w=e=>h(e)?e:null,_=e=>"string"==typeof e?e:void 0,A=e=>{const t=_(e)?.trim();return t||void 0},M=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}},v=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},U=e=>{const t=w(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},O=e=>{const t=w(e);return t?w(t.data)?t.data:t:null},E=(e,t)=>{const r=w(e),o=r&&w(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return M(a[0])},S=e=>A(e.chatRoomId)??A(e.chatroomid)??A(e.id)??"",T=e=>_(e.name)??_(e.title)??_(e.groupname)??"",x=e=>f(e),k=(e,t)=>{const r=(e=>{const t=_(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(A(e.owner)===t)return"owner";const o=Array.isArray(e.affiliations)?e.affiliations:[];for(const a of o){const e=w(a);if(e){if(A(e.owner)===t)return"owner";if(A(e.admin)===t)return"admin";if(A(e.member)===t)return"member"}}},$=(e,t)=>{const r=w(e);if(!r)return null;const o=S(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)})(A(r.owner)):A(r.owner);return{chatRoomId:o,name:T(r),owner:a?x(a):void 0,memberCount:M(r.memberCount)??M(r.affiliations_count),disabled:v(r.disabled)}},L=(e,t)=>{const r=(e=>{const t=w(e);return t?M(t.count):void 0})(e),o=U(e).map(e=>$(e,t)).filter(e=>null!==e),a=E(e,"pagenum"),s=E(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}},N=e=>U(e).map(e=>A(e)).filter(e=>Boolean(e)).map(e=>x(e)),D=(e,t)=>{const r=O(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=w(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:B(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},F=e=>{const t=w(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=w(e),r=(e=>{const t=w(e);if(!t)return null;const r=A(t.user),o=A(t.chatRoomId)??A(t.chatroomid)??A(t.id),a=_(t.action),s=v(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:x(r),action:a,reason:_(t.reason),...s?{}:{reason:_(t.reason)??"failed"}}:null})(e);if(!r||!t)return;v(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},B=t=>t.includes("is exceeding maximum limit")||t.includes("size of metadata")&&t.includes("exceeds")?e.SERVICE_LIMIT_EXCEEDED:t.includes("is not part of you")?e.CHATROOM_PERMISSION_DENIED:t.includes("is not Legal")||t.includes("is not exist")?e.VALIDATION_REQUIRED:e.REST_BUSINESS_UNKNOWN,j=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},z=t=>new r(`${t} is required`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),V=(t,o)=>new r(o,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:o,rule:"invalid_format"}]}}),P=(e,t)=>`/${e.orgName}/${e.appName}${t}`,q=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw V(t,`${t} must be a string`);return e}},H=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw V(t,`${t} must be a number`);return e}},W=(e,t)=>{const r=u();"number"==typeof e?.pageNum&&r.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&r.set("pagesize",String(e.pageSize));const o=r.toString();return o?`?${o}`:""},K=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw z(t);return e.trim()},G=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw z(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,a)=>{if("string"!=typeof e)throw V(`${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 z(t);return r},X=(e,t)=>G(e,t),Q=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true&version=v3`);return((e,t)=>{const r=U(e),o=w(r[0])??O(e)??{},a=$(o)??{chatRoomId:S(o),name:T(o)},s=k(o,t);return{...a,description:_(o.description),maxMembers:M(o.maxMembers)??M(o.maxusers)??M(o.max_users),createdAt:M(o.createdAt)??M(o.created),ext:_(o.ext)??_(o.custom),muteAllMembers:v(o.mute),permissionType:s}})(await e.get(s,{operation:"getChatRoomInfo"}),t.userId)},J=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s={},n=q(r.name,"params.name"),i=q(r.description,"params.description"),c=H(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 z("params");const m=P(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=O(e)??{};return{nameUpdated:v(t.groupname),descriptionUpdated:v(t.description),maxMembersUpdated:v(t.maxusers)}})(await e.put(m,s,{operation:"updateChatRoomInfo"}))},Y=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/users${(e=>{const t=u();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const r=t.toString();return r?`?${r}`:""})(r)}`);return(e=>{const t=[];for(const a of U(e)){const e=w(a);if(!e)continue;const r=A(e.owner),o=A(e.admin),s=A(e.member),n=r??o??s;n&&t.push({user:x(n),role:r?"owner":o?"admin":"member",joinedAt:M(e.joinedAt)??M(e.joined_time)})}const r=w(e),o=r?A(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(s,{operation:"getChatRoomMemberList"}))},Z=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return N(n)},ee=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=u();s.set("version","v3"),"number"==typeof r.pageNum&&s.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&s.set("pagesize",String(r.pageSize));const n=P(o,`/chatrooms/${encodeURIComponent(a)}/mute?${s.toString()}`);return(e=>{const t=U(e);if(t.every(e=>"string"==typeof e))return N(e).map(e=>({user:e}));const r=[];for(const o of t){const e=w(o);if(!e)continue;const t=A(e.user)??A(e.member)??A(e.owner)??A(e.admin);t&&r.push({user:x(t),muteExpire:M(e.muteExpire)??M(e.expire)??M(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(n,{operation:"getChatRoomMuteList"}))},te=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=O(e)??{};return{muted:v(t.muted)??v(t.value)??Boolean(t.data),muteExpireAt:M(t.muteExpireAt)??M(t.expire)??M(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},re=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=W(r),n=s?"&":"",i=P(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return N(c).map(e=>({user:e}))},oe=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return N(n).map(e=>({user:e}))},ae=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=O(e)??{};return v(t.value)??v(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},se=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=O(e)??{};return{announcement:_(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},ne=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(o,`/metadata/chatroom/${encodeURIComponent(a)}`);return((e,t)=>{const r=O(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(s,{keys:r.keys?X(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},ie=async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw V(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw z(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw V(t,`${t} contains invalid key`);if("string"!=typeof r)throw V(`${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=P(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),u=await e.put(m,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return D(u,a)},ce={onChatRoomDestroyed:m.CHAT_ROOM_DESTROYED,onMembersJoined:m.MEMBERS_JOINED,onMembersExited:m.MEMBERS_EXITED,onRemovedFromChatRoom:m.REMOVED_FROM_CHAT_ROOM,onMuteListAdded:m.MUTE_LIST_ADDED,onMuteListRemoved:m.MUTE_LIST_REMOVED,onAllowListAdded:m.ALLOW_LIST_ADDED,onAllowListRemoved:m.ALLOW_LIST_REMOVED,onAllMemberMuteStateChanged:m.ALL_MEMBER_MUTE_STATE_CHANGED,onAdminAdded:m.ADMIN_ADDED,onAdminRemoved:m.ADMIN_REMOVED,onOwnerChanged:m.OWNER_CHANGED,onAnnouncementChanged:m.ANNOUNCEMENT_CHANGED,onChatRoomInfoChanged:m.CHAT_ROOM_INFO_CHANGED,onAttributesUpdate:m.ATTRIBUTES_UPDATE,onAttributesRemoved:m.ATTRIBUTES_REMOVED},me=i(c,{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}}}}}),ue=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=/* @__PURE__ */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=ce[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=ce[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=j(t),a=P(o,`/chatrooms${W(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return L(s)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(t){this.requireClient();const o=t.trim();if(0===o.length)throw new r("chatRoomId is required",{code:e.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const a=this.chatRoomRegistry.get(o);if(a)return a;const s=new R(o,this);return this.chatRoomRegistry.set(o,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await Q(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=K(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=K(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 Y(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await Z(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=K(r.userId,"params.userId"),n=P(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=K(r.userId,"params.userId"),n=P(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 ee(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=H(r.duration,"params.duration"),i=P(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=P(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 te(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await re(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=1===s.length,i=P(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 F(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await oe(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return F(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=G(r.userIds,"params.userIds"),n=P(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return F(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return ae(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return se(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=q(r.announcement,"params.announcement");if(void 0===s)throw z("params.announcement");const n=P(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 ne(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await ie(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=j(t),a=K(r.chatRoomId,"params.chatRoomId"),s=X(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=P(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),m=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return D(m,a)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw o.warn(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(t,r){return r instanceof a?r:r instanceof Error?new a(`ChatRoomManager ${t} failed: ${r.message}`,e.UNKNOWN):new a(`ChatRoomManager ${t} failed`,e.UNKNOWN)}remapChatRoomOperationError(t,r){return r instanceof a&&r.code===e.GROUP_NOT_EXIST?new s("Chat room does not exist",{code:e.CHATROOM_NOT_EXIST,details:{...r.details,api:t,originalCode:r.code,canonicalCode:e.CHATROOM_NOT_EXIST,retryable:!1}}):r}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new a(e.message,e.code)}return e}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new n(e.restBaseUrl,{errorMap:me,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new a("ChatRoomManager is not bound to client",e.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(t,o){if(void 0!==t){if("string"!=typeof t)throw new r(`${o} must be a string`,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:o,message:`${o} must be a string`,rule:"invalid_format"}]}});return t}}normalizeOptionalBoolean(t,o){if(void 0!==t){if("boolean"!=typeof t)throw new r(`${o} must be a boolean`,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:o,message:`${o} 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(e){return C(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return o.warn("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=I(e),o=await C(r,t);return r.map(e=>b(void 0,o.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return o.warn("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=d(e),o=await this.getRestClient(t).request(l(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return p(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=/* @__PURE__ */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 b(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>b(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){o.warn("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:b(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:b(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:b(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ue.key="chatRoomManager";let he=ue;export{R as ChatRoom,he as ChatRoomManager};
@@ -111,7 +111,7 @@ export declare class ChatRoomManager implements ManagerBase<ChatClient> {
111
111
  * @param params - [zh-CN] 查询参数,包含必填 `chatRoomId`。 [en-US] Query parameters containing the required `chatRoomId`.
112
112
  * @operation getChatRoomInfo
113
113
  * @throws {ValidationError} [zh-CN] 错误码 `110`:`chatRoomId` 为空或格式非法。解决方式:传入有效聊天室 ID。 [en-US] Error code `110`: `chatRoomId` is empty or invalid. Pass a valid chat room ID.
114
- * @returns {Promise<ChatRoomDetail>} [zh-CN] 返回聊天室详情、公告、权限与当前用户状态。 [en-US] Returns chat room details, announcement, permission, and current user status.
114
+ * @returns {Promise<ChatRoomDetail>} [zh-CN] 返回聊天室详情与当前用户权限。 [en-US] Returns chat room details and the current user's permission.
115
115
  */
116
116
  getChatRoomInfo(params: GetChatRoomInfoParams): Promise<ChatRoomDetail>;
117
117
  /**
@@ -575,6 +575,11 @@ export declare class ChatRoomManager implements ManagerBase<ChatClient> {
575
575
  removeAttributes(params: RemoveChatRoomAttributesParams): Promise<ChatRoomAttributeMutationResult>;
576
576
  private runOperation;
577
577
  private normalizeSdkError;
578
+ /**
579
+ * MSync 将聊天室与群组的底层资源不存在统一报告为群组错误。
580
+ * 在聊天室公开 API 边界按调用上下文转换为聊天室错误码。
581
+ */
582
+ private remapChatRoomOperationError;
578
583
  /**
579
584
  * FR-051: 属性批量操作结果检查。
580
585
  * 所有 key 都失败 → 抛出 SDKError(取第一个 errorKey 的映射码)。
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-BsIqq7LU.cjs");exports.ContactManager=e.ContactManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-DtWkVcfb.cjs");exports.ContactManager=e.ContactManager;
@@ -1 +1 @@
1
- import{C as a}from"../../chunks/index-BmwQgZ3E.js";export{a as ContactManager};
1
+ import{C as a}from"../../chunks/index-BBFJYOM8.js";export{a as ContactManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-Dvvh1nf6.cjs");exports.Group=e.Group,exports.GroupManager=e.GroupManager;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-DJPAjXAp.cjs");exports.Group=e.Group,exports.GroupManager=e.GroupManager;
@@ -1 +1 @@
1
- import{G as r,a as o}from"../../chunks/index-CFMcR5a_.js";export{r as Group,o as GroupManager};
1
+ import{G as r,a as o}from"../../chunks/index-l_BUKi77.js";export{r as Group,o as GroupManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-BIpcR2uQ.cjs"),t=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),r=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(t){return this.runOperation("publishPresence",async()=>{this.validateDescription(t.customStatus);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/${r.clientResource}/1`,o={ext:t.customStatus};e.logger.debug("Call publishPresence",{customStatus:t.customStatus}),await s.request(n,{method:"POST",body:o,operation:"publishPresence"})})}async subscribePresence(t){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(t.userIds),this.validateExpiry(t.expiry);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/${t.expiry}`,o={usernames:t.userIds};e.logger.debug("Call subscribePresence",{userIds:t.userIds,expiry:t.expiry});const u=await s.request(n,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(u)})}async unsubscribePresence(t){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence`;e.logger.debug("Call unsubscribePresence",{userIds:t.userIds}),await s.request(n,{method:"DELETE",body:t.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(t){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(t.pageNum,t.pageSize);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/sublist?pageNum=${t.pageNum}&pageSize=${t.pageSize}`;e.logger.debug("Call getSubscribedPresenceList",{pageNum:t.pageNum,pageSize:t.pageSize});const o=await s.request(n,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(t){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence`,o={usernames:t.userIds};e.logger.debug("Call getPresenceStatus",{userIds:t.userIds});const u=await s.request(n,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(u)})}async runOperation(t,r){try{return await r()}catch(s){const r=this.normalizeSdkError(t,s);throw e.logger.warn(`PresenceManager ${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(`PresenceManager ${t} failed: ${r.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`PresenceManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new e.ValidationError("PresenceManager is not bound to event context",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new e.ValidationError("PresenceManager is not bound to client",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(r){return this.restClient&&this.restBaseUrl===r.restBaseUrl&&this.restToken===r.token||(this.restClient=new e.RestClient(r.restBaseUrl,{errorMap:t,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(r.token),this.restBaseUrl=r.restBaseUrl,this.restToken=r.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,i]of Object.entries(e))if("number"==typeof i&&Number.isFinite(i))r[s]=Math.trunc(i);else if("string"==typeof i&&i.trim().length>0){const e=Number(i);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(t){return new e.ValidationError("Invalid parameters",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};r.key="presenceManager";let s=r;exports.PresenceManager=s;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-tHGz9VBk.cjs"),t=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),r=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(t){return this.runOperation("publishPresence",async()=>{this.validateDescription(t.customStatus);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/${r.clientResource}/1`,o={ext:t.customStatus};e.logger.debug("Call publishPresence",{customStatus:t.customStatus}),await s.request(n,{method:"POST",body:o,operation:"publishPresence"})})}async subscribePresence(t){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(t.userIds),this.validateExpiry(t.expiry);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/${t.expiry}`,o={usernames:t.userIds};e.logger.debug("Call subscribePresence",{userIds:t.userIds,expiry:t.expiry});const u=await s.request(n,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(u)})}async unsubscribePresence(t){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence`;e.logger.debug("Call unsubscribePresence",{userIds:t.userIds}),await s.request(n,{method:"DELETE",body:t.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(t){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(t.pageNum,t.pageSize);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence/sublist?pageNum=${t.pageNum}&pageSize=${t.pageSize}`;e.logger.debug("Call getSubscribedPresenceList",{pageNum:t.pageNum,pageSize:t.pageSize});const o=await s.request(n,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(t){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:i,appName:a}=this.parseAppKey(r.appKey),n=`/${i}/${a}/users/${r.userId}/presence`,o={usernames:t.userIds};e.logger.debug("Call getPresenceStatus",{userIds:t.userIds});const u=await s.request(n,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(u)})}async runOperation(t,r){try{return await r()}catch(s){const r=this.normalizeSdkError(t,s);throw e.logger.warn(`PresenceManager ${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(`PresenceManager ${t} failed: ${r.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`PresenceManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new e.ValidationError("PresenceManager is not bound to event context",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new e.ValidationError("PresenceManager is not bound to client",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(r){return this.restClient&&this.restBaseUrl===r.restBaseUrl&&this.restToken===r.token||(this.restClient=new e.RestClient(r.restBaseUrl,{errorMap:t,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(r.token),this.restBaseUrl=r.restBaseUrl,this.restToken=r.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,i]of Object.entries(e))if("number"==typeof i&&Number.isFinite(i))r[s]=Math.trunc(i);else if("string"==typeof i&&i.trim().length>0){const e=Number(i);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(t){return new e.ValidationError("Invalid parameters",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};r.key="presenceManager";let s=r;exports.PresenceManager=s;
@@ -1 +1 @@
1
- import{l as e,S as t,E as r,V as s,f as a,m as i,i as n}from"../../chunks/common-D_DfwSd3.js";const u=i(n,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),o=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(t){return this.runOperation("publishPresence",async()=>{this.validateDescription(t.customStatus);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/${r.clientResource}/1`,u={ext:t.customStatus};e.debug("Call publishPresence",{customStatus:t.customStatus}),await s.request(n,{method:"POST",body:u,operation:"publishPresence"})})}async subscribePresence(t){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(t.userIds),this.validateExpiry(t.expiry);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/${t.expiry}`,u={usernames:t.userIds};e.debug("Call subscribePresence",{userIds:t.userIds,expiry:t.expiry});const o=await s.request(n,{method:"POST",body:u,operation:"subscribePresences"});return this.normalizeSubscribeResponse(o)})}async unsubscribePresence(t){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence`;e.debug("Call unsubscribePresence",{userIds:t.userIds}),await s.request(n,{method:"DELETE",body:t.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(t){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(t.pageNum,t.pageSize);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/sublist?pageNum=${t.pageNum}&pageSize=${t.pageSize}`;e.debug("Call getSubscribedPresenceList",{pageNum:t.pageNum,pageSize:t.pageSize});const u=await s.request(n,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(u)})}async getPresenceStatus(t){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence`,u={usernames:t.userIds};e.debug("Call getPresenceStatus",{userIds:t.userIds});const o=await s.request(n,{method:"POST",body:u,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(o)})}async runOperation(t,r){try{return await r()}catch(s){const r=this.normalizeSdkError(t,s);throw e.warn(`PresenceManager ${t} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(e,s){return s instanceof t?s:s instanceof Error?new t(`PresenceManager ${e} failed: ${s.message}`,r.UNKNOWN):new t(`PresenceManager ${e} failed`,r.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new s("PresenceManager is not bound to event context",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new s("PresenceManager is not bound to client",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new a(e.restBaseUrl,{errorMap:u,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,a]of Object.entries(e))if("number"==typeof a&&Number.isFinite(a))r[s]=Math.trunc(a);else if("string"==typeof a&&a.trim().length>0){const e=Number(a);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new s("Invalid parameters",{code:r.VALIDATION_INVALID_FORMAT,details:{fields:e}})}};o.key="presenceManager";let l=o;export{l as PresenceManager};
1
+ import{l as e,S as t,E as r,V as s,h as a,m as i,j as n}from"../../chunks/common-BvlDAw4a.js";const u=i(n,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),o=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(t){return this.runOperation("publishPresence",async()=>{this.validateDescription(t.customStatus);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/${r.clientResource}/1`,u={ext:t.customStatus};e.debug("Call publishPresence",{customStatus:t.customStatus}),await s.request(n,{method:"POST",body:u,operation:"publishPresence"})})}async subscribePresence(t){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(t.userIds),this.validateExpiry(t.expiry);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/${t.expiry}`,u={usernames:t.userIds};e.debug("Call subscribePresence",{userIds:t.userIds,expiry:t.expiry});const o=await s.request(n,{method:"POST",body:u,operation:"subscribePresences"});return this.normalizeSubscribeResponse(o)})}async unsubscribePresence(t){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence`;e.debug("Call unsubscribePresence",{userIds:t.userIds}),await s.request(n,{method:"DELETE",body:t.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(t){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(t.pageNum,t.pageSize);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence/sublist?pageNum=${t.pageNum}&pageSize=${t.pageSize}`;e.debug("Call getSubscribedPresenceList",{pageNum:t.pageNum,pageSize:t.pageSize});const u=await s.request(n,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(u)})}async getPresenceStatus(t){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(t.userIds);const r=this.getRestContextOrThrow(),s=this.getRestClient(r),{orgName:a,appName:i}=this.parseAppKey(r.appKey),n=`/${a}/${i}/users/${r.userId}/presence`,u={usernames:t.userIds};e.debug("Call getPresenceStatus",{userIds:t.userIds});const o=await s.request(n,{method:"POST",body:u,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(o)})}async runOperation(t,r){try{return await r()}catch(s){const r=this.normalizeSdkError(t,s);throw e.warn(`PresenceManager ${t} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(e,s){return s instanceof t?s:s instanceof Error?new t(`PresenceManager ${e} failed: ${s.message}`,r.UNKNOWN):new t(`PresenceManager ${e} failed`,r.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new s("PresenceManager is not bound to event context",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new s("PresenceManager is not bound to client",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new a(e.restBaseUrl,{errorMap:u,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,a]of Object.entries(e))if("number"==typeof a&&Number.isFinite(a))r[s]=Math.trunc(a);else if("string"==typeof a&&a.trim().length>0){const e=Number(a);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new s("Invalid parameters",{code:r.VALIDATION_INVALID_FORMAT,details:{fields:e}})}};o.key="presenceManager";let l=o;export{l as PresenceManager};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-BIpcR2uQ.cjs"),t=require("../../chunks/session-list-query-C4OQMvPf.cjs"),n=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),r=["singleChat","groupChat"],o=["ALL","AT","NONE","DEFAULT"],i=["ALL","AT","NONE"],a=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),s=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e}async uploadPushToken(t){return this.runOperation(async()=>{this.validateUploadPushTokenParams(t);const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}`;e.logger.debug("Call uploadPushToken",{deviceId:t.deviceId,notifierName:t.notifierName}),await r.request(a,{method:"PUT",body:{device_id:t.deviceId,device_token:t.deviceToken,notifier_name:t.notifierName},operation:"uploadPushToken"})})}async setGlobalSilentMode(t){return this.runOperation(async()=>{this.validateRuleInput(t.rule,"rule");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}/notification/user/${n.userId}?resource=${encodeURIComponent(n.clientResource)}`,s=this.buildSilentModePayload(t.rule);e.logger.debug("Call setGlobalSilentMode",{mode:t.rule.mode});const l=await r.request(a,{method:"PUT",body:s,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),t.rule)}})}async getGlobalSilentMode(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),{orgName:r,appName:o}=this.parseAppKey(t.appKey),i=`/${r}/${o}/users/${t.userId}/notification/user/${t.userId}`;e.logger.debug("Call getGlobalSilentMode");const a=await n.request(i,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async setConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType"),this.validateRuleInput(t.rule,"rule");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(n.clientResource)}`,l=this.buildSilentModePayload(t.rule);e.logger.debug("Call setConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType,mode:t.rule.mode});const u=await r.request(s,{method:"PUT",body:l,operation:"setConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(u),t.rule)}})}async getConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}`;e.logger.debug("Call getConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await r.request(s,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l))}})}async clearConversationRemindType(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(n.clientResource)}`;e.logger.debug("Call clearConversationRemindType",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await r.request(s,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),{remindType:"DEFAULT"})}})}async getConversationSilentModes(t){return this.runOperation(async()=>{this.validateConversationList(t.conversationList,"conversationList");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=t.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),s=t.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),l=`/${o}/${i}/users/${n.userId}/notification?user=${a}&group=${s}`;e.logger.debug("Call getConversationSilentModes",{count:t.conversationList.length});const u=await r.request(l,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(u,"user"),p=this.resolveConversationRuleMap(u,"group");return{conversations:t.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:p[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(t){await this.runOperation(async()=>{this.validateLanguage(t.language,"language");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}/notification/language`;e.logger.debug("Call setPushLanguage",{language:t.language}),await r.request(a,{method:"PUT",body:{translationLanguage:t.language},operation:"setPushLanguage"})})}async getPushLanguage(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),{orgName:r,appName:o}=this.parseAppKey(t.appKey),i=`/${r}/${o}/users/${t.userId}/notification/language`;e.logger.debug("Call getPushLanguage");const a=await n.request(i,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(a,"")}})}getConversationListByRemindType(n){return this.runOperation(()=>{e.logger.debug("Call getConversationListByRemindType",{pageSize:n.pageSize,hasCursor:Boolean(n.cursor)});const r=this.getClientOrThrow(),o=t.queryMutedConversationsFromSessionList({items:r.getCacheManager()?.loadSessionList()??[],pageSize:n.pageSize,cursor:n.cursor});return Promise.resolve(o)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(t){return t instanceof e.SDKError?t:t instanceof Error?new e.SDKError(`PushManager operation failed: ${t.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError("PushManager operation failed",e.ERROR_CODES.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:n,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}getClientOrThrow(){if(!this.client)throw new e.SDKError("PushManager is not bound to client",e.ERROR_CODES.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!r.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,n)=>{this.validateConversationId(e.conversationId,`${t}[${n}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${n}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!a(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!i.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,n){const r=Object.keys(e).find(e=>!n.includes(e));if(r)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${r}`,message:`${r} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!a(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const n=this.parseRuleView(e);return n?t?{...this.toRuleViewFromFallback(t),...n}:n:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!a(e))return null;const t={},n=this.normalizeRemindType(e.type);null!==n&&(t.remindType=n);const r=e.ignoreDuration;"number"==typeof r&&Number.isInteger(r)&&r>0&&(t.expireTimestamp=r);const o=e.ignoreInterval;if("string"==typeof o){const e=this.parseInterval(o);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const n=Number(t[1]),r=Number(t[2]),o=Number(t[3]),i=Number(t[4]);return Number.isInteger(n)&&Number.isInteger(r)&&Number.isInteger(o)&&Number.isInteger(i)?n<0||n>23||o<0||o>23||r<0||r>59||i<0||i>59?null:{startTime:{hours:n,minutes:r},endTime:{hours:o,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(a(e.data)){const n=e.data[t];if(a(n))return n}const n=e[t];return a(n)?n:{}}resolveSilentModeRuleSource(e){if(!a(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return a(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":o.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(a(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const n=e.data.language;if("string"==typeof n&&n.length>0)return n}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(t,n){return new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:n}})}};s.key="pushManager";let l=s;exports.PushManager=l;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-tHGz9VBk.cjs"),t=require("../../chunks/event-system-TYhmgy4K.cjs"),i=require("../../chunks/session-list-query-Dslj2k3t.cjs"),n=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],s=(t,i,n="invalid_format")=>new e.ValidationError(i,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:i,rule:n}]}}),r=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw s(t,`${t} must be a non-empty string`);return e.trim()}},o=e=>8===e?"normal":n[e]??"normal",a=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class l{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=new Set}configure(t){const i=(e=>{if(!e||"object"!=typeof e)throw s("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw s("plugin","plugin is required","required");const i=t;if("function"!=typeof i.onRegister)throw s("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof i.unRegister)throw s("plugin.unRegister","plugin.unRegister must be a function");const o=e.certificates;if(!o||"object"!=typeof o)throw s("certificates","certificates is required","required");const a=o,l={apns:r(a.apns,"certificates.apns"),fcm:r(a.fcm,"certificates.fcm"),huawei:r(a.huawei,"certificates.huawei"),xiaomi:r(a.xiaomi,"certificates.xiaomi"),meizu:r(a.meizu,"certificates.meizu"),vivo:r(a.vivo,"certificates.vivo"),oppo:r(a.oppo,"certificates.oppo"),honor:r(a.honor,"certificates.honor")};if(!n.some(e=>void 0!==l[e]))throw s("certificates","at least one native push certificate is required");return{plugin:t,certificates:l,signature:n.map(e=>`${e}:${l[e]??""}`).join("|")}})(t),o=null!==this.config&&"disabled"!==this.state,a=this.config?.plugin===i.plugin&&this.config.signature===i.signature;if(o&&!a)throw new e.ValidationError("Native push is enabled; call removePushToken() before replacing its configuration",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});o&&a&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=i,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const i of this.collectRemovalTargets(e.generation)){const n=await this.removeWithRetry(i,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!n){this.emitFailure(t.PushEventName.TOKEN_REMOVE_FAILED,"remove",i.channel,i.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,i=this.session.generation,n=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(s=>{if(!this.isRegistrationActive(i,n))return;const r=((e,t)=>{if(!a(e)||200!==e.code||0===e.push_token.trim().length)return null;const i=o(e.push_type);if("normal"===i)return null;const n=t.certificates[i];return n?{token:e.push_token,channel:i,notifierName:n}:null})(s,e);if(!r){this.state="failed";const i=a(s)?o(s.push_type):void 0,n=a(s)&&200===s.code&&s.push_token.trim().length>0&&void 0!==i&&"normal"!==i&&void 0===e.certificates[i];return void this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,n?"bind":"register",i)}this.enqueueBinding(r)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const i=this.session.generation,n=this.createBindingKey(e);this.activeBindingKey=n,this.state="binding";const s=await this.bindWithRetry(e,i);if(this.activeBindingKey=null,!this.session||this.session.generation!==i||this.disabledByUser)return;s?(this.binding={...e,generation:i,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=n,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===i||this.manualRemovalInProgress||this.dependencies.dispatch(t.PushEventName.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=n,this.state="failed",this.sessionEndingGeneration===i||this.manualRemovalInProgress||this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(t,i){this.lastBindingError=null;for(let s=0;s<=e.NATIVE_PUSH_BIND_MAX_RETRIES;s+=1)try{const n=this.session;return!(!n||n.generation!==i)&&(this.lastAttemptedBinding={...t,generation:i,userId:n.userId,deviceId:n.clientResource},await this.dependencies.requestToken({deviceId:n.clientResource,deviceToken:t.token,notifierName:t.notifierName,timeout:e.NATIVE_PUSH_BIND_REQUEST_TIMEOUT}),!0)}catch(n){if(this.lastBindingError=this.toSdkError(n),!this.session||this.session.generation!==i)return!1;if(!this.isRetryable(n)||s===e.NATIVE_PUSH_BIND_MAX_RETRIES)return!1;const t=e.NATIVE_PUSH_BIND_RETRY_DELAYS[s]??0;if(!(await this.wait(t)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN);const i=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(i))throw this.manualRemovalInProgress=!1,new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN);const n=this.collectRemovalTargets(i);if(0!==n.length)try{for(const e of n)if(await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName}),!this.isSessionGenerationActive(i))return;this.disableByUser()}catch(s){const e=this.toSdkError(s),r=n[0];throw r&&this.isSessionGenerationActive(i)&&this.emitFailure(t.PushEventName.TOKEN_REMOVE_FAILED,"remove",r.channel,r.notifierName,e),this.manualRemovalInProgress=!1,this.resumePendingBinding(i),e}else this.disableByUser()}async removeWithRetry(t,i){this.lastRemovalError=null;for(let s=0;s<=e.NATIVE_PUSH_REMOVE_MAX_RETRIES;s+=1)try{return await this.dependencies.requestToken({deviceId:t.deviceId,deviceToken:"",notifierName:t.notifierName,timeout:e.NATIVE_PUSH_REMOVE_REQUEST_TIMEOUT}),!0}catch(n){if(this.lastRemovalError=this.toSdkError(n),!this.isSessionGenerationActive(i))return!1;if(!this.isRetryable(n)||s===e.NATIVE_PUSH_REMOVE_MAX_RETRIES)return!1;if(!(await this.wait(e.NATIVE_PUSH_REMOVE_RETRY_DELAY)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,i)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===i)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{e.logger.warn("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const i={timer:setTimeout(()=>{this.delays.delete(i),t(!0)},e),resolve:t};this.delays.add(i)})}isRetryable(t){return!(t instanceof e.SDKError)||(!0===t.details?.retryable||[e.ERROR_CODES.REST_NETWORK_ERROR,e.ERROR_CODES.REST_TIMEOUT,e.ERROR_CODES.REST_HTTP_ERROR,e.ERROR_CODES.SERVER_BUSY].includes(t.code))}toSdkError(t){return t instanceof e.SDKError?t:new e.SDKError("Native push operation failed",e.ERROR_CODES.UNKNOWN)}emitFailure(t,i,n,s,r){const o=!!r&&this.isRetryable(r);this.dependencies.dispatchFailure(t,{stage:i,...n?{channel:n}:{},...s?{notifierName:s}:{},...r?{code:r.code}:{},retryable:o}),e.logger.warn("Native push operation failed",{stage:i,...n?{channel:n}:{},...s?{notifierName:s}:{},...r?{code:r.code}:{},retryable:o})}}const u=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),d=["singleChat","groupChat"],h=["ALL","AT","NONE","DEFAULT"],c=["ALL","AT","NONE"],g=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),m=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new l({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(t){const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey);e.logger.debug("Call native push token operation",{deviceId:t.deviceId,notifierName:t.notifierName,removing:0===t.deviceToken.length}),await n.request(`/${s}/${r}/users/${i.userId}`,{method:"PUT",body:{device_id:t.deviceId,device_token:t.deviceToken,notifier_name:t.notifierName},operation:"uploadPushToken",...void 0!==t.timeout?{timeout:t.timeout}:{}})}async setGlobalSilentMode(t){return this.runOperation(async()=>{this.validateRuleInput(t.rule,"rule");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=`/${s}/${r}/users/${i.userId}/notification/user/${i.userId}?resource=${encodeURIComponent(i.clientResource)}`,a=this.buildSilentModePayload(t.rule);e.logger.debug("Call setGlobalSilentMode",{mode:t.rule.mode});const l=await n.request(o,{method:"PUT",body:a,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),t.rule)}})}async getGlobalSilentMode(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/user/${t.userId}`;e.logger.debug("Call getGlobalSilentMode");const o=await i.request(r,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(o))}})}async setConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType"),this.validateRuleInput(t.rule,"rule");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(i.clientResource)}`,l=this.buildSilentModePayload(t.rule);e.logger.debug("Call setConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType,mode:t.rule.mode});const u=await n.request(a,{method:"PUT",body:l,operation:"setConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(u),t.rule)}})}async getConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}`;e.logger.debug("Call getConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await n.request(a,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l))}})}async clearConversationRemindType(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(i.clientResource)}`;e.logger.debug("Call clearConversationRemindType",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await n.request(a,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),{remindType:"DEFAULT"})}})}async getConversationSilentModes(t){return this.runOperation(async()=>{this.validateConversationList(t.conversationList,"conversationList");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=t.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=t.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),l=`/${s}/${r}/users/${i.userId}/notification?user=${o}&group=${a}`;e.logger.debug("Call getConversationSilentModes",{count:t.conversationList.length});const u=await n.request(l,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(u,"user"),h=this.resolveConversationRuleMap(u,"group");return{conversations:t.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:h[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(t){await this.runOperation(async()=>{this.validateLanguage(t.language,"language");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=`/${s}/${r}/users/${i.userId}/notification/language`;e.logger.debug("Call setPushLanguage",{language:t.language}),await n.request(o,{method:"PUT",body:{translationLanguage:t.language},operation:"setPushLanguage"})})}async getPushLanguage(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/language`;e.logger.debug("Call getPushLanguage");const o=await i.request(r,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(o,"")}})}getConversationListByRemindType(t){return this.runOperation(()=>{e.logger.debug("Call getConversationListByRemindType",{pageSize:t.pageSize,hasCursor:Boolean(t.cursor)});const n=this.getClientOrThrow(),s=i.queryMutedConversationsFromSessionList({items:n.getCacheManager()?.loadSessionList()??[],pageSize:t.pageSize,cursor:t.cursor});return Promise.resolve(s)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(t){return t instanceof e.SDKError?t:t instanceof Error?new e.SDKError(`PushManager operation failed: ${t.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError("PushManager operation failed",e.ERROR_CODES.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:u,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}getClientOrThrow(){if(!this.client)throw new e.SDKError("PushManager is not bound to client",e.ERROR_CODES.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!d.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,i)=>{this.validateConversationId(e.conversationId,`${t}[${i}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${i}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!g(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!c.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,i){const n=Object.keys(e).find(e=>!i.includes(e));if(n)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${n}`,message:`${n} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!g(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const i=this.parseRuleView(e);return i?t?{...this.toRuleViewFromFallback(t),...i}:i:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!g(e))return null;const t={},i=this.normalizeRemindType(e.type);null!==i&&(t.remindType=i);const n=e.ignoreDuration;"number"==typeof n&&Number.isInteger(n)&&n>0&&(t.expireTimestamp=n);const s=e.ignoreInterval;if("string"==typeof s){const e=this.parseInterval(s);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),r=Number(t[4]);return Number.isInteger(i)&&Number.isInteger(n)&&Number.isInteger(s)&&Number.isInteger(r)?i<0||i>23||s<0||s>23||n<0||n>59||r<0||r>59?null:{startTime:{hours:i,minutes:n},endTime:{hours:s,minutes:r}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(g(e.data)){const i=e.data[t];if(g(i))return i}const i=e[t];return g(i)?i:{}}resolveSilentModeRuleSource(e){if(!g(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return g(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":h.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(g(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const i=e.data.language;if("string"==typeof i&&i.length>0)return i}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(t,i){return new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:i}})}};m.key="pushManager";let p=m;exports.PushManager=p;
@@ -1 +1,3 @@
1
1
  export { PushManager } from '../push-manager';
2
+ export type { NativePushCertificates, NativePushChannel, NativePushPlugin, NativePushTokenResult, NativePushTypeCode, PushTokenBoundEvent, PushTokenOperationFailedEvent, SetNativePushOptions, } from '../../types/push';
3
+ export type { PushEventHandlerMap, PushEventPayloadMap } from '../../types/event-system';
@@ -1 +1 @@
1
- import{l as e,S as t,E as n,f as r,V as o,m as i,i as a}from"../../chunks/common-D_DfwSd3.js";import{q as s}from"../../chunks/session-list-query-rynxSxtv.js";const l=i(a,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),u=["singleChat","groupChat"],d=["ALL","AT","NONE","DEFAULT"],p=["ALL","AT","NONE"],c=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),h=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e}async uploadPushToken(t){return this.runOperation(async()=>{this.validateUploadPushTokenParams(t);const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}`;e.debug("Call uploadPushToken",{deviceId:t.deviceId,notifierName:t.notifierName}),await r.request(a,{method:"PUT",body:{device_id:t.deviceId,device_token:t.deviceToken,notifier_name:t.notifierName},operation:"uploadPushToken"})})}async setGlobalSilentMode(t){return this.runOperation(async()=>{this.validateRuleInput(t.rule,"rule");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}/notification/user/${n.userId}?resource=${encodeURIComponent(n.clientResource)}`,s=this.buildSilentModePayload(t.rule);e.debug("Call setGlobalSilentMode",{mode:t.rule.mode});const l=await r.request(a,{method:"PUT",body:s,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),t.rule)}})}async getGlobalSilentMode(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),{orgName:r,appName:o}=this.parseAppKey(t.appKey),i=`/${r}/${o}/users/${t.userId}/notification/user/${t.userId}`;e.debug("Call getGlobalSilentMode");const a=await n.request(i,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async setConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType"),this.validateRuleInput(t.rule,"rule");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(n.clientResource)}`,l=this.buildSilentModePayload(t.rule);e.debug("Call setConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType,mode:t.rule.mode});const u=await r.request(s,{method:"PUT",body:l,operation:"setConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(u),t.rule)}})}async getConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}`;e.debug("Call getConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await r.request(s,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l))}})}async clearConversationRemindType(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=this.mapConversationTypeToPath(t.conversationType),s=`/${o}/${i}/users/${n.userId}/notification/${a}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(n.clientResource)}`;e.debug("Call clearConversationRemindType",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await r.request(s,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),{remindType:"DEFAULT"})}})}async getConversationSilentModes(t){return this.runOperation(async()=>{this.validateConversationList(t.conversationList,"conversationList");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=t.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),s=t.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),l=`/${o}/${i}/users/${n.userId}/notification?user=${a}&group=${s}`;e.debug("Call getConversationSilentModes",{count:t.conversationList.length});const u=await r.request(l,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(u,"user"),p=this.resolveConversationRuleMap(u,"group");return{conversations:t.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:p[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(t){await this.runOperation(async()=>{this.validateLanguage(t.language,"language");const n=this.getRestContextOrThrow(),r=this.getRestClient(n),{orgName:o,appName:i}=this.parseAppKey(n.appKey),a=`/${o}/${i}/users/${n.userId}/notification/language`;e.debug("Call setPushLanguage",{language:t.language}),await r.request(a,{method:"PUT",body:{translationLanguage:t.language},operation:"setPushLanguage"})})}async getPushLanguage(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),{orgName:r,appName:o}=this.parseAppKey(t.appKey),i=`/${r}/${o}/users/${t.userId}/notification/language`;e.debug("Call getPushLanguage");const a=await n.request(i,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(a,"")}})}getConversationListByRemindType(t){return this.runOperation(()=>{e.debug("Call getConversationListByRemindType",{pageSize:t.pageSize,hasCursor:Boolean(t.cursor)});const n=this.getClientOrThrow(),r=s({items:n.getCacheManager()?.loadSessionList()??[],pageSize:t.pageSize,cursor:t.cursor});return Promise.resolve(r)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof t?e:e instanceof Error?new t(`PushManager operation failed: ${e.message}`,n.UNKNOWN):new t("PushManager operation failed",n.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new r(e.restBaseUrl,{errorMap:l,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new t("PushManager is not bound to client",n.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!u.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,n)=>{this.validateConversationId(e.conversationId,`${t}[${n}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${n}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!c(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!p.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,n){const r=Object.keys(e).find(e=>!n.includes(e));if(r)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${r}`,message:`${r} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!c(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const n=this.parseRuleView(e);return n?t?{...this.toRuleViewFromFallback(t),...n}:n:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!c(e))return null;const t={},n=this.normalizeRemindType(e.type);null!==n&&(t.remindType=n);const r=e.ignoreDuration;"number"==typeof r&&Number.isInteger(r)&&r>0&&(t.expireTimestamp=r);const o=e.ignoreInterval;if("string"==typeof o){const e=this.parseInterval(o);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const n=Number(t[1]),r=Number(t[2]),o=Number(t[3]),i=Number(t[4]);return Number.isInteger(n)&&Number.isInteger(r)&&Number.isInteger(o)&&Number.isInteger(i)?n<0||n>23||o<0||o>23||r<0||r>59||i<0||i>59?null:{startTime:{hours:n,minutes:r},endTime:{hours:o,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(c(e.data)){const n=e.data[t];if(c(n))return n}const n=e[t];return c(n)?n:{}}resolveSilentModeRuleSource(e){if(!c(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return c(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":d.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(c(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const n=e.data.language;if("string"==typeof n&&n.length>0)return n}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(e,t){return new o(e,{code:n.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};h.key="pushManager";let g=h;export{g as PushManager};
1
+ import{V as e,E as t,S as i,aI as n,aJ as s,aK as r,aL as o,aM as a,aN as l,l as u,h as d,m as h,j as c}from"../../chunks/common-BvlDAw4a.js";import{b as g}from"../../chunks/event-system-B62vbKqG.js";import{q as m}from"../../chunks/session-list-query-Cvr6rlme.js";const p=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],v=(i,n,s="invalid_format")=>new e(n,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:i,message:n,rule:s}]}}),y=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw v(t,`${t} must be a non-empty string`);return e.trim()}},f=e=>8===e?"normal":p[e]??"normal",T=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class R{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=/* @__PURE__ */new Set}configure(i){const n=(e=>{if(!e||"object"!=typeof e)throw v("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw v("plugin","plugin is required","required");const i=t;if("function"!=typeof i.onRegister)throw v("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof i.unRegister)throw v("plugin.unRegister","plugin.unRegister must be a function");const n=e.certificates;if(!n||"object"!=typeof n)throw v("certificates","certificates is required","required");const s=n,r={apns:y(s.apns,"certificates.apns"),fcm:y(s.fcm,"certificates.fcm"),huawei:y(s.huawei,"certificates.huawei"),xiaomi:y(s.xiaomi,"certificates.xiaomi"),meizu:y(s.meizu,"certificates.meizu"),vivo:y(s.vivo,"certificates.vivo"),oppo:y(s.oppo,"certificates.oppo"),honor:y(s.honor,"certificates.honor")};if(!p.some(e=>void 0!==r[e]))throw v("certificates","at least one native push certificate is required");return{plugin:t,certificates:r,signature:p.map(e=>`${e}:${r[e]??""}`).join("|")}})(i),s=null!==this.config&&"disabled"!==this.state,r=this.config?.plugin===n.plugin&&this.config.signature===n.signature;if(s&&!r)throw new e("Native push is enabled; call removePushToken() before replacing its configuration",{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});s&&r&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=n,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const t of this.collectRemovalTargets(e.generation)){const i=await this.removeWithRetry(t,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!i){this.emitFailure(g.TOKEN_REMOVE_FAILED,"remove",t.channel,t.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new i("User is not logged in",t.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,t=this.session.generation,i=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(n=>{if(!this.isRegistrationActive(t,i))return;const s=((e,t)=>{if(!T(e)||200!==e.code||0===e.push_token.trim().length)return null;const i=f(e.push_type);if("normal"===i)return null;const n=t.certificates[i];return n?{token:e.push_token,channel:i,notifierName:n}:null})(n,e);if(!s){this.state="failed";const t=T(n)?f(n.push_type):void 0,i=T(n)&&200===n.code&&n.push_token.trim().length>0&&void 0!==t&&"normal"!==t&&void 0===e.certificates[t];return void this.emitFailure(g.TOKEN_BIND_FAILED,i?"bind":"register",t)}this.enqueueBinding(s)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(g.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const t=this.session.generation,i=this.createBindingKey(e);this.activeBindingKey=i,this.state="binding";const n=await this.bindWithRetry(e,t);if(this.activeBindingKey=null,!this.session||this.session.generation!==t||this.disabledByUser)return;n?(this.binding={...e,generation:t,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=i,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.dependencies.dispatch(g.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=i,this.state="failed",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.emitFailure(g.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(e,t){this.lastBindingError=null;for(let o=0;o<=n;o+=1)try{const i=this.session;return!(!i||i.generation!==t)&&(this.lastAttemptedBinding={...e,generation:t,userId:i.userId,deviceId:i.clientResource},await this.dependencies.requestToken({deviceId:i.clientResource,deviceToken:e.token,notifierName:e.notifierName,timeout:s}),!0)}catch(i){if(this.lastBindingError=this.toSdkError(i),!this.session||this.session.generation!==t)return!1;if(!this.isRetryable(i)||o===n)return!1;const e=r[o]??0;if(!(await this.wait(e)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new i("User is not logged in",t.AUTH_NOT_LOGIN);const e=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(e))throw this.manualRemovalInProgress=!1,new i("User is not logged in",t.AUTH_NOT_LOGIN);const n=this.collectRemovalTargets(e);if(0!==n.length)try{for(const t of n)if(await this.dependencies.requestToken({deviceId:t.deviceId,deviceToken:"",notifierName:t.notifierName}),!this.isSessionGenerationActive(e))return;this.disableByUser()}catch(s){const t=this.toSdkError(s),i=n[0];throw i&&this.isSessionGenerationActive(e)&&this.emitFailure(g.TOKEN_REMOVE_FAILED,"remove",i.channel,i.notifierName,t),this.manualRemovalInProgress=!1,this.resumePendingBinding(e),t}else this.disableByUser()}async removeWithRetry(e,t){this.lastRemovalError=null;for(let n=0;n<=o;n+=1)try{return await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName,timeout:a}),!0}catch(i){if(this.lastRemovalError=this.toSdkError(i),!this.isSessionGenerationActive(t))return!1;if(!this.isRetryable(i)||n===o)return!1;if(!(await this.wait(l)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,i)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===i)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{u.warn("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const i={timer:setTimeout(()=>{this.delays.delete(i),t(!0)},e),resolve:t};this.delays.add(i)})}isRetryable(e){return!(e instanceof i)||(!0===e.details?.retryable||[t.REST_NETWORK_ERROR,t.REST_TIMEOUT,t.REST_HTTP_ERROR,t.SERVER_BUSY].includes(e.code))}toSdkError(e){return e instanceof i?e:new i("Native push operation failed",t.UNKNOWN)}emitFailure(e,t,i,n,s){const r=!!s&&this.isRetryable(s);this.dependencies.dispatchFailure(e,{stage:t,...i?{channel:i}:{},...n?{notifierName:n}:{},...s?{code:s.code}:{},retryable:r}),u.warn("Native push operation failed",{stage:t,...i?{channel:i}:{},...n?{notifierName:n}:{},...s?{code:s.code}:{},retryable:r})}}const b=h(c,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),I=["singleChat","groupChat"],N=["ALL","AT","NONE","DEFAULT"],E=["ALL","AT","NONE"],C=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),w=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new R({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(e){const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey);u.debug("Call native push token operation",{deviceId:e.deviceId,notifierName:e.notifierName,removing:0===e.deviceToken.length}),await i.request(`/${n}/${s}/users/${t.userId}`,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken",...void 0!==e.timeout?{timeout:e.timeout}:{}})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);u.debug("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await i.request(r,{method:"PUT",body:o,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:i,appName:n}=this.parseAppKey(e.appKey),s=`/${i}/${n}/users/${e.userId}/notification/user/${e.userId}`;u.debug("Call getGlobalSilentMode");const r=await t.request(s,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(r))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);u.debug("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const l=await i.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}`;u.debug("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await i.request(o,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;u.debug("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await i.request(o,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),o=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${n}/${s}/users/${t.userId}/notification?user=${r}&group=${o}`;u.debug("Call getConversationSilentModes",{count:e.conversationList.length});const l=await i.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(l,"user"),h=this.resolveConversationRuleMap(l,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:h[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/language`;u.debug("Call setPushLanguage",{language:e.language}),await i.request(r,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:i,appName:n}=this.parseAppKey(e.appKey),s=`/${i}/${n}/users/${e.userId}/notification/language`;u.debug("Call getPushLanguage");const r=await t.request(s,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(r,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{u.debug("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),i=m({items:t.getCacheManager()?.loadSessionList()??[],pageSize:e.pageSize,cursor:e.cursor});return Promise.resolve(i)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof i?e:e instanceof Error?new i(`PushManager operation failed: ${e.message}`,t.UNKNOWN):new i("PushManager operation failed",t.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new d(e.restBaseUrl,{errorMap:b,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new i("PushManager is not bound to client",t.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!I.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,i)=>{this.validateConversationId(e.conversationId,`${t}[${i}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${i}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!C(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!E.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,i){const n=Object.keys(e).find(e=>!i.includes(e));if(n)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${n}`,message:`${n} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!C(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const i=this.parseRuleView(e);return i?t?{...this.toRuleViewFromFallback(t),...i}:i:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!C(e))return null;const t={},i=this.normalizeRemindType(e.type);null!==i&&(t.remindType=i);const n=e.ignoreDuration;"number"==typeof n&&Number.isInteger(n)&&n>0&&(t.expireTimestamp=n);const s=e.ignoreInterval;if("string"==typeof s){const e=this.parseInterval(s);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),r=Number(t[4]);return Number.isInteger(i)&&Number.isInteger(n)&&Number.isInteger(s)&&Number.isInteger(r)?i<0||i>23||s<0||s>23||n<0||n>59||r<0||r>59?null:{startTime:{hours:i,minutes:n},endTime:{hours:s,minutes:r}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(C(e.data)){const i=e.data[t];if(C(i))return i}const i=e[t];return C(i)?i:{}}resolveSilentModeRuleSource(e){if(!C(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return C(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":N.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(C(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const i=e.data.language;if("string"==typeof i&&i.length>0)return i}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(i,n){return new e(i,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:n}})}};w.key="pushManager";let S=w;export{S as PushManager};