easemob-websdk 5.0.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-manager.d.ts +3 -0
- package/cache/cache-store.d.ts +6 -4
- package/cache/cache-utils.d.ts +1 -1
- package/chat-client.d.ts +25 -12
- package/chunks/cache-utils-B99glc0H.js +1 -0
- package/chunks/cache-utils-gowrxNr8.cjs +1 -0
- package/chunks/chat-manager-DCqgMxLm.js +2 -0
- package/chunks/chat-manager-D_KF5qM1.cjs +1 -0
- package/chunks/common-BIpcR2uQ.cjs +1 -0
- package/chunks/common-D_DfwSd3.js +1 -0
- package/chunks/{group-user-info-resolver-C5pdiqox.cjs → group-user-info-resolver-Ds35Z1Uf.cjs} +1 -1
- package/chunks/{group-user-info-resolver-FNRqDg18.js → group-user-info-resolver-lEtRdWli.js} +1 -1
- package/chunks/index-BmwQgZ3E.js +1 -0
- package/chunks/index-BsIqq7LU.cjs +1 -0
- package/chunks/index-CFMcR5a_.js +1 -0
- package/chunks/index-Dvvh1nf6.cjs +1 -0
- package/chunks/light-Dg9A1Xmd.js +1 -0
- package/chunks/light-dJjIln5b.cjs +1 -0
- package/chunks/query-params-BHyPuD2k.cjs +1 -0
- package/chunks/query-params-Bu3Xq4b6.js +1 -0
- package/chunks/reflection-proto-codec-BerStgkC.cjs +1 -0
- package/chunks/reflection-proto-codec-CjRraw85.js +1 -0
- package/chunks/{session-list-query-B6dh-b4Y.cjs → session-list-query-C4OQMvPf.cjs} +1 -1
- package/chunks/{session-list-query-Dnp2HbpW.js → session-list-query-rynxSxtv.js} +1 -1
- package/chunks/{user-info-BfRwS4ZA.js → user-info-DfbCp80h.js} +1 -1
- package/chunks/{user-info-icpL0Eaw.cjs → user-info-DsDDTJrw.cjs} +1 -1
- package/index.cjs +1 -1
- package/index.js +2 -2
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-manager.d.ts +3 -2
- package/managers/chat-thread/index.cjs +1 -1
- package/managers/chat-thread/index.js +1 -1
- package/managers/chat-thread-manager.d.ts +3 -2
- package/managers/chatroom/index.cjs +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.cjs +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.cjs +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.cjs +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.js +1 -1
- package/managers/user-info/index.cjs +1 -1
- package/managers/user-info/index.js +1 -1
- package/package.json +1 -1
- package/platform/env.d.ts +1 -0
- package/rest/dns-config.d.ts +10 -2
- package/types/chat-client.d.ts +28 -3
- package/utils/query-params.d.ts +16 -0
- package/utils/runtime-global.d.ts +13 -0
- package/utils/storage-error.d.ts +8 -0
- package/validators/chat-client.d.ts +13 -5
- package/chunks/cache-utils-BwRPIZ7n.js +0 -1
- package/chunks/cache-utils-CKbcYPlM.cjs +0 -1
- package/chunks/chat-manager-ChdK26ck.cjs +0 -1
- package/chunks/chat-manager-DH8a6Qj9.js +0 -2
- package/chunks/common-CfAlncj9.cjs +0 -1
- package/chunks/common-DN_g4O3n.js +0 -1
- package/chunks/index-BKg4EGcI.cjs +0 -1
- package/chunks/index-CK3GHdGU.cjs +0 -1
- package/chunks/index-CjofwvEQ.js +0 -1
- package/chunks/index-uKWbjx-u.js +0 -1
- package/chunks/reflection-proto-codec-64ocOTHU.js +0 -1
- package/chunks/reflection-proto-codec-BnQFQdZC.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,h as i}from"../../chunks/common-DN_g4O3n.js";import{b as c}from"../../chunks/event-system-D6IJA0C4.js";import{i as u}from"../../chunks/cache-utils-BwRPIZ7n.js";import{b as m,a as h,n as d}from"../../chunks/user-info-BfRwS4ZA.js";class l{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 p=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],R=e=>{const t=[],r=/* @__PURE__ */new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},g=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),I=e=>({userId:e}),y=(e,t,r)=>{const o={userId:r};for(const a of p){const r=t?.[a]??e?.[a];void 0!==r&&(o[a]=r)}return o},f=async(e,t)=>{const r=R(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,g(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,I(n));return o},b=e=>u(e)?e:null,C=e=>"string"==typeof e?e:void 0,w=e=>{const t=C(e)?.trim();return t||void 0},_=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}},A=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},M=e=>{const t=b(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},U=e=>{const t=b(e);return t?b(t.data)?t.data:t:null},v=(e,t)=>{const r=b(e),o=r&&b(r.params),a=o?.[t];if(Array.isArray(a)&&0!==a.length)return _(a[0])},S=e=>w(e.chatRoomId)??w(e.chatroomid)??w(e.id)??"",E=e=>C(e.name)??C(e.title)??C(e.groupname)??"",O=e=>I(e),T=(e,t)=>{const r=b(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)})(w(r.owner)):w(r.owner);return{chatRoomId:o,name:E(r),owner:a?O(a):void 0,memberCount:_(r.memberCount)??_(r.affiliations_count),disabled:A(r.disabled)}},x=(e,t)=>{const r=(e=>{const t=b(e);return t?_(t.count):void 0})(e),o=M(e).map(e=>T(e,t)).filter(e=>null!==e),a=v(e,"pagenum"),s=v(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}},k=(e,t)=>{const r=M(e),o=b(r[0])??U(e)??{},a=T(o)??{chatRoomId:S(o),name:E(o)},s=((e,t)=>{if(!t)return;if(w(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const o of r){const e=b(o);if(e){if(w(e.owner)===t)return"owner";if(w(e.admin)===t)return"admin";if(w(e.member)===t)return"member"}}})(o,t),n=_(o.muteExpireAt)??_(o.mute_expire)??_(o.expire),i=A(o.inAllowlist)??A(o.white)??A(o.in_whitelist),c=A(o.muted);return{...a,description:C(o.description),maxMembers:_(o.maxMembers)??_(o.maxusers)??_(o.max_users),createdAt:_(o.createdAt)??_(o.created),ext:C(o.ext)??C(o.custom),announcement:C(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}},$=e=>M(e).map(e=>w(e)).filter(e=>Boolean(e)).map(e=>O(e)),L=(e,t)=>{const r=U(e)??{},o=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],a=b(r.errorKeys)??{},s={};for(const[n,i]of Object.entries(a))"string"==typeof i&&(s[n]={code:D(i),message:i});return{chatRoomId:t,appliedKeys:o,failedKeys:s}},N=e=>{const t=b(e),r=t?.data,o=Array.isArray(r)?r:void 0!==r?[r]:[],a=[],s=[];return o.forEach(e=>{const t=b(e),r=(e=>{const t=b(e);if(!t)return null;const r=w(t.user),o=w(t.chatRoomId)??w(t.chatroomid)??w(t.id),a=C(t.action),s=A(t.result);return r&&o&&void 0!==a&&void 0!==s?{chatRoomId:o,user:O(r),action:a,reason:C(t.reason),...s?{}:{reason:C(t.reason)??"failed"}}:null})(e);if(!r||!t)return;A(t.result)?a.push(r):s.push(r)}),{succeeded:a,failed:s}},D=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,F=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},B=t=>new r(`${t} is required`,{code:e.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),z=(t,o)=>new r(o,{code:e.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:o,rule:"invalid_format"}]}}),j=(e,t)=>`/${e.orgName}/${e.appName}${t}`,V=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw z(t,`${t} must be a string`);return e}},P=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw z(t,`${t} must be a number`);return e}},q=(e,t)=>{const r=new URLSearchParams;"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}`:""},W=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw B(t);return e.trim()},H=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw B(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,a)=>{if("string"!=typeof e)throw z(`${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 B(t);return r},K=(e,t)=>H(e,t),G=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s={},n=V(r.name,"params.name"),i=V(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 B("params");const u=j(o,`/chatrooms/${encodeURIComponent(a)}?resource=${o.encodedResource}`);return(e=>{const t=U(e)??{};return{nameUpdated:A(t.groupname),descriptionUpdated:A(t.description),maxMembersUpdated:A(t.maxusers)}})(await e.put(u,s,{operation:"updateChatRoomInfo"}))},Q=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(o,`/chatrooms/${encodeURIComponent(a)}/users${(e=>{const t=new URLSearchParams;"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 M(e)){const e=b(a);if(!e)continue;const r=w(e.owner),o=w(e.admin),s=w(e.member),n=r??o??s;n&&t.push({user:O(n),role:r?"owner":o?"admin":"member",joinedAt:_(e.joinedAt)??_(e.joined_time)})}const r=b(e),o=r?w(r.cursor):void 0;return{items:t,cursor:o,hasMore:"string"==typeof o&&o.length>0}})(await e.get(s,{operation:"getChatRoomMemberList"}))},J=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(o,`/chatrooms/${encodeURIComponent(a)}/admin`),n=await e.get(s,{operation:"getChatRoomAdminList"});return $(n)},X=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=new URLSearchParams;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=j(o,`/chatrooms/${encodeURIComponent(a)}/mute?${s.toString()}`);return(e=>{const t=M(e);if(t.every(e=>"string"==typeof e))return $(e).map(e=>({user:e}));const r=[];for(const o of t){const e=b(o);if(!e)continue;const t=w(e.user)??w(e.member)??w(e.owner)??w(e.admin);t&&r.push({user:O(t),muteExpire:_(e.muteExpire)??_(e.expire)??_(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(n,{operation:"getChatRoomMuteList"}))},Y=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(o,`/sdk/chatrooms/${encodeURIComponent(a)}/mute/${o.encodedUserId}?version=v3`);return(e=>{const t=U(e)??{};return{muted:A(t.muted)??A(t.value)??Boolean(t.data),muteExpireAt:_(t.muteExpireAt)??_(t.expire)??_(t.mute_expire)}})(await e.get(s,{operation:"isCurrentUserMutedInChatRoom"}))},Z=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=q(r),n=s?"&":"",i=j(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users?version=v3${n}${s.replace("?","")}`),c=await e.get(i,{operation:"getChatRoomBlocklist"});return $(c).map(e=>({user:e}))},ee=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(o,`/chatrooms/${encodeURIComponent(a)}/white/users`),n=await e.get(s,{operation:"getChatRoomAllowlist"});return $(n).map(e=>({user:e}))},te=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${o.encodedUserId}?version=v3`);return(e=>{const t=U(e)??{};return A(t.value)??A(t.white)??!1})(await e.get(s,{operation:"checkIfInChatRoomAllowList"}))},re=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(o,`/chatrooms/${encodeURIComponent(a)}/announcement`);return(e=>{const t=U(e)??{};return{announcement:C(t.announcement)??""}})(await e.get(s,{operation:"getChatRoomAnnouncement"}))},oe=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(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?K(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),a)},ae=async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw z(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw B(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw z(t,`${t} contains invalid key`);if("string"!=typeof r)throw z(`${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=j(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${c}`),m=await e.put(u,{metaData:s,autoDelete:n?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return L(m,a)},se={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},ne=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}}}}}),ie=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=se[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=se[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=F(t),a=j(o,`/chatrooms${q(r)}`),s=await e.get(a,{operation:"getChatRoomList"});return x(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 l(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(o,`/chatrooms/${encodeURIComponent(a)}?joined_time=true`),n=await e.get(s,{operation:"getChatRoomInfo"});return k(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 G(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=W(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=W(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 Q(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=H(r.userIds,"params.userIds"),n=j(o,`/chatrooms/${encodeURIComponent(a)}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeChatRoomMembers"});return N(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await J(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=W(r.userId,"params.userId"),n=j(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=W(r.userId,"params.userId"),n=j(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 X(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=H(r.userIds,"params.userIds"),n=P(r.duration,"params.duration"),i=j(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=H(r.userIds,"params.userIds"),n=j(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=j(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 Y(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await Z(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=H(r.userIds,"params.userIds"),n=1===s.length,i=j(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 N(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=H(r.userIds,"params.userIds"),n=j(o,`/chatrooms/${encodeURIComponent(a)}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"unblockChatRoomMembers"});return N(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await ee(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=H(r.userIds,"params.userIds"),n=j(o,`/chatrooms/${encodeURIComponent(a)}/white/users?resource=${o.encodedResource}`),i=await e.post(n,{usernames:s},{operation:"addUsersToChatRoomAllowlist"});return N(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=H(r.userIds,"params.userIds"),n=j(o,`/chatrooms/${encodeURIComponent(a)}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`),i=await e.delete(n,{operation:"removeUsersFromChatRoomAllowlist"});return N(i)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return te(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return re(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=V(r.announcement,"params.announcement");if(void 0===s)throw B("params.announcement");const n=j(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 oe(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await ae(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=F(t),a=W(r.chatRoomId,"params.chatRoomId"),s=K(r.keys,"params.keys"),{isForced:n=!1}=r,i=n?"/forced":"",c=j(o,`/metadata/chatroom/${encodeURIComponent(a)}/user/${o.encodedUserId}${i}`),u=await e.request(c,{method:"DELETE",body:{keys:s},operation:"removeChatRoomAttributes"});return L(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:ne,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 f(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=R(e),o=await f(r,t);return r.map(e=>y(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=m(e),o=await this.getRestClient(t).request(h(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return d(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 y(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>y(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:y(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:y(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:y(e.owner,t.get(e.owner.userId),e.owner.userId)}}};ie.key="chatRoomManager";let ce=ie;export{l as ChatRoom,ce as ChatRoomManager};
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-BsIqq7LU.cjs");exports.ContactManager=e.ContactManager;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as a}from"../../chunks/index-
|
|
1
|
+
import{C as a}from"../../chunks/index-BmwQgZ3E.js";export{a as ContactManager};
|
package/managers/group/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/index-
|
|
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;
|
package/managers/group/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{G as r,a}from"../../chunks/index-
|
|
1
|
+
import{G as r,a as o}from"../../chunks/index-CFMcR5a_.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-
|
|
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 +1 @@
|
|
|
1
|
-
import{l as e,S as t,E as r,V as s,f as a,m as i,
|
|
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};
|
package/managers/push/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/common-CfAlncj9.cjs"),t=require("../../chunks/session-list-query-B6dh-b4Y.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-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;
|
package/managers/push/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as e,S as t,E as n,f as r,V as o,m as i,h as a}from"../../chunks/common-DN_g4O3n.js";import{q as s}from"../../chunks/session-list-query-Dnp2HbpW.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{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 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/cache-utils-CKbcYPlM.cjs"),t=require("../../chunks/profile-version-njNs7R5-.cjs"),r=require("../../chunks/common-CfAlncj9.cjs"),s=require("../../chunks/user-info-icpL0Eaw.cjs"),n=require("../../chunks/event-system-COBJFEIq.cjs"),a=e=>{const{orgName:t,appName:s}=r.parseAppKey(e.appKey);return`/${t}/${s}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},o=(e,t="params.userIds")=>s.normalizeUserInfoTargetIds(e,t),i=e=>{const t=o(e);if(t.length>100)throw((e,t,s,n=r.ERROR_CODES.VALIDATION_INVALID_FORMAT)=>new r.ValidationError(e,{code:n,details:{fields:[{path:t,message:e,rule:s}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",r.ERROR_CODES.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},d=(e,t)=>{const r=(e=>o(e))(t);return`${a(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},u=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},l=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],c=r.mergeRuntimeErrorMaps(r.COMMON_ERROR_MAP,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),p=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],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.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,s=t?.getCacheManager();if(!t||!s||!t.getCurrentUserId())return;const a=e.payload,o=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=u(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(a);if(!o)return;const i=s.applyUserInfoNotifyPatch(o);if(!i.applied)return void r.logger.debug("User-info notify ignored",{userId:o.userId,notifyType:a.notifyType,reason:i.reason,lastModified:o.lastModified});if(s.updateUserInfoSummaryFromRuntime(o.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:o.userId,lastModified:o.lastModified}]),"subscription"===o.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===o.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const d=t.getContactSnapshot()?.items.find(e=>e.userId===o.userId);this.eventContext?.dispatch?.(n.ContactEventName.CONTACT_INFO_UPDATED,{userInfo:i.record.profile,contact:d})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildFetchUserInfoByUserIdRequest(s.normalizeUserInfoTargetIds(e.userIds,"params.userIds")),o=s.buildUserInfoFetchEndpoint(t);r.logger.debug("UserInfoManager getUserInfoByUserId",{userIds:a.targets});const i=await n.request(o,{method:"POST",body:a,operation:"getUserInfoByUserId"}),d=this.normalizeFetchEnvelope(i,a.targets);return this.writeCache(d),d.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildFetchUserInfoByAttributeRequest(s.normalizeUserInfoTargetIds(e.userIds,"params.userIds"),s.normalizeUserInfoAttributes(e.attributes,"params.attributes")),o=s.buildUserInfoFetchEndpoint(t);r.logger.debug("UserInfoManager getUserInfoByAttribute",{userIds:a.targets,attributes:a.properties});const i=await n.request(o,{method:"POST",body:a,operation:"getUserInfoByAttribute"}),d=this.normalizeFetchEnvelope(i,a.targets);return this.writeCache(d),d.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),s=this.getRestClient(t),n=(e=>a(e))(t),o=i(e.userIds);r.logger.debug("UserInfoManager subscribeUsersInfo",{userIds:o.usernames}),await s.request(n,{method:"POST",body:o,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=d(t,e.userIds);r.logger.debug("UserInfoManager unsubscribeUsersInfo",{userIds:s.normalizeUserInfoTargetIds(e.userIds,"params.userIds")}),await n.request(a,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),s=(e=>a(e))(e);r.logger.debug("UserInfoManager getSubscribedUsers",{userId:e.userId});const n=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(s,{method:"GET",operation:"getSubscribedUsers"}));return 0===n.length?[]:await this.getUserInfoByUserId({userIds:n})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildUpdateOwnInfoFormBody(e),o=s.buildUserInfoUpdateEndpoint(t);r.logger.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await n.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a,operation:"updateOwnInfo"}),d=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([d]),this.dispatchSelfUpdate(d.profile),d.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const n=this.getRestContextOrThrow(),a=this.getRestClient(n),o=s.buildUpdateOwnInfoByAttributeFormBody(e,t),i=s.buildUserInfoUpdateEndpoint(n);r.logger.debug("UserInfoManager updateOwnInfoByAttribute",{userId:n.userId,attribute:e});const d=await a.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o,operation:"updateOwnInfoByAttribute"}),u=this.normalizeUpdateEnvelope(d,n.userId,{userId:n.userId,[e]:t});return this.writeCache([u]),this.dispatchSelfUpdate(u.profile),u.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof r.SDKError?t:(r.logger.warn("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new r.SDKError(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new r.ValidationError("UserInfoManager is not bound to client",{code:r.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new r.RestClient(e.restBaseUrl,{errorMap:c,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return s.normalizeUserInfoFetchRecords(e,t)}normalizeUpdateEnvelope(t,r,s){const n=e.isRecord(t)?t:null,a=(n&&e.isRecord(n.data)?n.data:null)??(n&&this.looksLikeUserInfoAttributes(n)?n:null),o=n&&"number"==typeof n.lastModified?n.lastModified:void 0;return{profile:a?this.toUserInfo(r,a):{userId:r,...s??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(t){return!!e.isRecord(t)&&("nickname"in t||"avatarurl"in t||"avatarUrl"in t||"mail"in t||"phone"in t||"gender"in t||"sign"in t||"birth"in t||"ext"in t)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of l)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return l.filter(t=>t in e)}projectToSummary(e){const r=Date.now(),s=t.normalizeProfileVersionFromTimestamp(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:s,lastSyncAt:r,lastAccess:r,lastUpdate:e.lastModified??r}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};p.key="userInfoManager";let f=p;exports.UserInfoManager=f;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../chunks/cache-utils-gowrxNr8.cjs"),t=require("../../chunks/profile-version-njNs7R5-.cjs"),r=require("../../chunks/common-BIpcR2uQ.cjs"),s=require("../../chunks/user-info-DsDDTJrw.cjs"),n=require("../../chunks/event-system-COBJFEIq.cjs"),a=e=>{const{orgName:t,appName:s}=r.parseAppKey(e.appKey);return`/${t}/${s}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},o=(e,t="params.userIds")=>s.normalizeUserInfoTargetIds(e,t),i=e=>{const t=o(e);if(t.length>100)throw((e,t,s,n=r.ERROR_CODES.VALIDATION_INVALID_FORMAT)=>new r.ValidationError(e,{code:n,details:{fields:[{path:t,message:e,rule:s}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",r.ERROR_CODES.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},d=(e,t)=>{const r=(e=>o(e))(t);return`${a(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},u=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},l=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],c=r.mergeRuntimeErrorMaps(r.COMMON_ERROR_MAP,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),p=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],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.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,s=t?.getCacheManager();if(!t||!s||!t.getCurrentUserId())return;const a=e.payload,o=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=u(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(a);if(!o)return;const i=s.applyUserInfoNotifyPatch(o);if(!i.applied)return void r.logger.debug("User-info notify ignored",{userId:o.userId,notifyType:a.notifyType,reason:i.reason,lastModified:o.lastModified});if(s.updateUserInfoSummaryFromRuntime(o.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:o.userId,lastModified:o.lastModified}]),"subscription"===o.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===o.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const d=t.getContactSnapshot()?.items.find(e=>e.userId===o.userId);this.eventContext?.dispatch?.(n.ContactEventName.CONTACT_INFO_UPDATED,{userInfo:i.record.profile,contact:d})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildFetchUserInfoByUserIdRequest(s.normalizeUserInfoTargetIds(e.userIds,"params.userIds")),o=s.buildUserInfoFetchEndpoint(t);r.logger.debug("UserInfoManager getUserInfoByUserId",{userIds:a.targets});const i=await n.request(o,{method:"POST",body:a,operation:"getUserInfoByUserId"}),d=this.normalizeFetchEnvelope(i,a.targets);return this.writeCache(d),d.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildFetchUserInfoByAttributeRequest(s.normalizeUserInfoTargetIds(e.userIds,"params.userIds"),s.normalizeUserInfoAttributes(e.attributes,"params.attributes")),o=s.buildUserInfoFetchEndpoint(t);r.logger.debug("UserInfoManager getUserInfoByAttribute",{userIds:a.targets,attributes:a.properties});const i=await n.request(o,{method:"POST",body:a,operation:"getUserInfoByAttribute"}),d=this.normalizeFetchEnvelope(i,a.targets);return this.writeCache(d),d.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),s=this.getRestClient(t),n=(e=>a(e))(t),o=i(e.userIds);r.logger.debug("UserInfoManager subscribeUsersInfo",{userIds:o.usernames}),await s.request(n,{method:"POST",body:o,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=d(t,e.userIds);r.logger.debug("UserInfoManager unsubscribeUsersInfo",{userIds:s.normalizeUserInfoTargetIds(e.userIds,"params.userIds")}),await n.request(a,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),s=(e=>a(e))(e);r.logger.debug("UserInfoManager getSubscribedUsers",{userId:e.userId});const n=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(s,{method:"GET",operation:"getSubscribedUsers"}));return 0===n.length?[]:await this.getUserInfoByUserId({userIds:n})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),n=this.getRestClient(t),a=s.buildUpdateOwnInfoFormBody(e),o=s.buildUserInfoUpdateEndpoint(t);r.logger.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await n.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a,operation:"updateOwnInfo"}),d=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([d]),this.dispatchSelfUpdate(d.profile),d.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const n=this.getRestContextOrThrow(),a=this.getRestClient(n),o=s.buildUpdateOwnInfoByAttributeFormBody(e,t),i=s.buildUserInfoUpdateEndpoint(n);r.logger.debug("UserInfoManager updateOwnInfoByAttribute",{userId:n.userId,attribute:e});const d=await a.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o,operation:"updateOwnInfoByAttribute"}),u=this.normalizeUpdateEnvelope(d,n.userId,{userId:n.userId,[e]:t});return this.writeCache([u]),this.dispatchSelfUpdate(u.profile),u.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof r.SDKError?t:(r.logger.warn("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new r.SDKError(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new r.ValidationError("UserInfoManager is not bound to client",{code:r.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new r.RestClient(e.restBaseUrl,{errorMap:c,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return s.normalizeUserInfoFetchRecords(e,t)}normalizeUpdateEnvelope(t,r,s){const n=e.isRecord(t)?t:null,a=(n&&e.isRecord(n.data)?n.data:null)??(n&&this.looksLikeUserInfoAttributes(n)?n:null),o=n&&"number"==typeof n.lastModified?n.lastModified:void 0;return{profile:a?this.toUserInfo(r,a):{userId:r,...s??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(t){return!!e.isRecord(t)&&("nickname"in t||"avatarurl"in t||"avatarUrl"in t||"mail"in t||"phone"in t||"gender"in t||"sign"in t||"birth"in t||"ext"in t)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of l)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return l.filter(t=>t in e)}projectToSummary(e){const r=Date.now(),s=t.normalizeProfileVersionFromTimestamp(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:s,lastSyncAt:r,lastAccess:r,lastUpdate:e.lastModified??r}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};p.key="userInfoManager";let f=p;exports.UserInfoManager=f;
|