easemob-websdk 5.0.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/cache/cache-manager.d.ts +3 -0
  3. package/cache/cache-store.d.ts +6 -4
  4. package/cache/cache-utils.d.ts +1 -1
  5. package/chunks/cache-utils-B99glc0H.js +1 -0
  6. package/chunks/cache-utils-gowrxNr8.cjs +1 -0
  7. package/chunks/chat-manager-5wHx7UeW.cjs +1 -0
  8. package/chunks/chat-manager-DdAnJpcH.js +2 -0
  9. package/chunks/common-BIpcR2uQ.cjs +1 -0
  10. package/chunks/common-BW2KLpvb.js +1 -0
  11. package/chunks/{group-user-info-resolver-FNRqDg18.js → group-user-info-resolver-Diqjmjyj.js} +1 -1
  12. package/chunks/{group-user-info-resolver-C5pdiqox.cjs → group-user-info-resolver-Ds35Z1Uf.cjs} +1 -1
  13. package/chunks/index-BItCF8E7.cjs +1 -0
  14. package/chunks/{index-uKWbjx-u.js → index-DKksD5YM.js} +1 -1
  15. package/chunks/{index-BKg4EGcI.cjs → index-DKmdsV1-.cjs} +1 -1
  16. package/chunks/index-VEUtqiDw.js +1 -0
  17. package/chunks/query-params-BHyPuD2k.cjs +1 -0
  18. package/chunks/query-params-Bu3Xq4b6.js +1 -0
  19. package/chunks/{session-list-query-B6dh-b4Y.cjs → session-list-query-C4OQMvPf.cjs} +1 -1
  20. package/chunks/{session-list-query-Dnp2HbpW.js → session-list-query-DtoToipt.js} +1 -1
  21. package/chunks/{user-info-BfRwS4ZA.js → user-info-22jZtcSi.js} +1 -1
  22. package/chunks/{user-info-icpL0Eaw.cjs → user-info-DsDDTJrw.cjs} +1 -1
  23. package/index.cjs +1 -1
  24. package/index.js +2 -2
  25. package/managers/chat/index.cjs +1 -1
  26. package/managers/chat/index.js +1 -1
  27. package/managers/chat-thread/index.cjs +1 -1
  28. package/managers/chat-thread/index.js +1 -1
  29. package/managers/chatroom/index.cjs +1 -1
  30. package/managers/chatroom/index.js +1 -1
  31. package/managers/contact/index.cjs +1 -1
  32. package/managers/contact/index.js +1 -1
  33. package/managers/group/index.cjs +1 -1
  34. package/managers/group/index.js +1 -1
  35. package/managers/presence/index.cjs +1 -1
  36. package/managers/presence/index.js +1 -1
  37. package/managers/push/index.cjs +1 -1
  38. package/managers/push/index.js +1 -1
  39. package/managers/user-info/index.cjs +1 -1
  40. package/managers/user-info/index.js +1 -1
  41. package/package.json +1 -1
  42. package/platform/env.d.ts +1 -0
  43. package/utils/query-params.d.ts +16 -0
  44. package/utils/runtime-global.d.ts +13 -0
  45. package/utils/storage-error.d.ts +8 -0
  46. package/chunks/cache-utils-BwRPIZ7n.js +0 -1
  47. package/chunks/cache-utils-CKbcYPlM.cjs +0 -1
  48. package/chunks/chat-manager-ChdK26ck.cjs +0 -1
  49. package/chunks/chat-manager-DH8a6Qj9.js +0 -2
  50. package/chunks/common-CfAlncj9.cjs +0 -1
  51. package/chunks/common-DN_g4O3n.js +0 -1
  52. package/chunks/index-CK3GHdGU.cjs +0 -1
  53. package/chunks/index-CjofwvEQ.js +0 -1
@@ -1 +1 @@
1
- "use strict";const e=require("./common-CfAlncj9.cjs"),t=require("./cache-utils-CKbcYPlM.cjs"),s=require("./user-info-icpL0Eaw.cjs"),r=require("./reflection-proto-codec-BnQFQdZC.cjs"),a=e=>({userId:e}),n=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),o=e=>e,i=async(e,t)=>{const s=(e=>{const t=[],s=new Set;for(const r of e){const e=r.trim();e&&!s.has(e)&&(s.add(e),t.push(e))}return t})(e),r=new Map;if(0===s.length)return r;const i=t.cacheManager?.getUserInfoSummaries(s,!1)??[];for(const a of i)r.set(a.userId,n(a));const c=s.filter(e=>!r.has(e));if(c.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:c});for(const t of e)r.set(t.userId,o(t))}for(const n of s)r.has(n)||r.set(n,a(n));return r},c={UNSPECIFIED:0,PING:1,PONG:2,REQUEST:3,RESPONSE:4,ERROR:5},d=0,l=0,u=1,h=1001,p=1002,g=1003,m=1004,y=1005,R=1101,I=t=>{const{orgName:s,appName:r}=e.parseAppKey(t.appKey);return{orgName:s,appName:r,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},E=e=>t.isRecord(e)&&Array.isArray(e.data)?e.data.filter(e=>"string"==typeof e&&e.length>0):Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[],C=(s,r)=>{if(!Array.isArray(s.userIds)||0===s.userIds.length)throw new e.ValidationError(`${r} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});const a=s.userIds.map((t,s)=>{if("string"!=typeof t)throw new e.ValidationError(`${r}[${s}] must be a string`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${r}[${s}]`,message:"userId must be a string",rule:"invalid_format"}]}});return t.trim()}),n=(e=>{const t=[],s=new Set;for(const r of e)r&&!s.has(r)&&(s.add(r),t.push(r));return t})(a);if(0===n.length)throw new e.ValidationError(`${r} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});return n.length!==a.length&&t.isRecord(s),n},S=async(e,t)=>{const s=I(t),r=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/blocks/users`,a=await e.get(r,{operation:"getBlocklist"});return E(a).map(e=>({userId:e}))},f=async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`,n=await e.post(a,{usernames:s},{operation:"addUsersToBlocklist"});return{succeeded:E(n).map(e=>({userId:e})),failed:[]}},v={nested:{easemob:{nested:{imfusion:{nested:{gateway:{nested:{v1:{nested:{MessageType:{values:{MESSAGE_TYPE_UNSPECIFIED:0,MESSAGE_TYPE_PING:1,MESSAGE_TYPE_PONG:2,MESSAGE_TYPE_ROSTER_REQUEST:3,MESSAGE_TYPE_ROSTER_RESPONSE:4,MESSAGE_TYPE_ERROR:5}},ServerStatus:{values:{SERVER_STATUS_OK:0,SERVER_STATUS_BUSY:1}},RosterResponseType:{values:{ROSTER_RESPONSE_TYPE_UNSPECIFIED:0,ROSTER_RESPONSE_TYPE_INCREMENTAL:1,ROSTER_RESPONSE_TYPE_FULL:2}},BaseMessage:{fields:{type:{type:"MessageType",id:1}}},GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},requestId:{type:"string",id:3},protocolVersion:{type:"int32",id:4}}},PingRequest:{fields:{type:{type:"MessageType",id:1}}},PongResponse:{fields:{type:{type:"MessageType",id:1},status:{type:"ServerStatus",id:2}}},ErrorDetail:{fields:{type:{type:"MessageType",id:1},code:{type:"string",id:2},message:{type:"string",id:3},header:{type:"GatewayHeader",id:4}}},GetRosterRequest:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},version:{type:"string",id:6},cursor:{type:"uint64",id:7}}},RosterItem:{fields:{contact:{type:"string",id:1},remark:{type:"string",id:2},metadata:{type:"string",id:3},createdAt:{type:"int64",id:4},updatedAt:{type:"int64",id:5},metadataUpdatedAt:{type:"int64",id:6}}},GetRosterResponse:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},data:{rule:"repeated",type:"RosterItem",id:3},cursor:{type:"uint64",id:4},version:{type:"string",id:5},responseType:{type:"RosterResponseType",id:6}}}}}}}}}}}}};let _=!1,O=null;const T=()=>O||(_||(r.lightExports.util.Long=r.Long,r.lightExports.configure(),_=!0),r.installReflectionRuntime(),O=r.lightExports.Root.fromJSON(v),r.installReflectionCodecInNamespace(O),O),U=e=>"number"==typeof e?e:r.Long.isLong(e)?e.toNumber():0,w=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:U(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:U(t.protocolVersion)}};class b{encodeRequest(e){const t=T().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=d){const t=T().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:c.PONG,status:e})).finish()}decode(e){const t=T(),s=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(s.type){case c.PING:return{type:c.PING};case c.PONG:{const s=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:c.PONG,status:U(s.status)}}case c.RESPONSE:{const s=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:c.RESPONSE,header:w(s.header),data:Array.isArray(s.data)?s.data.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{contact:"string"==typeof t.contact?t.contact:"",remark:"string"==typeof t.remark?t.remark:"",metadata:"string"==typeof t.metadata?t.metadata:"",createdAt:U(t.createdAt),updatedAt:U(t.updatedAt),metadataUpdatedAt:U(t.metadataUpdatedAt)}})(e)):[],cursor:U(s.cursor),version:"string"==typeof s.version?s.version:"",responseType:U(s.responseType)||l}}case c.ERROR:{const s=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:c.ERROR,header:w(s.header),code:"string"==typeof s.code?s.code:"",message:"string"==typeof s.message?s.message:"Unknown roster error"}}default:return{type:"number"==typeof s.type?s.type:c.UNSPECIFIED}}}}class N{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(t){const s=t.header?.requestId;if(s&&s!==this.requestId)throw new e.SDKError("Roster response requestId mismatched",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:s}});if(this.completed)throw new e.SDKError("Roster response received after completion",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:t.cursor}});if(null!==this.responseType&&this.responseType!==t.responseType)throw new e.SDKError("Roster response type changed in same session",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:t.responseType}});if(this.pages.length>0&&0!==t.cursor&&t.cursor===this.pages[this.pages.length-1]?.cursor)throw new e.SDKError("Roster cursor duplicated",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:t.cursor}});return this.responseType=t.responseType,this.version=t.version||this.version,this.pages.push(t),this.nextCursor=t.cursor,this.pageCount+=1,this.completed=0===t.cursor,{done:this.completed,nextCursor:this.nextCursor,pageCount:this.pageCount}}getNextCursor(){return this.nextCursor}getPageCount(){return this.pageCount}hasPages(){return this.pages.length>0}isCompleted(){return this.completed}buildResult(){return{mode:this.responseType===u?"incremental":"full",version:this.version,pages:this.pages}}}const k=e=>e.type===c.RESPONSE,A=e=>"message"in e&&"code"in e;class D{constructor(e){this.codec=new b,this.sharedSession=e}async sync(e){const t=new N(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(t,s){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:t.header.requestId,encode:()=>{const e=this.buildAttemptRequest(t,s.getNextCursor());return this.codec.encodeRequest(e)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:k(t)||A(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(t,r)=>{try{if(t.type===c.PING)return void(await r.send(this.codec.encodePong()));if(k(t)){if(!s.push(t).done)return;return{done:!0,result:s.buildResult()}}if(A(t))throw(t=>{const s=t.header?.requestId,r=e=>({stage:"sync_page",serverCode:t.code,requestId:s,retryable:e});switch(Number.parseInt(t.code,10)){case p:return new e.AuthenticationError(t.message,{code:e.ERROR_CODES.AUTH_UNAUTHORIZED,details:r(!1)});case g:return new e.SDKError(t.message,e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case h:return new e.SDKError(t.message,e.ERROR_CODES.VALIDATION_REQUIRED,{details:r(!1)});case m:return new e.SDKError(t.message,e.ERROR_CODES.VALIDATION_INVALID_FORMAT,{details:r(!1)});case y:return new e.SDKError(t.message,e.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:r(!0)});case R:return new e.SDKError(t.message,e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new e.SDKError(t.message,e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(t);return}catch(a){throw a instanceof e.SDKError?a:new e.SDKError("Roster frame decode failed",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:a instanceof Error?a.message:String(a)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const M=e=>e.versionState.version?"incremental":"full",q=e=>{const{metadata:t,metadataFailed:s,state:r}=e,a=r.versionState.version;return s||!t?{decision:"complete"===r.cacheMeta.cacheIntegrity?M(r):"full",version:a}:t.requiresSync||"complete"!==r.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===r.cacheMeta.cacheIntegrity&&a?{decision:"incremental",version:t.version||a}:{decision:"full",version:t.version||a}:{decision:"skip",version:t.version||a}},P=e=>{if(!e)return{};try{const t=JSON.parse(e);return{nickname:"string"==typeof t.nickname?t.nickname:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:"string"==typeof t.avatarurl?t.avatarurl:void 0,sign:"string"==typeof t.sign?t.sign:void 0,ext:"string"==typeof t.ext?t.ext:void 0}}catch{return{}}},$=t=>{const s=(t=>{if(!(t instanceof e.SDKError&&t.details))return null;const s=t.details.httpStatus;return"number"==typeof s?s:null})(t);return 401===s||403===s||404===s},B=(e,t,s,r)=>({code:t,stage:e,message:`${e}: ${s}`,retryable:r}),F=t=>{e.logger.warn("Contact sync duration",t)};class x{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("contact-sync-cancelled")}async runSync(){const t=this.dependencies.getContextState(),s=Date.now();let r;this.dependencies.onStart();try{const e=await this.dependencies.queryMetadata(t.versionState.version);if(r=q({metadata:e,state:t}),"skip"===r.decision)return this.dependencies.onFinish(),void F({outcome:"skip",decision:r.decision,durationMs:Date.now()-s,version:r.version,hasUsableSnapshot:t.cachedSnapshot.complete})}catch(a){if($(a)){const r=q({metadataFailed:!0,state:t}),n=a instanceof e.SDKError?a:new e.SDKError("Contact metadata request failed",e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:B("metadata",n.code,n.message,!1)}),void F({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:t.versionState.version,stage:"metadata",hasUsableSnapshot:t.cachedSnapshot.complete,source:t.cachedSnapshot.complete?t.cachedSnapshot.source:void 0})}if(r=q({metadataFailed:!0,state:t}),t.cachedSnapshot.complete)return this.dependencies.onFinish({error:B("metadata",e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,a instanceof Error?a.message:String(a),!0)}),void F({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:t.cachedSnapshot.source})}try{const e=await this.dependencies.getSyncUrls(),a=this.dependencies.buildRosterRequest({decision:r.decision,version:t.versionState.version}),n=await new D(this.dependencies.getSharedSyncSession()).sync({urls:e,request:a}),o=(e=>{const t=[];for(const s of e)for(const e of s.data){const s=P(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:s.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:s.nickname,avatarUrl:s.avatarUrl,sign:s.sign,ext:s.ext}})}return t})(n.pages),i=this.dependencies.applySyncResult({mode:n.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:n.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),F({outcome:"finish",decision:r.decision,durationMs:Date.now()-s,version:n.version,source:"sync",changed:i.changed,hasUsableSnapshot:i.snapshot.complete})}catch(a){const n=a instanceof e.SDKError?a:new e.SDKError("Contact sync failed",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:a instanceof Error?a.message:String(a)}}),o=n.details??{},i="string"==typeof o.stage?o.stage:"sync_page";this.dependencies.onFinish({error:B(i,n.code,n.message,!0)}),F({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:i,hasUsableSnapshot:t.cachedSnapshot.complete,source:t.cachedSnapshot.complete?t.cachedSnapshot.source:void 0})}}}const L={items:[],loaded:!1,source:"server"},K=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,223",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:223,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}}),V=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=L,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=L,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(t){return this.runOperation("addContact",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.validateOptionalString(t.message,"params.message"),a=this.getRestContextOrThrow(),n=this.getRestClient(a);e.logger.debug("ContactManager addContact",{userId:s,hasMessage:"string"==typeof r&&r.length>0}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/apply?resource=${r.encodedResource}`;await e.post(a,{usernames:[s.userId],reason:s.message??""},{operation:"addContact"})})(n,a,{userId:s,message:r})})}async deleteContact(t){return this.runOperation("deleteContact",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager deleteContact",{userId:s}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.delete(a,{operation:"deleteContact"})})(a,r,{userId:s});const n=this.client?.getCacheManager()?.removeContact(s);e.logger.debug("ContactManager deleteContact patched cache",{userId:s,changed:n?.changed??!1})})}async acceptContactInvite(t){return this.runOperation("acceptContactInvite",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager acceptContactInvite",{userId:s}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/accept/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"acceptContactInvite"})})(a,r,{userId:s}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(t){return this.runOperation("declineContactInvite",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager declineContactInvite",{userId:s}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/decline/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"declineContactInvite"})})(a,r,{userId:s})})}async setContactRemark(t){return this.runOperation("setContactRemark",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.validateRemark(t.remark,"params.remark"),a=this.getRestContextOrThrow(),n=this.getRestClient(a);e.logger.debug("ContactManager setContactRemark",{userId:s,remarkLength:r.length}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.put(a,{remark:s.remark},{operation:"setContactRemark"})})(n,a,{userId:s,remark:r});const o=this.client?.getCacheManager()?.updateContactRemark(s,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:s}],"profile"),e.logger.debug("ContactManager setContactRemark patched cache",{userId:s,changed:o?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=this.getRestClient(t);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const r=await this.enrichBlocklistUsers(await S(s,t));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},e.logger.debug("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(t){return this.runOperation("addUsersToBlocklist",async()=>{const s=this.getRestContextOrThrow();this.ensureBlocklistSession(s);const r=C(t,"params.userIds"),a=this.getRestClient(s);e.logger.debug("ContactManager addUsersToBlocklist",{userIds:r,inputCount:t.userIds.length,normalizedCount:r.length});const n=await f(a,s,r),o=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(o),{succeeded:o,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(t){return this.runOperation("removeUserFromBlocklist",async()=>{const s=this.getRestContextOrThrow();this.ensureBlocklistSession(s);const r=C(t,"params.userIds"),a=this.getRestClient(s);e.logger.debug("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:t.userIds.length,normalizedCount:r.length}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`;await e.request(a,{method:"DELETE",body:{usernames:s},operation:"removeUserFromBlocklist"})})(a,s,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(t,s){try{return await s()}catch(r){const s=this.normalizeSdkError(t,r);throw e.logger.warn(`ContactManager ${t} failed`,{code:s.code,message:s.message,details:s.details}),s}}normalizeSdkError(t,s){return s instanceof e.SDKError?s:s instanceof Error?new e.SDKError(`ContactManager ${t} failed: ${s.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`ContactManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}requireClient(){if(!this.client)throw this.buildValidationError("ContactManager is not bound to client",[{path:"contactManager.client",message:"ContactManager is not bound to client",rule:"required"}]);return this.client}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:K,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}ensureBlocklistSession(e){const t=`${e.restBaseUrl}:${e.userId}:${e.token}`;this.blocklistSessionKey!==t&&(this.blocklistSessionKey=t,this.blocklistSnapshot=L)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.set(s.userId,s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}patchBlocklistSnapshotWithRemovals(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.delete(s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}validateUserId(e,t){if("string"!=typeof e)throw this.buildValidationError("userId must be a string",[{path:t,message:"userId must be a string",rule:"invalid_format"}]);const s=e.trim();if(!s)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return s}validateOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw this.buildValidationError(`${t} must be a string`,[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]);return e}}validateRemark(e,t){if("string"!=typeof e)throw this.buildValidationError("remark must be a string",[{path:t,message:"remark must be a string",rule:"invalid_format"}]);return e}buildValidationError(t,s){const r=s.some(e=>"invalid_format"===e.rule)?e.ERROR_CODES.VALIDATION_INVALID_FORMAT:e.ERROR_CODES.VALIDATION_REQUIRED;return new e.ValidationError(t,{code:r,details:{fields:s}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await i(e.map(e=>e.userId),{cacheManager:this.requireClient().getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchUserInfos(e)});return e.map(e=>t.get(e.userId)??e)}async fetchUserInfos(t){if(0===t.length)return[];try{const e=this.getUserInfoManager();return e?await e.getUserInfoByUserId({userIds:t}):await this.fetchUserInfosFromRest(t)}catch(s){return e.logger.warn("ContactManager user info fetch failed",{userIds:t,error:s}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=s.buildFetchUserInfoByUserIdRequest(e),a=await this.getRestClient(t).request(s.buildUserInfoFetchEndpoint(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return s.normalizeFetchedUserInfos(a,r.targets)}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}createSyncController(e){return new x(e)}};V.key="contactManager";let G=V;exports.ContactManager=G,exports.RosterMessageType=c,exports.resolveSingleContactUserInfo=async(e,t)=>((e,t,s)=>({userId:s,nickname:t?.nickname??e?.nickname,avatarUrl:t?.avatarUrl??e?.avatarUrl,mail:t?.mail??e?.mail,phone:t?.phone??e?.phone,gender:t?.gender??e?.gender,sign:t?.sign??e?.sign,birth:t?.birth??e?.birth,ext:t?.ext??e?.ext}))(void 0,(await i([e],t)).get(e),e);
1
+ "use strict";const e=require("./common-BIpcR2uQ.cjs"),t=require("./cache-utils-gowrxNr8.cjs"),s=require("./user-info-DsDDTJrw.cjs"),r=require("./reflection-proto-codec-BnQFQdZC.cjs"),a=e=>({userId:e}),n=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),o=e=>e,i=async(e,t)=>{const s=(e=>{const t=[],s=new Set;for(const r of e){const e=r.trim();e&&!s.has(e)&&(s.add(e),t.push(e))}return t})(e),r=new Map;if(0===s.length)return r;const i=t.cacheManager?.getUserInfoSummaries(s,!1)??[];for(const a of i)r.set(a.userId,n(a));const c=s.filter(e=>!r.has(e));if(c.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:c});for(const t of e)r.set(t.userId,o(t))}for(const n of s)r.has(n)||r.set(n,a(n));return r},c={UNSPECIFIED:0,PING:1,PONG:2,REQUEST:3,RESPONSE:4,ERROR:5},d=0,l=0,u=1,h=1001,p=1002,g=1003,m=1004,y=1005,R=1101,I=t=>{const{orgName:s,appName:r}=e.parseAppKey(t.appKey);return{orgName:s,appName:r,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},E=e=>t.isRecord(e)&&Array.isArray(e.data)?e.data.filter(e=>"string"==typeof e&&e.length>0):Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[],C=(s,r)=>{if(!Array.isArray(s.userIds)||0===s.userIds.length)throw new e.ValidationError(`${r} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});const a=s.userIds.map((t,s)=>{if("string"!=typeof t)throw new e.ValidationError(`${r}[${s}] must be a string`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${r}[${s}]`,message:"userId must be a string",rule:"invalid_format"}]}});return t.trim()}),n=(e=>{const t=[],s=new Set;for(const r of e)r&&!s.has(r)&&(s.add(r),t.push(r));return t})(a);if(0===n.length)throw new e.ValidationError(`${r} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});return n.length!==a.length&&t.isRecord(s),n},S=async(e,t)=>{const s=I(t),r=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/blocks/users`,a=await e.get(r,{operation:"getBlocklist"});return E(a).map(e=>({userId:e}))},f=async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`,n=await e.post(a,{usernames:s},{operation:"addUsersToBlocklist"});return{succeeded:E(n).map(e=>({userId:e})),failed:[]}},v={nested:{easemob:{nested:{imfusion:{nested:{gateway:{nested:{v1:{nested:{MessageType:{values:{MESSAGE_TYPE_UNSPECIFIED:0,MESSAGE_TYPE_PING:1,MESSAGE_TYPE_PONG:2,MESSAGE_TYPE_ROSTER_REQUEST:3,MESSAGE_TYPE_ROSTER_RESPONSE:4,MESSAGE_TYPE_ERROR:5}},ServerStatus:{values:{SERVER_STATUS_OK:0,SERVER_STATUS_BUSY:1}},RosterResponseType:{values:{ROSTER_RESPONSE_TYPE_UNSPECIFIED:0,ROSTER_RESPONSE_TYPE_INCREMENTAL:1,ROSTER_RESPONSE_TYPE_FULL:2}},BaseMessage:{fields:{type:{type:"MessageType",id:1}}},GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},requestId:{type:"string",id:3},protocolVersion:{type:"int32",id:4}}},PingRequest:{fields:{type:{type:"MessageType",id:1}}},PongResponse:{fields:{type:{type:"MessageType",id:1},status:{type:"ServerStatus",id:2}}},ErrorDetail:{fields:{type:{type:"MessageType",id:1},code:{type:"string",id:2},message:{type:"string",id:3},header:{type:"GatewayHeader",id:4}}},GetRosterRequest:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},version:{type:"string",id:6},cursor:{type:"uint64",id:7}}},RosterItem:{fields:{contact:{type:"string",id:1},remark:{type:"string",id:2},metadata:{type:"string",id:3},createdAt:{type:"int64",id:4},updatedAt:{type:"int64",id:5},metadataUpdatedAt:{type:"int64",id:6}}},GetRosterResponse:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},data:{rule:"repeated",type:"RosterItem",id:3},cursor:{type:"uint64",id:4},version:{type:"string",id:5},responseType:{type:"RosterResponseType",id:6}}}}}}}}}}}}};let _=!1,O=null;const T=()=>O||(_||(r.lightExports.util.Long=r.Long,r.lightExports.configure(),_=!0),r.installReflectionRuntime(),O=r.lightExports.Root.fromJSON(v),r.installReflectionCodecInNamespace(O),O),U=e=>"number"==typeof e?e:r.Long.isLong(e)?e.toNumber():0,w=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:U(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:U(t.protocolVersion)}};class b{encodeRequest(e){const t=T().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=d){const t=T().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:c.PONG,status:e})).finish()}decode(e){const t=T(),s=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(s.type){case c.PING:return{type:c.PING};case c.PONG:{const s=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:c.PONG,status:U(s.status)}}case c.RESPONSE:{const s=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:c.RESPONSE,header:w(s.header),data:Array.isArray(s.data)?s.data.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{contact:"string"==typeof t.contact?t.contact:"",remark:"string"==typeof t.remark?t.remark:"",metadata:"string"==typeof t.metadata?t.metadata:"",createdAt:U(t.createdAt),updatedAt:U(t.updatedAt),metadataUpdatedAt:U(t.metadataUpdatedAt)}})(e)):[],cursor:U(s.cursor),version:"string"==typeof s.version?s.version:"",responseType:U(s.responseType)||l}}case c.ERROR:{const s=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:c.ERROR,header:w(s.header),code:"string"==typeof s.code?s.code:"",message:"string"==typeof s.message?s.message:"Unknown roster error"}}default:return{type:"number"==typeof s.type?s.type:c.UNSPECIFIED}}}}class N{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(t){const s=t.header?.requestId;if(s&&s!==this.requestId)throw new e.SDKError("Roster response requestId mismatched",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:s}});if(this.completed)throw new e.SDKError("Roster response received after completion",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:t.cursor}});if(null!==this.responseType&&this.responseType!==t.responseType)throw new e.SDKError("Roster response type changed in same session",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:t.responseType}});if(this.pages.length>0&&0!==t.cursor&&t.cursor===this.pages[this.pages.length-1]?.cursor)throw new e.SDKError("Roster cursor duplicated",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:t.cursor}});return this.responseType=t.responseType,this.version=t.version||this.version,this.pages.push(t),this.nextCursor=t.cursor,this.pageCount+=1,this.completed=0===t.cursor,{done:this.completed,nextCursor:this.nextCursor,pageCount:this.pageCount}}getNextCursor(){return this.nextCursor}getPageCount(){return this.pageCount}hasPages(){return this.pages.length>0}isCompleted(){return this.completed}buildResult(){return{mode:this.responseType===u?"incremental":"full",version:this.version,pages:this.pages}}}const k=e=>e.type===c.RESPONSE,A=e=>"message"in e&&"code"in e;class D{constructor(e){this.codec=new b,this.sharedSession=e}async sync(e){const t=new N(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(t,s){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:t.header.requestId,encode:()=>{const e=this.buildAttemptRequest(t,s.getNextCursor());return this.codec.encodeRequest(e)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:k(t)||A(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(t,r)=>{try{if(t.type===c.PING)return void(await r.send(this.codec.encodePong()));if(k(t)){if(!s.push(t).done)return;return{done:!0,result:s.buildResult()}}if(A(t))throw(t=>{const s=t.header?.requestId,r=e=>({stage:"sync_page",serverCode:t.code,requestId:s,retryable:e});switch(Number.parseInt(t.code,10)){case p:return new e.AuthenticationError(t.message,{code:e.ERROR_CODES.AUTH_UNAUTHORIZED,details:r(!1)});case g:return new e.SDKError(t.message,e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case h:return new e.SDKError(t.message,e.ERROR_CODES.VALIDATION_REQUIRED,{details:r(!1)});case m:return new e.SDKError(t.message,e.ERROR_CODES.VALIDATION_INVALID_FORMAT,{details:r(!1)});case y:return new e.SDKError(t.message,e.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:r(!0)});case R:return new e.SDKError(t.message,e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new e.SDKError(t.message,e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(t);return}catch(a){throw a instanceof e.SDKError?a:new e.SDKError("Roster frame decode failed",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:a instanceof Error?a.message:String(a)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const M=e=>e.versionState.version?"incremental":"full",q=e=>{const{metadata:t,metadataFailed:s,state:r}=e,a=r.versionState.version;return s||!t?{decision:"complete"===r.cacheMeta.cacheIntegrity?M(r):"full",version:a}:t.requiresSync||"complete"!==r.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===r.cacheMeta.cacheIntegrity&&a?{decision:"incremental",version:t.version||a}:{decision:"full",version:t.version||a}:{decision:"skip",version:t.version||a}},P=e=>{if(!e)return{};try{const t=JSON.parse(e);return{nickname:"string"==typeof t.nickname?t.nickname:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:"string"==typeof t.avatarurl?t.avatarurl:void 0,sign:"string"==typeof t.sign?t.sign:void 0,ext:"string"==typeof t.ext?t.ext:void 0}}catch{return{}}},$=t=>{const s=(t=>{if(!(t instanceof e.SDKError&&t.details))return null;const s=t.details.httpStatus;return"number"==typeof s?s:null})(t);return 401===s||403===s||404===s},B=(e,t,s,r)=>({code:t,stage:e,message:`${e}: ${s}`,retryable:r}),F=t=>{e.logger.warn("Contact sync duration",t)};class x{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("contact-sync-cancelled")}async runSync(){const t=this.dependencies.getContextState(),s=Date.now();let r;this.dependencies.onStart();try{const e=await this.dependencies.queryMetadata(t.versionState.version);if(r=q({metadata:e,state:t}),"skip"===r.decision)return this.dependencies.onFinish(),void F({outcome:"skip",decision:r.decision,durationMs:Date.now()-s,version:r.version,hasUsableSnapshot:t.cachedSnapshot.complete})}catch(a){if($(a)){const r=q({metadataFailed:!0,state:t}),n=a instanceof e.SDKError?a:new e.SDKError("Contact metadata request failed",e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:B("metadata",n.code,n.message,!1)}),void F({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:t.versionState.version,stage:"metadata",hasUsableSnapshot:t.cachedSnapshot.complete,source:t.cachedSnapshot.complete?t.cachedSnapshot.source:void 0})}if(r=q({metadataFailed:!0,state:t}),t.cachedSnapshot.complete)return this.dependencies.onFinish({error:B("metadata",e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,a instanceof Error?a.message:String(a),!0)}),void F({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:t.cachedSnapshot.source})}try{const e=await this.dependencies.getSyncUrls(),a=this.dependencies.buildRosterRequest({decision:r.decision,version:t.versionState.version}),n=await new D(this.dependencies.getSharedSyncSession()).sync({urls:e,request:a}),o=(e=>{const t=[];for(const s of e)for(const e of s.data){const s=P(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:s.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:s.nickname,avatarUrl:s.avatarUrl,sign:s.sign,ext:s.ext}})}return t})(n.pages),i=this.dependencies.applySyncResult({mode:n.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:n.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),F({outcome:"finish",decision:r.decision,durationMs:Date.now()-s,version:n.version,source:"sync",changed:i.changed,hasUsableSnapshot:i.snapshot.complete})}catch(a){const n=a instanceof e.SDKError?a:new e.SDKError("Contact sync failed",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:a instanceof Error?a.message:String(a)}}),o=n.details??{},i="string"==typeof o.stage?o.stage:"sync_page";this.dependencies.onFinish({error:B(i,n.code,n.message,!0)}),F({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:i,hasUsableSnapshot:t.cachedSnapshot.complete,source:t.cachedSnapshot.complete?t.cachedSnapshot.source:void 0})}}}const L={items:[],loaded:!1,source:"server"},K=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,223",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:223,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}}),V=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=L,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=L,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(t){return this.runOperation("addContact",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.validateOptionalString(t.message,"params.message"),a=this.getRestContextOrThrow(),n=this.getRestClient(a);e.logger.debug("ContactManager addContact",{userId:s,hasMessage:"string"==typeof r&&r.length>0}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/apply?resource=${r.encodedResource}`;await e.post(a,{usernames:[s.userId],reason:s.message??""},{operation:"addContact"})})(n,a,{userId:s,message:r})})}async deleteContact(t){return this.runOperation("deleteContact",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager deleteContact",{userId:s}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.delete(a,{operation:"deleteContact"})})(a,r,{userId:s});const n=this.client?.getCacheManager()?.removeContact(s);e.logger.debug("ContactManager deleteContact patched cache",{userId:s,changed:n?.changed??!1})})}async acceptContactInvite(t){return this.runOperation("acceptContactInvite",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager acceptContactInvite",{userId:s}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/accept/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"acceptContactInvite"})})(a,r,{userId:s}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(t){return this.runOperation("declineContactInvite",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager declineContactInvite",{userId:s}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/decline/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"declineContactInvite"})})(a,r,{userId:s})})}async setContactRemark(t){return this.runOperation("setContactRemark",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.validateRemark(t.remark,"params.remark"),a=this.getRestContextOrThrow(),n=this.getRestClient(a);e.logger.debug("ContactManager setContactRemark",{userId:s,remarkLength:r.length}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.put(a,{remark:s.remark},{operation:"setContactRemark"})})(n,a,{userId:s,remark:r});const o=this.client?.getCacheManager()?.updateContactRemark(s,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:s}],"profile"),e.logger.debug("ContactManager setContactRemark patched cache",{userId:s,changed:o?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=this.getRestClient(t);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const r=await this.enrichBlocklistUsers(await S(s,t));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},e.logger.debug("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(t){return this.runOperation("addUsersToBlocklist",async()=>{const s=this.getRestContextOrThrow();this.ensureBlocklistSession(s);const r=C(t,"params.userIds"),a=this.getRestClient(s);e.logger.debug("ContactManager addUsersToBlocklist",{userIds:r,inputCount:t.userIds.length,normalizedCount:r.length});const n=await f(a,s,r),o=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(o),{succeeded:o,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(t){return this.runOperation("removeUserFromBlocklist",async()=>{const s=this.getRestContextOrThrow();this.ensureBlocklistSession(s);const r=C(t,"params.userIds"),a=this.getRestClient(s);e.logger.debug("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:t.userIds.length,normalizedCount:r.length}),await(async(e,t,s)=>{const r=I(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`;await e.request(a,{method:"DELETE",body:{usernames:s},operation:"removeUserFromBlocklist"})})(a,s,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(t,s){try{return await s()}catch(r){const s=this.normalizeSdkError(t,r);throw e.logger.warn(`ContactManager ${t} failed`,{code:s.code,message:s.message,details:s.details}),s}}normalizeSdkError(t,s){return s instanceof e.SDKError?s:s instanceof Error?new e.SDKError(`ContactManager ${t} failed: ${s.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`ContactManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}requireClient(){if(!this.client)throw this.buildValidationError("ContactManager is not bound to client",[{path:"contactManager.client",message:"ContactManager is not bound to client",rule:"required"}]);return this.client}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:K,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}ensureBlocklistSession(e){const t=`${e.restBaseUrl}:${e.userId}:${e.token}`;this.blocklistSessionKey!==t&&(this.blocklistSessionKey=t,this.blocklistSnapshot=L)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.set(s.userId,s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}patchBlocklistSnapshotWithRemovals(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.delete(s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}validateUserId(e,t){if("string"!=typeof e)throw this.buildValidationError("userId must be a string",[{path:t,message:"userId must be a string",rule:"invalid_format"}]);const s=e.trim();if(!s)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return s}validateOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw this.buildValidationError(`${t} must be a string`,[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]);return e}}validateRemark(e,t){if("string"!=typeof e)throw this.buildValidationError("remark must be a string",[{path:t,message:"remark must be a string",rule:"invalid_format"}]);return e}buildValidationError(t,s){const r=s.some(e=>"invalid_format"===e.rule)?e.ERROR_CODES.VALIDATION_INVALID_FORMAT:e.ERROR_CODES.VALIDATION_REQUIRED;return new e.ValidationError(t,{code:r,details:{fields:s}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await i(e.map(e=>e.userId),{cacheManager:this.requireClient().getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchUserInfos(e)});return e.map(e=>t.get(e.userId)??e)}async fetchUserInfos(t){if(0===t.length)return[];try{const e=this.getUserInfoManager();return e?await e.getUserInfoByUserId({userIds:t}):await this.fetchUserInfosFromRest(t)}catch(s){return e.logger.warn("ContactManager user info fetch failed",{userIds:t,error:s}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=s.buildFetchUserInfoByUserIdRequest(e),a=await this.getRestClient(t).request(s.buildUserInfoFetchEndpoint(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return s.normalizeFetchedUserInfos(a,r.targets)}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}createSyncController(e){return new x(e)}};V.key="contactManager";let G=V;exports.ContactManager=G,exports.RosterMessageType=c,exports.resolveSingleContactUserInfo=async(e,t)=>((e,t,s)=>({userId:s,nickname:t?.nickname??e?.nickname,avatarUrl:t?.avatarUrl??e?.avatarUrl,mail:t?.mail??e?.mail,phone:t?.phone??e?.phone,gender:t?.gender??e?.gender,sign:t?.sign??e?.sign,birth:t?.birth??e?.birth,ext:t?.ext??e?.ext}))(void 0,(await i([e],t)).get(e),e);
@@ -0,0 +1 @@
1
+ import{i as e}from"./cache-utils-B99glc0H.js";import{p as t,V as r,E as o,S as s,A as n,_ as a,l as i,n as u,v as p,ar as d,b as c,e as m,as as l,f as h,m as g,i as I}from"./common-BW2KLpvb.js";import{a as y}from"./profile-version-DLMz8lqW.js";import{m as f,g as _,r as w,b as G}from"./group-user-info-resolver-Diqjmjyj.js";import{G as b}from"./event-system-D6IJA0C4.js";import{c as v}from"./query-params-Bu3Xq4b6.js";import{b as R,a as S,n as A}from"./user-info-22jZtcSi.js";import{L as U,a as E,l as C,b as O}from"./reflection-proto-codec-64ocOTHU.js";const T=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],M=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),D=e=>({userId:e}),N=(e,t,r)=>{const o={userId:r};for(const s of T){const r=t?.[s]??e?.[s];void 0!==r&&(o[s]=r)}return o},L=async(e,t)=>{const r=(e=>{const t=[],r=/* @__PURE__ */new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),o=/* @__PURE__ */new Map;if(0===r.length)return o;const s=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const a of s)o.set(a.userId,M(a));const n=r.filter(e=>!o.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)o.set(t.userId,t)}for(const a of r)o.has(a)||o.set(a,D(a));return o},F=t=>e(t)?t:null,P=e=>{if("string"==typeof e)return e},$=e=>{const t=P(e)?.trim();return t||void 0},x=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}},j=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},k=e=>{const t=F(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},J=e=>{const t=F(e);return t?F(t.data)?t.data:t:null},q=(e,t)=>{const r=F(e),o=r&&F(r.params),s=o?.[t];if(Array.isArray(s)&&0!==s.length)return x(s[0])},B=(e,t)=>{const r=(e=>{const t=F(e);return t?x(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},H=e=>$(e.groupId)??$(e.groupid)??$(e.id)??"",V=e=>P(e.name)??P(e.groupname)??P(e.groupName)??"",K=e=>{const t=k(e),r=F(t[0])??J(e)??{},o=(e=>{const t=F(e);if(!t)return null;const r=H(t);return r?{groupId:r,name:V(t),description:P(t.description),memberCount:x(t.memberCount)??x(t.affiliations_count),public:j(t.public),joinApprovalRequired:j(t.joinApprovalRequired)??j(t.approval)??j(t.membersonly)??j(t.members_only),allowInvites:j(t.allowInvites)??j(t.allowinvites)??j(t.allow_user_invites),maxMembers:x(t.maxMembers)??x(t.maxusers),role:$(t.role)??$(t.permission),disabled:j(t.disabled)}:null})(r)??{groupId:H(r),name:V(r)},s=$(r.owner)??$(r.admin)??$(r.member),n=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>F(e)).filter(e=>null!==e).map(e=>x(e.joined_time)).find(e=>void 0!==e);return{...o,owner:s?D(s):void 0,inviteNeedConfirm:j(r.inviteNeedConfirm)??j(r.invite_need_confirm),muteAllMembers:j(r.mute),ext:P(r.ext)??P(r.custom),createdAt:x(r.createdAt)??x(r.created),joinedAt:n,avatarUrl:P(r.avatar),messageBlocked:j(r.messageBlocked)??j(r.isMessageBlocked)??j(r.shieldgroup)}},z=e=>D(e),W=e=>k(e).map(e=>$(e)).filter(e=>Boolean(e)).map(e=>z(e)),Q=e=>{const t=F(e);if(!t)return null;const r=$(t.fileId)??$(t.file_id);if(!r)return null;const o=P(t.fileName)??P(t.file_name)??r,s=$(t.fileOwner)??$(t.file_owner);return{fileId:r,fileName:o,fileOwner:s?z(s):void 0,fileSize:x(t.fileSize)??x(t.file_size),createdAt:x(t.createdAt)??x(t.created)}},Y=100,X=3e3,Z=e=>({...e}),ee=e=>"object"==typeof e&&null!==e,te=e=>"DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e?e:"mentionOnly"===e?"AT":"mute"===e?"NONE":"default"===e?"DEFAULT":2===e?"AT":3===e?"NONE":0===e?"DEFAULT":1===e?"ALL":void 0;class re{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:Y,serverLimit:X,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:Y,serverLimit:X,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return ee(t=e)&&"string"==typeof t.groupId&&0!==t.groupId.length?{groupId:t.groupId,name:"string"==typeof t.name?t.name:"",description:"string"==typeof t.description?t.description:void 0,memberCount:"number"==typeof t.memberCount?t.memberCount:void 0,role:"owner"===t.role||"admin"===t.role||"member"===t.role?t.role:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,ownerId:"string"==typeof t.ownerId?t.ownerId:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:void 0,muteAllMembers:"boolean"==typeof t.muteAllMembers?t.muteAllMembers:void 0,muteExpiration:"number"==typeof t.muteExpiration?t.muteExpiration:void 0,remindType:te(t.remindType),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,updatedAt:"number"==typeof t.updatedAt?t.updatedAt:void 0,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null;var t}).filter(e=>null!==e):[];this.items=t.slice(0,Y),this.meta=(e=>{const t=ee(e)?e:{};return{integrity:"synced"===t.integrity||"limited"===t.integrity||"incomplete"===t.integrity||"unknown"===t.integrity?t.integrity:"preview",limited:!0===t.limited,storageLimit:"number"==typeof t.storageLimit?t.storageLimit:Y,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:X,source:"localPreview",lastSyncFinishedTs:"number"==typeof t.lastSyncFinishedTs?t.lastSyncFinishedTs:void 0,lastSuccessfulAt:"number"==typeof t.lastSuccessfulAt?t.lastSuccessfulAt:void 0,reason:"string"==typeof t.reason?t.reason:void 0}})(e.meta)}setSnapshot(e){this.items=e.items.map(e=>Z(e)).slice(0,Y),this.meta={...e.meta,source:"localPreview",storageLimit:Y,serverLimit:X,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>Z(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>Z(e)),meta:{...this.meta,source:"localPreview"}}}}class oe{constructor(e,t){this.groupId=e,this.manager=t}getSummary(){return this.manager.getGroupSummaryForHandle(this.groupId)}getDetail(){return this.manager.getGroupDetailForHandle(this.groupId)}refresh(){return this.manager.refreshGroupDetailForHandle(this.groupId)}updateInfo(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}updateConfigs(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}changeOwner(e){return this.manager.changeGroupOwner({groupId:this.groupId,newOwner:e.newOwner})}destroy(){return this.manager.destroyGroup(this.toTarget())}leave(){return this.manager.leaveGroup(this.toTarget())}getMembers(e={}){return this.manager.getGroupMemberList({groupId:this.groupId,...e})}removeMembers(e){return this.manager.removeGroupMembers(this.toUserBatchParams(e))}getAdmins(){return this.manager.getGroupAdminList(this.toTarget())}addAdmin(e){return this.manager.addGroupAdmin({groupId:this.groupId,userId:e.userId})}removeAdmin(e){return this.manager.removeGroupAdmin({groupId:this.groupId,userId:e.userId})}getMuteList(e){return this.manager.getGroupMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteGroupMembers({groupId:this.groupId,userIds:e.userIds,muteDuration:e.muteDuration})}unmuteMembers(e){return this.manager.unmuteGroupMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllGroupMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllGroupMembers(this.toTarget())}getBlocklist(e){return this.manager.getGroupBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockGroupMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockGroupMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getGroupAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToGroupAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromGroupAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInGroupAllowList({groupId:this.groupId})}checkIfInMuteList(){return this.manager.checkIfInGroupMuteList(this.toTarget())}getAnnouncement(){return this.manager.getGroupAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateGroupAnnouncement({groupId:this.groupId,announcement:e.announcement})}getSharedFileList(e={}){return this.manager.getGroupSharedFileList({groupId:this.groupId,...e})}uploadSharedFile(e){return this.manager.uploadGroupSharedFile({groupId:this.groupId,...e})}deleteSharedFile(e){return this.manager.deleteGroupSharedFile({groupId:this.groupId,fileId:e.fileId})}downloadSharedFile(e){return this.manager.downloadGroupSharedFile({groupId:this.groupId,...e})}setMemberAttributes(e){return this.manager.setGroupMemberAttributes({groupId:this.groupId,userId:e.userId,memberAttributes:e.memberAttributes})}getMembersAttributes(e){return this.manager.getGroupMembersAttributes({groupId:this.groupId,userIds:e.userIds,keys:e.keys})}toTarget(){return{groupId:this.groupId}}toUserBatchParams(e){return{groupId:this.groupId,userIds:e.userIds}}}const se=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},ne=e=>new r(`${e} is required`,{code:o.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),ae=(e,t)=>new r(t,{code:o.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),ie=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw ne(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,s)=>{if("string"!=typeof e)throw ae(`${t}[${s}]`,`${t}[${s}] must be a string`);const n=e.trim();n&&!o.has(n)&&(o.add(n),r.push(n))}),0===r.length)throw ne(t);return r},ue=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw ne(t);return e.trim()},pe=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw ae(t,`${t} must be a string`);return e}},de=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw ae(t,`${t} must be a boolean`);return e}},ce=(e,t)=>`/${e.orgName}/${e.appName}${t}`,me=/* @__PURE__ */new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),le=e=>{const t=v();"number"==typeof e?.pageNum&&t.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize));const r=t.toString();return r?`?${r}`:""},he=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups?resource=${o.encodedResource}`);return(e=>{const t=k(e),r=F(t[0]),o=J(e)??r;return{groupId:o&&H(o)||r&&H(r)||""}})(await e.post(s,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?ie(r.memberIds,"params.memberIds"):[],public:r.public,approval:r.joinApprovalRequired,allowinvites:r.allowInvites,invite_need_confirm:r.inviteNeedConfirm,maxusers:r.maxMembers,custom:r.ext,avatar:r.avatar},{operation:"createGroup"}))},ge=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=ce(o,`/chatgroups/${encodeURIComponent(s)}?joined_time=true&version=v3`),a=await e.get(n,{operation:"getGroupInfo"});return K(a)},Ie=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n={},a=pe(r.name,"params.name"),i=pe(r.description,"params.description"),u=pe(r.avatar,"params.avatar"),p=pe(r.ext,"params.ext"),d=de(r.public,"params.public"),c=de(r.joinApprovalRequired,"params.joinApprovalRequired"),m=de(r.allowInvites,"params.allowInvites"),l=de(r.inviteNeedConfirm,"params.inviteNeedConfirm"),h=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw ae(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==a&&(n.groupname=a),void 0!==i&&(n.description=i),void 0!==u&&(n.avatar=u),void 0!==p&&(n.custom=p),void 0!==d&&(n.public=d),void 0!==c&&(n.membersonly=c),void 0!==m&&(n.allowinvites=m),void 0!==l&&(n.invite_need_confirm=l),void 0!==h&&(n.maxusers=h),0===Object.keys(n).length)throw ne("params");const g=ce(o,`/chatgroups/${encodeURIComponent(s)}?resource=${o.encodedResource}&version=v3`);await e.put(g,n,{operation:"updateGroupInfo"})},ye=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/users${(e=>{const t=v();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const n of k(e)){const e=F(n);if(!e)continue;const r=$(e.owner),o=$(e.admin),s=$(e.member),a=r??o??s;if(!a)continue;const i=x(e.joinedAt)??x(e.joined_time);t.push({user:z(a),role:r?"owner":o?"admin":"member",...void 0===i?{}:{joinedAt:i}})}const r=q(e,"pagenum"),o=q(e,"pagesize"),s=B(e,o);return{items:t,pageNum:r,pageSize:o,...void 0===s?{}:{hasMore:s}}})(await e.get(s,{operation:"getGroupMemberList"}))},fe=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin`),n=await e.get(s,{operation:"getGroupAdminList"});return W(n)},_e=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=le(r),a=n?"&":"",i=ce(o,`/chatgroups/${encodeURIComponent(s)}/mute?version=v3${a}${n.replace("?","")}`);return(e=>{const t=[];for(const r of k(e)){const e=$(r);if(e){t.push({user:z(e)});continue}const o=F(r);if(!o)continue;const s=$(o.user);if(!s)continue;const n=x(o.expire);t.push({user:z(s),...void 0===n?{}:{muteExpire:n}})}return t})(await e.get(i,{operation:"getGroupMuteList"}))},we=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=le(r),a=n?"&":"",i=ce(o,`/chatgroups/${encodeURIComponent(s)}/blocks/users?version=v3${a}${n.replace("?","")}`),u=await e.get(i,{operation:"getGroupBlocklist"});return W(u).map(e=>({user:e}))},Ge=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users`),n=await e.get(s,{operation:"getGroupAllowlist"});return W(n).map(e=>({user:e}))},be=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=J(e)??{};return{announcement:P(t.announcement)??""}})(await e.get(s,{operation:"getGroupAnnouncement"}))},ve=async(e,t,r)=>{const o=se(t),s=v();s.set("pagenum",String(r.pageNum??1)),s.set("pagesize",String(r.pageSize??20));const n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/share_files?${s.toString()}`);return(e=>{const t=q(e,"pagenum"),r=q(e,"pagesize"),o=B(e,r);return{items:k(e).map(e=>Q(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===o?{}:{hasMore:o}}})(await e.get(n,{operation:"getGroupSharedFileList"}))},Re=(e,t)=>{const r=se(e);return ce(r,`/chatgroups/${encodeURIComponent(ue(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(ue(t.fileId,"params.fileId"))}`)},Se=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=ue(r.userId,"params.userId"),a=((e,t,r)=>{if(t!==e.userId)return null;const o=Object.entries(r);if(0===o.length)return null;let s;for(const[n,a]of o){if(!me.has(n)||"string"!=typeof a)return null;if(void 0!==s){if(s!==a)return null}else s=a}return void 0===s?null:{nameCard:s}})(t,n,r.memberAttributes);if(a){const t=ce(o,`/sdk/chatgroups/${encodeURIComponent(s)}/nameCard`);return await e.put(t,a,{operation:"setGroupMemberAttributes"})}const i=ce(o,`/sdk/metadata/chatgroup/${encodeURIComponent(s)}/user/${encodeURIComponent(n)}?resource=${o.encodedResource}`);return await e.put(i,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},Ae=async(e,t,r)=>{const o=se(t),s=ce(o,`/sdk/metadata/chatgroup/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/get`);return(e=>{const t=J(e)??{},r=F(t.data)??t,o={};for(const[s,n]of Object.entries(r)){const e=F(n);e&&(o[s]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:o}})(await e.post(s,{targets:ie(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},Ue=t=>{const r=e(t)?t:{},o=r.data,s=e(o)?o.data:void 0,n=Array.isArray(o)?o:Array.isArray(s)?s:null;if(Array.isArray(n))return Ee(n);const a=e(o)?o:r,i=e(a.namecards)?a.namecards:a,u={};for(const[p,d]of Object.entries(i)){if("string"==typeof d){u[p]={namecard:d};continue}if(!e(d))continue;const t=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof t&&(u[p]={namecard:t,namecardUpdateTime:Ce(d)})}return u},Ee=t=>{const r={};return t.forEach(t=>{if(!e(t))return;const o=t.username??t.userId??t.userid??t.user_id,s=t.name_card??t.namecard??t.nameCard??t.groupNamecard??t.group_namecard??t.group_name_card;"string"==typeof o&&o.trim()&&"string"==typeof s&&(r[o.trim()]={namecard:s,namecardUpdateTime:Ce(t)})}),r},Ce=e=>y("number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.timestamp?e.timestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0),Oe=t=>{if(e(t))return y("number"==typeof t.timestamp?t.timestamp:"number"==typeof t.update_timestamp?t.update_timestamp:"number"==typeof t.updateTimestamp?t.updateTimestamp:"number"==typeof t.lastModified?t.lastModified:"number"==typeof t.last_modified?t.last_modified:void 0)};class Te{constructor(e){this.repository=e}applyPatch(e){e.shouldMarkStale&&this.repository.markStale(e.groupId);const t=this.repository.getDetailSnapshot(e.groupId);if(!e.groupPatch)return t;const r=t??{groupId:e.groupId,name:e.groupPatch.name??e.groupName??""};return this.repository.mergeDetail({...r,...e.groupPatch,groupId:e.groupId})}}const Me=e=>({...e}),De=e=>({...e,owner:e.owner?{...e.owner}:void 0});class Ne{constructor(e){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null,this.groupId=e}mergeSummary(e){e.groupId===this.groupId&&(this.summarySnapshot=Me({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=De({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=Me(this.toSummaryFromDetail(this.detailSnapshot)),this.loadedSummary=!0,this.loadedDetail=!0,this.stale=!1,this.lastPatchedAt=Date.now(),this.lastHydratedAt=Date.now())}markStale(){this.stale=!0,this.lastPatchedAt=Date.now()}clear(){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null}getSummarySnapshot(){return this.summarySnapshot?Me(this.summarySnapshot):this.detailSnapshot?Me(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?De(this.detailSnapshot):null}isStale(){return this.stale}hasLoadedSummary(){return this.loadedSummary}hasLoadedDetail(){return this.loadedDetail}getLastPatchedAt(){return this.lastPatchedAt}getLastHydratedAt(){return this.lastHydratedAt}toSummaryFromDetail(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,public:e.public,joinApprovalRequired:e.joinApprovalRequired,allowInvites:e.allowInvites,maxMembers:e.maxMembers,role:e.role,disabled:e.disabled}}}class Le{toSummary(e){const t=e.getSummarySnapshot();return t?(e=>({...e}))(t):null}toDetail(e){const t=e.getDetailSnapshot();return t?(e=>({...e,owner:e.owner?{...e.owner}:void 0}))(t):null}}class Fe{constructor(){this.groups=/* @__PURE__ */new Map,this.joinedGroupById=/* @__PURE__ */new Map,this.removedJoinedGroupIds=/* @__PURE__ */new Set,this.snapshotMapper=new Le,this.joinedGroupSnapshot=null,this.sessionKey=null}ensureSession(e){return this.sessionKey!==e&&(this.sessionKey=e,this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null,!0)}getSessionKey(){return this.sessionKey}getOrCreate(e){const t=this.groups.get(e);if(t)return t;const r=new Ne(e);return this.groups.set(e,r),r}mergeSummary(e){return this.getOrCreate(e.groupId).mergeSummary(e),this.getSummarySnapshot(e.groupId)??{...e}}mergeSummaries(e){return e.map(e=>this.mergeSummary(e))}applyJoinedGroupSnapshot(e){const t=e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId));this.joinedGroupSnapshot={items:t.map(e=>({...e})),meta:{...e.meta}},this.joinedGroupById.clear();for(const r of t){const e={...r};this.joinedGroupById.set(e.groupId,e),this.mergeSummary(this.toGroupSummary(e))}}getJoinedGroupSnapshot(e){return this.joinedGroupSnapshot?{items:this.joinedGroupSnapshot.items.map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}}:e?{items:e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId)).map(e=>({...e})),meta:{...e.meta}}:{items:[],meta:{integrity:"unknown",limited:!1,storageLimit:100,serverLimit:3e3,source:"sync"}}}getJoinedGroupSummarySnapshot(e,t){const r=this.joinedGroupById.get(e);if(r)return{...r};if(this.removedJoinedGroupIds.has(e))return null;const o=t?.items.find(t=>t.groupId===e);return o?{...o}:null}addJoinedGroupIfAbsent(e,t){const r=this.getJoinedGroupSnapshot(t);return r.items.some(t=>t.groupId===e.groupId)?null:(this.removedJoinedGroupIds.delete(e.groupId),this.applyJoinedGroupSnapshot({items:[{...e},...r.items],meta:{...r.meta}}),this.getJoinedGroupSnapshot())}mergeJoinedGroupSummary(e,t){const r=this.joinedGroupById.get(e);if(!r||!this.joinedGroupSnapshot)return null;const o={...r,...t,groupId:e};return this.joinedGroupById.set(e,o),this.mergeSummary(this.toGroupSummary(o)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...o}:{...t}),meta:{...this.joinedGroupSnapshot.meta}},this.getJoinedGroupSnapshot()}mergeDetail(e){const t=this.mergeJoinedGroupFieldsIntoDetail(e);return this.getOrCreate(t.groupId).mergeDetail(t),this.getDetailSnapshot(t.groupId)??{...t}}mergeDetails(e){return e.map(e=>this.mergeDetail(e))}getSummarySnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toSummary(t):null}getDetailSnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toDetail(t):null}hasFreshDetail(e){const t=this.groups.get(e);return Boolean(t&&t.hasLoadedDetail()&&!t.isStale())}markStale(e){this.getOrCreate(e).markStale()}delete(e){this.groups.delete(e),this.joinedGroupById.delete(e),this.joinedGroupSnapshot&&(this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.filter(t=>t.groupId!==e).map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}})}markJoinedGroupRemoved(e){this.removedJoinedGroupIds.add(e),this.delete(e)}clear(){this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null}mergeJoinedGroupFieldsIntoDetail(e){const t=this.joinedGroupById.get(e.groupId);return t&&void 0===e.joinedAt&&void 0!==t.joinedAt?{...e,joinedAt:t.joinedAt}:e}toGroupSummary(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,role:e.role,disabled:e.disabled}}}const Pe=0,$e=5,xe=12,je=13,ke=0,Je=1,qe=2,Be=0,He=1,Ve=2,Ke=3,ze=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(o=e.role,o===ke?"owner":o===Je?"admin":o===qe?"member":void 0),disabled:e.disabled,ownerId:e.group_owner,avatarUrl:e.group_avatar,muteAllMembers:e.mute_all,muteExpiration:e.mute_expiration,remindType:(r=e.remind_type,r===Be?"DEFAULT":r===He?"ALL":r===Ve?"AT":r===Ke?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,o},We=e=>e.updatedAt??0,Qe=(e,t)=>{if(!e)return!0;return We(t)>=We(e)},Ye={nested:{easemob:{nested:{joinedgroups:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},GetJoinedGroupsRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},cursor:{type:"string",id:7}}},GroupItem:{fields:{group_id:{type:"string",id:1},group_name:{type:"string",id:2},group_owner:{type:"string",id:3},members_count:{type:"int64",id:4},mute_all:{type:"bool",id:5},disabled:{type:"bool",id:6},description:{type:"string",id:7},group_avatar:{type:"string",id:8},role:{type:"uint32",id:9},mute_expiration:{type:"int64",id:10},remind_type:{type:"int32",id:11},create_at:{type:"uint64",id:12},update_at:{type:"uint64",id:13},joined_timestamp:{type:"int64",id:14}}},GetJoinedGroupsResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},groups:{rule:"repeated",type:"GroupItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5},cursor:{type:"string",id:6}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let Xe=null,Ze=!1;const et=()=>Xe||(Ze||(C.util.Long=U,C.configure(),Ze=!0),E(),Xe=C.Root.fromJSON(Ye),O(Xe),Xe),tt=e=>et().lookupType(e),rt=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if(U.isLong(e))return e.toNumber();if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},ot=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:rt(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:rt(t.protocol_version)??rt(t.protocolVersion)??0}};class st{constructor(){this.requestType=tt("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=tt("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=tt("easemob.joinedgroups.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,cursor:e.cursor});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const o=this.tryDecodeRequest(e);return o||{type:Pe}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==xe?null:{type:r,header:ot(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:rt(t.last_sync_time)??rt(t.lastSyncTime)??0,cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==je?null:{type:r,header:ot(t.header),groups:Array.isArray(t.groups)?t.groups.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{group_id:"string"==typeof t.group_id?t.group_id:"string"==typeof t.groupId?t.groupId:void 0,group_name:"string"==typeof t.group_name?t.group_name:"string"==typeof t.groupName?t.groupName:void 0,group_owner:"string"==typeof t.group_owner?t.group_owner:"string"==typeof t.groupOwner?t.groupOwner:void 0,members_count:rt(t.members_count)??rt(t.membersCount),mute_all:"boolean"==typeof t.mute_all?t.mute_all:"boolean"==typeof t.muteAll?t.muteAll:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,description:"string"==typeof t.description?t.description:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:"string"==typeof t.groupAvatar?t.groupAvatar:void 0,role:rt(t.role),mute_expiration:rt(t.mute_expiration)??rt(t.muteExpiration),remind_type:rt(t.remind_type)??rt(t.remindType),create_at:rt(t.create_at)??rt(t.createAt),update_at:rt(t.update_at)??rt(t.updateAt),joined_timestamp:rt(t.joined_timestamp)??rt(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:rt(t.last_sync_finished_ts)??rt(t.lastSyncFinishedTs),cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==$e?null:{type:r,header:ot(t.header),code:rt(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class nt{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==je)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new s("Joined groups response received after completion",o.REST_BUSINESS_UNKNOWN,{details:{stage:"response_decode",requestId:this.requestId}});if(this.batches.push(e),e.cursor&&(this.latestCursor=e.cursor),e.isLastBatch){if("number"!=typeof e.lastSyncFinishedTs)throw new s("Joined groups final batch missing lastSyncFinishedTs",o.REST_BUSINESS_UNKNOWN,{details:{stage:"completion_meta",requestId:this.requestId}});this.done=!0,this.lastSyncFinishedTs=e.lastSyncFinishedTs}return{done:this.done}}buildResult(){return{batches:this.batches.map(e=>({...e,groups:e.groups.map(e=>({...e}))})),lastSyncFinishedTs:this.lastSyncFinishedTs}}}const at=e=>e.type===je,it=e=>e.type===$e;class ut{constructor(e){this.codec=new st,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new nt(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,t,r){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:t,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,t,r.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:at(t)||it(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(at(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(it(e))throw(e=>{const t=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new s(e.message,o.VALIDATION_REQUIRED,{details:t("request_send",!1)});case 1602:return new s(e.message,o.REST_BUSINESS_UNKNOWN,{details:t("batch_merge",!0)});case 1002:return new n(e.message,{code:o.AUTH_UNAUTHORIZED,details:t("auth",!1)});case 1003:return new s(e.message,o.SERVICE_LIMIT_EXCEEDED,{details:t("server_limit",!0)});default:return new s(e.message,o.REST_BUSINESS_UNKNOWN,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof s?t:new s("Joined groups frame decode failed",o.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:t instanceof Error?t.message:String(t)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class pt{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const r=await this.dependencies.getSyncUrls();if(0===r.length)throw new s("Group sync websocket urls are unavailable",o.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const n=this.buildRequest(),u=await new ut(this.dependencies.getSharedSyncSession()).sync({urls:r,request:n}),p=u.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=ze(r);e&&t.push(e)}return t})(e.groups)),d=this.dependencies.getRuntimeSnapshot(),c=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=/* @__PURE__ */new Map;for(const s of e.incomingItems){const e=r.get(s.groupId)??t.get(s.groupId);Qe(e,s)?r.set(s.groupId,{...e??{},...s,groupId:s.groupId}):e&&r.set(s.groupId,{...e})}const o=r.size>=X;return{items:Array.from(o?e.existingItems.map(e=>({...e})):r.values()).sort((e,t)=>{const r=(t.joinedAt??0)-(e.joinedAt??0);return 0!==r?r:e.groupId.localeCompare(t.groupId)}),meta:{integrity:o?"limited":"synced",limited:o,storageLimit:Y,serverLimit:X,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:d?.items??[],incomingItems:p,lastSyncFinishedTs:u.lastSyncFinishedTs}),m=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(c);const l=this.dependencies.getRuntimeSnapshot()??c;try{await m.commitJoinedGroupPreviewSnapshot(l);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(l,e)&&await m.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw d&&this.dependencies.applyRuntimeSnapshot(d),new a("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}i.warn("Group sync finished",{durationMs:Date.now()-e,itemCount:c.items.length,limited:c.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof s?e:new s("Group sync failed",o.REST_BUSINESS_UNKNOWN,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},n=r.serverCode;return{dataType:"group",code:t.code,stage:(a=r.stage,"config"===a||"socket_connect"===a||"request_send"===a||"response_decode"===a||"batch_merge"===a||"preview_persist"===a||"completion_meta"===a||"auth"===a||"server_limit"===a||"cancelled"===a?a:"socket_connect"),message:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof n||"string"==typeof n?n:void 0};var a})(t);i.warn("Group sync failed",{durationMs:Date.now()-e,stage:r.stage,code:r.code,serverCode:r.serverCode}),this.dependencies.onFinish({status:"failed",error:r})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:r,appName:o}=t(e.appKey);return{type:xe,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:r,app:o,username:e.userId,lastSyncTime:0}}}const dt=g(I,{common:{},apis:{createGroup:{range:"4,110,204,608",errors:{invalid_parameter:{code:110,httpStatus:400,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:4,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1,aliases:["INVALID_GROUP_NAME"]},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]}}},getJoinedGroupList:{range:"",errors:{}},getGroupInfo:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupInfoList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupInfo:{range:"110,603,606,607,608",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},forbidden_op:{code:603,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:110,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},changeGroupOwner:{range:"603,606",errors:{forbidden_op:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},destroyGroup:{range:"603,606,607",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},leaveGroup:{range:"602,603,606",errors:{not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},owner_cannot_leave:{code:603,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"owner can not quit group"},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},joinGroup:{range:"600-607,613",errors:{group_invalid_id:{code:600,retryable:!1,aliases:["GROUP_INVALID_ID"]},already_joined:{code:601,retryable:!1,aliases:["ALREADY_JOINED","GROUP_ALREADY_JOINED","group_already_joined"]},not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},group_authorization:{code:603,httpStatus:403,retryable:!1,aliases:["NEED_APPROVAL","GROUP_PERMISSION_DENIED"]},group_full:{code:604,httpStatus:403,retryable:!1,aliases:["GROUP_FULL","GROUP_MEMBERS_FULL"],matchField:"error_description",matchPattern:"member list is full"},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["GROUP_NOT_FOUND","service_resource_not_found"]},group_disabled:{code:607,retryable:!1,aliases:["GROUP_DISABLED"]},group_user_in_blocklist:{code:613,httpStatus:403,retryable:!1,aliases:["GROUP_USER_IN_BLOCKLIST"],matchField:"error_description",matchPattern:"is in the blacklist"}}},inviteUsersToGroup:{range:"204,603,606,607",errors:{group_authorization:{code:603,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]},group_not_found:{code:606,retryable:!1,aliases:["GROUP_NOT_FOUND"]},group_disabled:{code:607,retryable:!1}}},acceptGroupJoinRequest:{range:"",errors:{}},rejectGroupJoinRequest:{range:"",errors:{}},acceptInvitation:{range:"",errors:{}},rejectInvitation:{range:"",errors:{}},removeGroupMembers:{range:"",errors:{}},addGroupAdmin:{range:"",errors:{}},removeGroupAdmin:{range:"",errors:{}},muteGroupMembers:{range:"",errors:{}},unmuteGroupMembers:{range:"",errors:{}},muteAllGroupMembers:{range:"",errors:{}},unmuteAllGroupMembers:{range:"",errors:{}},blockGroupMembers:{range:"",errors:{}},unblockGroupMembers:{range:"",errors:{}},addUsersToGroupAllowlist:{range:"",errors:{}},removeUsersFromGroupAllowlist:{range:"",errors:{}},checkIfInGroupAllowList:{range:"",errors:{}},getGroupMemberList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},getGroupAdminList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},checkIfInGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupBlocklist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAllowlist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAnnouncement:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupAnnouncement:{range:"110",errors:{announcement_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce into length exceeds limit"},announcement_info_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce info length exceeds limit"}}},getGroupSharedFileList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["RestGroupFeignException"]}}},deleteGroupSharedFile:{range:"603,605,606",errors:{group_authorization:{code:603,retryable:!1},file_not_found:{code:605,retryable:!1,aliases:["GROUP_SHARED_FILE_INVALID_ID"]},resource_not_found:{code:606,retryable:!1}}},setGroupMemberAttributes:{range:"4,210,302,305,602,609-612",errors:{attributes_reach_limit:{code:609,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT"],matchField:"error_code",matchValue:60006},attributes_update_failed:{code:610,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED"],matchField:"error_code",matchValue:60005},attributes_key_reach_limit:{code:611,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT"],matchField:"error_code",matchValue:60009},attributes_value_reach_limit:{code:612,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT"],matchField:"error_code",matchValue:600010},not_joined:{code:602,httpStatus:404,retryable:!1,matchField:"error_code",matchValue:60003},permission_denied:{code:210,httpStatus:401,retryable:!1,matchField:"error_code",matchValue:60001},permission_denied_403:{code:210,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60002},exceed_service_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60007},service_disabled:{code:305,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60004}}},getGroupMembersAttributes:{range:"606",errors:{resource_not_found:{code:606,retryable:!1}}},getGroupNamecards:{range:"",errors:{}}}}),ct=class{constructor(){this.capabilities=["rawNotify:group","group:namecard"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.groupRegistry=/* @__PURE__ */new Map,this.groupRepository=null,this.groupEventSync=null}bind(e,t){this.client=e,this.eventContext=t??null,this.groupRegistry.clear(),this.groupRepository=new Fe,this.groupEventSync=new Te(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,o=await this.buildIncomingEventPayload(r,t);if(!o)return;if(this.eventContext?.dispatch?.(r,o),r!==b.GROUP_MEMBER_ATTRIBUTE_CHANGED)return;if(!("attribute"in o)||!("user"in o))return;const s=this.extractGroupNamecard(o.attribute);if(void 0===s||!o.user?.userId)return;const n=this.client?.getCurrentUserId();o.user.userId!==n&&(this.getCacheManager()?.setGroupNamecards([{groupId:o.groupId,userId:o.user.userId,namecard:s,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(b.USER_GROUP_NAMECARD_UPDATED,{groupId:o.groupId,userId:o.user.userId,namecard:s}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await he(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const t=e.trim();if(0===t.length)throw new r("groupId is required",{code:o.VALIDATION_REQUIRED,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const s=this.groupRegistry.get(t);if(s)return s;this.getGroupSummaryForHandle(t),this.getGroupRepository().getOrCreate(t);const n=new oe(t,this);return this.groupRegistry.set(t,n),n}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await ge(this.getRestClient(t),t,e),o=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(o)})}async getGroupInfoList(t){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const r=this.getRestContextOrThrow(),o=await(async(t,r,o)=>{const s=se(r),n=ie(o.groupIds,"params.groupIds"),a=ce(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),i=await t.get(a,{operation:"getGroupInfoList"});return(e(i)&&Array.isArray(i.data)?i.data:[]).map(e=>K({data:[e]}))})(this.getRestClient(r),r,t),s=await this.hydrateGroupDetailsUsers(o);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,o=e===b.GROUP_DESTROYED?this.resolveLocalGroupName(r.groupId):void 0,s=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,s),e){case b.INVITATION_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,s),reason:r.reason};case b.REQUEST_TO_JOIN_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,s),reason:r.reason};case b.REQUEST_TO_JOIN_ACCEPTED:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,s)};case b.REQUEST_TO_JOIN_DECLINED:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,s),applicant:this.pickEventUser(r.applicantId,s),reason:r.reason};case b.INVITATION_ACCEPTED:case b.INVITATION_DECLINED:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,s),reason:r.reason};case b.USER_REMOVED:return{groupId:r.groupId,groupName:r.groupName};case b.GROUP_DESTROYED:return{groupId:r.groupId,groupName:r.groupName??o};case b.AUTO_ACCEPT_INVITATION:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,s),inviteMessage:r.reason};case b.MUTE_LIST_ADDED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,s),muteExpire:r.muteExpire};case b.MUTE_LIST_REMOVED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,s)};case b.ALLOW_LIST_ADDED:case b.ALLOW_LIST_REMOVED:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,s)};case b.ALL_MEMBER_MUTE_STATE_CHANGED:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case b.ADMIN_ADDED:case b.ADMIN_REMOVED:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,s)};case b.OWNER_CHANGED:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,s),oldOwner:this.pickEventUser(r.oldOwnerId,s)};case b.MEMBERS_JOINED:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,s)};case b.MEMBERS_EXITED:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,s)};case b.ANNOUNCEMENT_CHANGED:return{groupId:r.groupId,announcement:r.announcement??""};case b.SHARED_FILE_ADDED:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,s)};case b.SHARED_FILE_DELETED:return{groupId:r.groupId,fileId:r.fileId??""};case b.GROUP_INFO_CHANGED:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case b.GROUP_DISABLED_CHANGED:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case b.GROUP_MEMBER_ATTRIBUTE_CHANGED:return{groupId:r.groupId,user:this.pickEventUser(r.userId,s),attribute:r.attribute??{},from:r.from,source:r.source};default:return null}}async resolveGroupDetailForEvent(e){this.ensureRepositorySession();const t=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},r=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:t,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(s){i.warn("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:s})}if(r)return r;const o=this.getGroupRepository().getDetailSnapshot(e.groupId);return o||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await Ie(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}?resource=${o.encodedResource}`);await e.put(s,{newowner:ue(r.newOwner,"params.newOwner")},{operation:"changeGroupOwner"})})(this.getRestClient(t),t,e)})}async destroyGroup(e){return this.runOperation("destroyGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}?version=v3&resource=${o.encodedResource}`);await e.delete(s,{operation:"destroyGroup"})})(this.getRestClient(t),t,e),await this.requireClient().handleGroupDestroyedConversation(e.groupId),await this.removeJoinedGroupLocal(e.groupId)})}async leaveGroup(e){return this.runOperation("leaveGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/quit?resource=${o.encodedResource}`);await e.delete(s,{operation:"leaveGroup"})})(this.getRestClient(t),t,e),await this.removeJoinedGroupLocal(e.groupId)})}async joinGroup(e){return this.runOperation("joinGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply?resource=${o.encodedResource}`);await e.post(s,{message:r.message??""},{operation:"joinGroup"})})(this.getRestClient(t),t,e)})}async inviteUsersToGroup(e){return this.runOperation("inviteUsersToGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"inviteUsersToGroup"})})(this.getRestClient(t),t,e)})}async acceptGroupJoinRequest(e){return this.runOperation("acceptGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:ue(r.userId,"params.userId"),verifyResult:!0},{operation:"acceptGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async rejectGroupJoinRequest(e){return this.runOperation("rejectGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:ue(r.userId,"params.userId"),verifyResult:!1,reason:r.reason},{operation:"rejectGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async acceptInvitation(e){return this.runOperation("acceptInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!0},{operation:"acceptInvitation"})})(this.getRestClient(t),t,e)})}async rejectInvitation(e){return this.runOperation("rejectInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await ye(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await fe(this.getRestClient(t),t,e);return this.hydrateUserInfos(e.groupId,r)})}async addGroupAdmin(e){return this.runOperation("addGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin?resource=${o.encodedResource}`);await e.post(s,{newadmin:r.userId},{operation:"addGroupAdmin"})})(this.getRestClient(t),t,e)})}async removeGroupAdmin(e){return this.runOperation("removeGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${o.encodedResource}`);await e.delete(s,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await _e(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async muteGroupMembers(e){return this.runOperation("muteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/mute?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds"),mute_duration:r.muteDuration},{operation:"muteGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteGroupMembers(e){return this.runOperation("unmuteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllGroupMembers(e){return this.runOperation("unmuteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await we(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async blockGroupMembers(e){return this.runOperation("blockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/blocks/users?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"blockGroupMembers"})})(this.getRestClient(t),t,e)})}async unblockGroupMembers(e){return this.runOperation("unblockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await Ge(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async addUsersToGroupAllowlist(e){return this.runOperation("addUsersToGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"addUsersToGroupAllowlist"})})(this.getRestClient(t),t,e)})}async removeUsersFromGroupAllowlist(e){return this.runOperation("removeUsersFromGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(t){return this.runOperation("checkIfInGroupAllowList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=se(r),n=ce(s,`/chatgroups/${encodeURIComponent(ue(o.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof a?a:e(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async checkIfInGroupMuteList(t){return this.runOperation("checkIfInGroupMuteList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=se(r),n=ce(s,`/sdk/chatgroups/${encodeURIComponent(ue(o.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof a?a:e(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return be(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/announcement?resource=${o.encodedResource}`);await e.post(s,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await ve(this.getRestClient(t),t,e),o=await this.resolveGroupContextUserInfoMap(e.groupId,r.items.map(e=>e.fileOwner).filter(e=>void 0!==e));return{...r,items:r.items.map(e=>({...e,fileOwner:e.fileOwner?.userId?o.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const t=this.getRestContextOrThrow(),r=Re(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),n=u({file:e.file}),a=p({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=a?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const u=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[c]:m()},source:n.source,timeoutMs:d,onProgress:e.onFileUploadProgress}));if(!u)throw new Error("platform upload adapter is unavailable");if(u.status<200||u.status>=300)throw new s("uploadGroupSharedFile failed",o.REST_HTTP_ERROR,{details:{status:u.status}});i?.finish({code:u.status,success:!0}),a?.finish({code:0,success:!0}),e.onFileUploadComplete?.(u.body)}catch(l){const t=f(l);throw i?.finish({code:t.code,success:!1,description:t.message}),a?.finish({code:t.code,success:!1,description:t.message}),t.code===o.UPLOAD_ABORTED&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(t),t}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(ue(r.fileId,"params.fileId"))}?resource=${o.encodedResource}`);await e.delete(s,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let t,r;try{const n=this.getRestContextOrThrow(),a=`${n.restBaseUrl}${Re(n,e)}`;t=p({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:a});const i=this.requireClient().getRequestAdapter();if(!i)throw new s("downloadGroupSharedFile request adapter is unavailable",o.REST_NETWORK_ERROR);const u=await i.request({url:a,method:"GET",headers:{Authorization:`Bearer ${n.token}`,...e.secret?{"Share-Secret":e.secret}:{},[c]:m()},responseType:"arraybuffer",timeoutMs:l});if(u.status<200||u.status>=300)throw r?.finish({code:u.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:u.status,success:!1,description:"downloadGroupSharedFile failed"}),new s("downloadGroupSharedFile failed",o.REST_HTTP_ERROR);r?.finish({code:u.status,success:!0}),t?.finish({code:0,success:!0});const d="undefined"!=typeof Blob?new Blob([u.data]):u.data;e.onFileDownloadComplete?.(d)}catch(n){const a=n instanceof s?n.code:o.REST_NETWORK_ERROR,i=n instanceof Error?n.message:String(n);throw r?.finish({code:a,success:!1,description:i}),t?.finish({code:a,success:!1,description:i}),e.onFileDownloadError?.(n),n}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await Se(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return Ae(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,t){0!==t.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const r=this.getRestContextOrThrow(),o=t.map(e=>e.userId),s=await(async(e,t,r)=>{const o=se(t),s=ce(o,`/sdk/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/nameCard/batch/get`),n=await e.post(s,{members:ie(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:Ue(n),responseTimestamp:Oe(n)}})(this.getRestClient(r),r,{groupId:e,userIds:o}),n=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),a=[],u=/* @__PURE__ */new Set;for(const[t,i]of Object.entries(s.items))u.add(t),a.push({groupId:e,userId:t,namecard:i.namecard,namecardUpdateTime:n.get(t)??i.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const p=o.filter(e=>!u.has(e));p.length>0&&"number"==typeof s.responseTimestamp&&a.push(...p.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:s.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(a);for(const e of a)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(b.USER_GROUP_NAMECARD_UPDATED,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});p.length>0&&"number"!=typeof s.responseTimestamp&&i.warn("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:o,missingUserIds:p})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw i.warn(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof s?t:t instanceof Error?new s(`GroupManager ${e} failed: ${t.message}`,o.UNKNOWN):new s(`GroupManager ${e} failed`,o.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new h(e.restBaseUrl,{errorMap:dt,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new s("GroupManager is not bound to client",o.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new Fe),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new Te(this.getGroupRepository())),this.groupEventSync}ensureRepositorySession(){this.getGroupRepository().ensureSession(this.resolveRepositorySessionKey())&&this.groupRegistry.clear()}resolveRepositorySessionKey(){if(!this.client)return null;const e=this.client.getCurrentUserId();if(!e)return null;try{const e=this.client.getRestContext();return`${e.restBaseUrl}:${e.userId}:${e.token}:${e.clientResource}`}catch{return`pending:${e}`}}getCacheManager(){return this.client?.getCacheManager()??null}loadJoinedGroupPreviewSnapshot(){const e=this.getCacheManager();if(e&&"function"==typeof e.loadJoinedGroupPreviewSnapshot)return e.loadJoinedGroupPreviewSnapshot()}resolveLocalGroupName(e){const t=this.getGroupRepository(),r=t.getSummarySnapshot(e)?.name;if(r)return r;const o=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return o||void 0}async resolveMembersJoinedGroupName(e){const t=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(t)return t;const r=this.resolveUsableGroupName(e.groupName,e.groupId);if(r)return r;const o=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await ge(this.getRestClient(t),t,{groupId:e.groupId}),s=this.getGroupRepository();if(s.getSessionKey()!==o)return;return s.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(s){return void i.warn("Members joined group detail enrichment failed",{groupId:e.groupId,error:s})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,t,r){if(t.userId!==e)return;const o=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof o)return;const s=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof s&&i.warn("Group member attributes update response missing server update time",{groupId:t.groupId,userId:t.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:t.groupId,userId:t.userId,namecard:o,namecardUpdateTime:s,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const o of r){const e=y("number"==typeof o?o:Number(o));if("number"==typeof e)return e}}collectUpdateTimeCandidates(t,r,o){if(!e(t))return;o.push(t.lastModified,t.last_modified,t.timestamp,t.updateTime,t.update_time,t.updatedAt,t.updated_at);const s=t.data;if(e(s)){this.collectUpdateTimeCandidates(s,r,o);const t=s[r];e(t)&&this.collectUpdateTimeCandidates(t,r,o)}const n=t.lastModified??t.last_modified;e(n)&&o.push(n[r])}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return L(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return i.warn("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],o=[],s=/* @__PURE__ */new Set;for(const n of r){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return N(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>N(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:N(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case b.ALL_MEMBER_MUTE_STATE_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case b.OWNER_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case b.REQUEST_TO_JOIN_ACCEPTED:case b.AUTO_ACCEPT_INVITATION:return void this.addCurrentUserJoinedGroupFromEvent(t);case b.MEMBERS_JOINED:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case b.MEMBERS_EXITED:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case b.USER_REMOVED:case b.GROUP_DESTROYED:return void(await this.removeJoinedGroupLocal(t.groupId));case b.MUTE_LIST_ADDED:case b.MUTE_LIST_REMOVED:case b.ALLOW_LIST_ADDED:case b.ALLOW_LIST_REMOVED:case b.ADMIN_ADDED:case b.ADMIN_REMOVED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case b.MEMBERS_JOINED:case b.MEMBERS_EXITED:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const o=this.getGroupRepository().getDetailSnapshot(e);return!(!o||"number"!=typeof o.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,o.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(o){return i.warn("Joined group detail enrichment skipped",{groupId:e.groupId,error:o}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(o){return i.warn("Joined group detail enrichment failed",{groupId:e.groupId,error:o}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const o=await ge(this.getRestClient(r),r,{groupId:e}),s=this.getGroupRepository();if(s.getSessionKey()!==t)return!1;s.mergeDetail(o);const n=s.getJoinedGroupSummarySnapshot(e);if(!n)return!1;const a=s.mergeJoinedGroupSummary(e,{...n.name||!o.name?{}:{name:o.name},...void 0!==n.description||void 0===o.description?{}:{description:o.description},...void 0!==n.memberCount||void 0===o.memberCount?{}:{memberCount:o.memberCount},...void 0!==n.role||void 0===o.role?{}:{role:o.role},...void 0!==n.disabled||void 0===o.disabled?{}:{disabled:o.disabled},...n.ownerId||!o.owner?.userId?{}:{ownerId:o.owner.userId},...void 0!==n.avatarUrl||void 0===o.avatarUrl?{}:{avatarUrl:o.avatarUrl},...void 0!==n.muteAllMembers||void 0===o.muteAllMembers?{}:{muteAllMembers:o.muteAllMembers},...void 0!==n.createdAt||void 0===o.createdAt?{}:{createdAt:o.createdAt},...void 0!==n.joinedAt||void 0===o.joinedAt?{}:{joinedAt:o.joinedAt}});if(a){this.persistJoinedGroupSnapshot(a);const t=s.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:o.name||t.name,avatarUrl:o.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void i.warn("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{i.warn("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=R(e),o=await this.getRestClient(t).request(S(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return A(o,r.targets)}async hydrateEntriesWithUsers(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t.map(e=>e.user));return t.map(e=>({...e,user:r.get(e.user.userId)??e.user}))}extractGroupNamecard(e){return e.groupNamecard??e.group_namecard??e.group_name_card??e.namecard}async hydrateGroupDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveGroupContextUserInfoMap(e.groupId,[e.owner]);return{...e,owner:t.get(e.owner.userId)??e.owner}}async hydrateGroupDetailsUsers(e){const t=e.filter(e=>Boolean(e.owner?.userId)).map(e=>({groupId:e.groupId,user:e.owner}));if(0===t.length)return e;const r=await this.resolveGroupUserInfoContexts(t);return e.map(e=>e.owner?.userId?{...e,owner:r.get(_(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),o=await w({groupId:e,users:t,includeNameCard:r,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return r&&this.dispatchFetchedUserInfoUpdates(o.fetchedUserInfos),o.usersById}async resolveGroupUserInfoContexts(e){const t=this.isGroupNamecardEnhancementEnabled(),r=await G({contexts:e,includeNameCard:t,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return t&&this.dispatchFetchedUserInfoUpdates(r.fetchedUserInfos),r.usersByContextKey}async fetchGroupUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}isGroupNamecardEnhancementEnabled(){const e=this.requireClient(),t=e.isUserInfoSyncEnabled;return"function"==typeof t&&t.call(e)}dispatchFetchedUserInfoUpdates(e){if(0===e.length)return;const t=this.requireClient(),r=t.getCurrentUserId(),o=e.find(e=>e.userId===r),s=e.filter(e=>e.userId!==r);o&&t.dispatchOwnInfoUpdated?.(o),t.dispatchUserInfoUpdated?.(s),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new pt(e)}};ct.key="groupManager";let mt=ct;export{oe as G,re as J,mt as a,Q as n};
@@ -0,0 +1 @@
1
+ "use strict";const e=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+");exports.createQueryParams=r=>"function"==typeof URLSearchParams?new URLSearchParams(r):(r=>{const t=new Map;if(r)for(const[e,o]of Object.entries(r))t.set(e,o);return{set(e,r){t.set(e,r)},toString:()=>Array.from(t,([r,t])=>`${e(r)}=${e(t)}`).join("&")}})(r);
@@ -0,0 +1 @@
1
+ const e=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),t=t=>"function"==typeof URLSearchParams?new URLSearchParams(t):(t=>{const r=/* @__PURE__ */new Map;if(t)for(const[e,o]of Object.entries(t))r.set(e,o);return{set(e,t){r.set(e,t)},toString:()=>Array.from(r,([t,r])=>`${e(t)}=${e(r)}`).join("&")}})(t);export{t as c};
@@ -1 +1 @@
1
- "use strict";const e=require("./common-CfAlncj9.cjs"),t=t=>new e.ValidationError(`${t} must be a local paging cursor returned by SDK`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),s=(e,t,s)=>{const n=e+t;return n<s?String(n):""},n=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null;exports.hasSessionMark=(e,t)=>e.marks.includes(t),exports.queryMutedConversationsFromSessionList=r=>{if(!Number.isInteger(r.pageSize)||r.pageSize<=0)throw new e.ValidationError("pageSize must be a positive integer",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const o=((e,s)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw t(s);const n=Number.parseInt(e,10);if(!Number.isSafeInteger(n)||n<0)throw t(s);return n})(r.cursor,"cursor"),i=[];for(const e of r.items){if("chatRoom"===e.conversationType)continue;const t=n(e.remindType);t&&i.push({conversationId:e.conversationId,conversationType:e.conversationType,remindType:t})}return{conversations:i.slice(o,o+r.pageSize),cursor:s(o,r.pageSize,i.length)}},exports.toConversationItem=e=>({...e}),exports.toConversationSummary=e=>{const t=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),s=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:s,lastUpdate:s}};
1
+ "use strict";const e=require("./common-BIpcR2uQ.cjs"),t=t=>new e.ValidationError(`${t} must be a local paging cursor returned by SDK`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),s=(e,t,s)=>{const n=e+t;return n<s?String(n):""},n=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null;exports.hasSessionMark=(e,t)=>e.marks.includes(t),exports.queryMutedConversationsFromSessionList=r=>{if(!Number.isInteger(r.pageSize)||r.pageSize<=0)throw new e.ValidationError("pageSize must be a positive integer",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const o=((e,s)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw t(s);const n=Number.parseInt(e,10);if(!Number.isSafeInteger(n)||n<0)throw t(s);return n})(r.cursor,"cursor"),i=[];for(const e of r.items){if("chatRoom"===e.conversationType)continue;const t=n(e.remindType);t&&i.push({conversationId:e.conversationId,conversationType:e.conversationType,remindType:t})}return{conversations:i.slice(o,o+r.pageSize),cursor:s(o,r.pageSize,i.length)}},exports.toConversationItem=e=>({...e}),exports.toConversationSummary=e=>{const t=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),s=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:s,lastUpdate:s}};
@@ -1 +1 @@
1
- import{V as e,E as s}from"./common-DN_g4O3n.js";const t=t=>new e(`${t} must be a local paging cursor returned by SDK`,{code:s.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),n=(e,s,t)=>{const n=e+s;return n<t?String(n):""},a=e=>({...e}),r=e=>{const s=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),t=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:s,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:t,lastUpdate:t}},i=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,o=a=>{if(!Number.isInteger(a.pageSize)||a.pageSize<=0)throw new e("pageSize must be a positive integer",{code:s.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const r=((e,s)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw t(s);const n=Number.parseInt(e,10);if(!Number.isSafeInteger(n)||n<0)throw t(s);return n})(a.cursor,"cursor"),o=[];for(const e of a.items){if("chatRoom"===e.conversationType)continue;const s=i(e.remindType);s&&o.push({conversationId:e.conversationId,conversationType:e.conversationType,remindType:s})}return{conversations:o.slice(r,r+a.pageSize),cursor:n(r,a.pageSize,o.length)}},d=(e,s)=>e.marks.includes(s);export{r as a,d as h,o as q,a as t};
1
+ import{V as e,E as s}from"./common-BW2KLpvb.js";const t=t=>new e(`${t} must be a local paging cursor returned by SDK`,{code:s.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),n=(e,s,t)=>{const n=e+s;return n<t?String(n):""},a=e=>({...e}),r=e=>{const s=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),t=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:s,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:t,lastUpdate:t}},i=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,o=a=>{if(!Number.isInteger(a.pageSize)||a.pageSize<=0)throw new e("pageSize must be a positive integer",{code:s.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const r=((e,s)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw t(s);const n=Number.parseInt(e,10);if(!Number.isSafeInteger(n)||n<0)throw t(s);return n})(a.cursor,"cursor"),o=[];for(const e of a.items){if("chatRoom"===e.conversationType)continue;const s=i(e.remindType);s&&o.push({conversationId:e.conversationId,conversationType:e.conversationType,remindType:s})}return{conversations:o.slice(r,r+a.pageSize),cursor:n(r,a.pageSize,o.length)}},d=(e,s)=>e.marks.includes(s);export{r as a,d as h,o as q,a as t};
@@ -1 +1 @@
1
- import{i as e}from"./cache-utils-BwRPIZ7n.js";import{p as r,V as t,E as a}from"./common-DN_g4O3n.js";const n={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},i=(e,r,n)=>new t(e,{code:"required"===n?a.VALIDATION_REQUIRED:a.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:e,rule:n}]}}),s=(e,r)=>{if("string"!=typeof e)throw i(`${r} must be a string`,r,"invalid_format");return e},o=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw i(`${r} must be a string, number, or boolean`,r,"invalid_format")},p=(e,r="attribute")=>{const t=n[e];if(!t)throw i(`${r} is invalid`,r,"invalid_format");return t},m=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[n,i]of e.entries()){const e=s(i,`${r}[${n}]`).trim();e&&(a.has(e)||(a.add(e),t.push(e)))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[o,p]of e.entries()){const e=s(p,`${r}[${o}]`);if(!(e in n))throw i(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");a.has(e)||(a.add(e),t.push(e))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},u=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/get`},f=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/${encodeURIComponent(e.userId)}`},l=e=>({targets:m(e)}),g=(e,r)=>({targets:m(e),properties:d(r).map(e=>p(e,"params.attributes"))}),c=r=>!!e(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),h=(r,t)=>{if(Array.isArray(r))for(const a of r){if(!e(a))continue;const r="string"==typeof a.username?a.username:"";r&&t.set(r,a)}},b=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},y=(r,t)=>{const a=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(a?.data&&e(a.data))for(const[e,n]of Object.entries(a.data))c(n)&&t.set(e,n);return h(a?.entities,t),h(a?.data&&e(a.data)?a.data.entities:void 0,t),t})(r),n=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(!a?.lastModified||!e(a.lastModified))return t;for(const[e,n]of Object.entries(a.lastModified))"number"==typeof n&&t.set(e,n);return t})(r),i=[];for(const e of t){const r=a.get(e);r&&i.push({profile:b(e,r),lastModified:n.get(e)})}return i},v=(e,r)=>y(e,r).map(e=>e.profile),$=(e,r,t,a)=>{void 0!==t&&("gender"!==r?e.push([r,s(t,a)]):e.push([r,String(o(t,a))]))},w=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"),I=e=>{const r=[];if($(r,"nickname",e.nickname,"params.nickname"),$(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),$(r,"mail",e.mail,"params.mail"),$(r,"phone",e.phone,"params.phone"),$(r,"gender",e.gender,"params.gender"),$(r,"sign",e.sign,"params.sign"),$(r,"birth",e.birth,"params.birth"),$(r,"ext",e.ext,"params.ext"),0===r.length)throw i("params must include at least one updatable field","params","required");return w(r)},A=(e,r)=>{const t=p(e,"attribute"),a=o(r,"value");if("gender"!==t&&"string"!=typeof a)throw i("value must be a string","value","invalid_format");return w([[t,String(a)]])};export{u as a,l as b,m as c,g as d,d as e,I as f,f as g,A as h,y as i,v as n};
1
+ import{i as e}from"./cache-utils-B99glc0H.js";import{p as r,V as t,E as a}from"./common-BW2KLpvb.js";const n={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},i=(e,r,n)=>new t(e,{code:"required"===n?a.VALIDATION_REQUIRED:a.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:e,rule:n}]}}),s=(e,r)=>{if("string"!=typeof e)throw i(`${r} must be a string`,r,"invalid_format");return e},o=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw i(`${r} must be a string, number, or boolean`,r,"invalid_format")},p=(e,r="attribute")=>{const t=n[e];if(!t)throw i(`${r} is invalid`,r,"invalid_format");return t},m=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[n,i]of e.entries()){const e=s(i,`${r}[${n}]`).trim();e&&(a.has(e)||(a.add(e),t.push(e)))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[o,p]of e.entries()){const e=s(p,`${r}[${o}]`);if(!(e in n))throw i(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");a.has(e)||(a.add(e),t.push(e))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},u=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/get`},f=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/${encodeURIComponent(e.userId)}`},l=e=>({targets:m(e)}),g=(e,r)=>({targets:m(e),properties:d(r).map(e=>p(e,"params.attributes"))}),c=r=>!!e(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),h=(r,t)=>{if(Array.isArray(r))for(const a of r){if(!e(a))continue;const r="string"==typeof a.username?a.username:"";r&&t.set(r,a)}},b=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},y=(r,t)=>{const a=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(a?.data&&e(a.data))for(const[e,n]of Object.entries(a.data))c(n)&&t.set(e,n);return h(a?.entities,t),h(a?.data&&e(a.data)?a.data.entities:void 0,t),t})(r),n=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(!a?.lastModified||!e(a.lastModified))return t;for(const[e,n]of Object.entries(a.lastModified))"number"==typeof n&&t.set(e,n);return t})(r),i=[];for(const e of t){const r=a.get(e);r&&i.push({profile:b(e,r),lastModified:n.get(e)})}return i},v=(e,r)=>y(e,r).map(e=>e.profile),$=(e,r,t,a)=>{void 0!==t&&("gender"!==r?e.push([r,s(t,a)]):e.push([r,String(o(t,a))]))},w=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"),I=e=>{const r=[];if($(r,"nickname",e.nickname,"params.nickname"),$(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),$(r,"mail",e.mail,"params.mail"),$(r,"phone",e.phone,"params.phone"),$(r,"gender",e.gender,"params.gender"),$(r,"sign",e.sign,"params.sign"),$(r,"birth",e.birth,"params.birth"),$(r,"ext",e.ext,"params.ext"),0===r.length)throw i("params must include at least one updatable field","params","required");return w(r)},A=(e,r)=>{const t=p(e,"attribute"),a=o(r,"value");if("gender"!==t&&"string"!=typeof a)throw i("value must be a string","value","invalid_format");return w([[t,String(a)]])};export{u as a,l as b,m as c,g as d,d as e,I as f,f as g,A as h,y as i,v as n};
@@ -1 +1 @@
1
- "use strict";const e=require("./cache-utils-CKbcYPlM.cjs"),r=require("./common-CfAlncj9.cjs"),t={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},n=(e,t,n)=>new r.ValidationError(e,{code:"required"===n?r.ERROR_CODES.VALIDATION_REQUIRED:r.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:n}]}}),a=(e,r)=>{if("string"!=typeof e)throw n(`${r} must be a string`,r,"invalid_format");return e},i=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw n(`${r} must be a string, number, or boolean`,r,"invalid_format")},s=(e,r="attribute")=>{const a=t[e];if(!a)throw n(`${r} is invalid`,r,"invalid_format");return a},o=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw n(`${r} is required`,r,"required");const t=[],i=new Set;for(const[n,s]of e.entries()){const e=a(s,`${r}[${n}]`).trim();e&&(i.has(e)||(i.add(e),t.push(e)))}if(0===t.length)throw n(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw n(`${r} is required`,r,"required");const i=[],s=new Set;for(const[o,d]of e.entries()){const e=a(d,`${r}[${o}]`);if(!(e in t))throw n(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");s.has(e)||(s.add(e),i.push(e))}if(0===i.length)throw n(`${r} is required`,r,"required");return i},p=r=>!!e.isRecord(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),u=(r,t)=>{if(Array.isArray(r))for(const n of r){if(!e.isRecord(n))continue;const r="string"==typeof n.username?n.username:"";r&&t.set(r,n)}},l=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},m=(r,t)=>{const n=(r=>{const t=new Map,n=e.isRecord(r)?r:null;if(n?.data&&e.isRecord(n.data))for(const[e,a]of Object.entries(n.data))p(a)&&t.set(e,a);return u(n?.entities,t),u(n?.data&&e.isRecord(n.data)?n.data.entities:void 0,t),t})(r),a=(r=>{const t=new Map,n=e.isRecord(r)?r:null;if(!n?.lastModified||!e.isRecord(n.lastModified))return t;for(const[e,a]of Object.entries(n.lastModified))"number"==typeof a&&t.set(e,a);return t})(r),i=[];for(const e of t){const r=n.get(e);r&&i.push({profile:l(e,r),lastModified:a.get(e)})}return i},f=(e,r,t,n)=>{void 0!==t&&("gender"!==r?e.push([r,a(t,n)]):e.push([r,String(i(t,n))]))},c=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&");exports.buildFetchUserInfoByAttributeRequest=(e,r)=>({targets:o(e),properties:d(r).map(e=>s(e,"params.attributes"))}),exports.buildFetchUserInfoByUserIdRequest=e=>({targets:o(e)}),exports.buildUpdateOwnInfoByAttributeFormBody=(e,r)=>{const t=s(e,"attribute"),a=i(r,"value");if("gender"!==t&&"string"!=typeof a)throw n("value must be a string","value","invalid_format");return c([[t,String(a)]])},exports.buildUpdateOwnInfoFormBody=e=>{const r=[];if(f(r,"nickname",e.nickname,"params.nickname"),f(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),f(r,"mail",e.mail,"params.mail"),f(r,"phone",e.phone,"params.phone"),f(r,"gender",e.gender,"params.gender"),f(r,"sign",e.sign,"params.sign"),f(r,"birth",e.birth,"params.birth"),f(r,"ext",e.ext,"params.ext"),0===r.length)throw n("params must include at least one updatable field","params","required");return c(r)},exports.buildUserInfoFetchEndpoint=e=>{const{orgName:t,appName:n}=r.parseAppKey(e.appKey);return`/${t}/${n}/metadata/user/get`},exports.buildUserInfoUpdateEndpoint=e=>{const{orgName:t,appName:n}=r.parseAppKey(e.appKey);return`/${t}/${n}/metadata/user/${encodeURIComponent(e.userId)}`},exports.normalizeFetchedUserInfos=(e,r)=>m(e,r).map(e=>e.profile),exports.normalizeUserInfoAttributes=d,exports.normalizeUserInfoFetchRecords=m,exports.normalizeUserInfoTargetIds=o;
1
+ "use strict";const e=require("./cache-utils-gowrxNr8.cjs"),r=require("./common-BIpcR2uQ.cjs"),t={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},n=(e,t,n)=>new r.ValidationError(e,{code:"required"===n?r.ERROR_CODES.VALIDATION_REQUIRED:r.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:n}]}}),a=(e,r)=>{if("string"!=typeof e)throw n(`${r} must be a string`,r,"invalid_format");return e},i=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw n(`${r} must be a string, number, or boolean`,r,"invalid_format")},s=(e,r="attribute")=>{const a=t[e];if(!a)throw n(`${r} is invalid`,r,"invalid_format");return a},o=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw n(`${r} is required`,r,"required");const t=[],i=new Set;for(const[n,s]of e.entries()){const e=a(s,`${r}[${n}]`).trim();e&&(i.has(e)||(i.add(e),t.push(e)))}if(0===t.length)throw n(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw n(`${r} is required`,r,"required");const i=[],s=new Set;for(const[o,d]of e.entries()){const e=a(d,`${r}[${o}]`);if(!(e in t))throw n(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");s.has(e)||(s.add(e),i.push(e))}if(0===i.length)throw n(`${r} is required`,r,"required");return i},p=r=>!!e.isRecord(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),u=(r,t)=>{if(Array.isArray(r))for(const n of r){if(!e.isRecord(n))continue;const r="string"==typeof n.username?n.username:"";r&&t.set(r,n)}},l=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},m=(r,t)=>{const n=(r=>{const t=new Map,n=e.isRecord(r)?r:null;if(n?.data&&e.isRecord(n.data))for(const[e,a]of Object.entries(n.data))p(a)&&t.set(e,a);return u(n?.entities,t),u(n?.data&&e.isRecord(n.data)?n.data.entities:void 0,t),t})(r),a=(r=>{const t=new Map,n=e.isRecord(r)?r:null;if(!n?.lastModified||!e.isRecord(n.lastModified))return t;for(const[e,a]of Object.entries(n.lastModified))"number"==typeof a&&t.set(e,a);return t})(r),i=[];for(const e of t){const r=n.get(e);r&&i.push({profile:l(e,r),lastModified:a.get(e)})}return i},f=(e,r,t,n)=>{void 0!==t&&("gender"!==r?e.push([r,a(t,n)]):e.push([r,String(i(t,n))]))},c=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&");exports.buildFetchUserInfoByAttributeRequest=(e,r)=>({targets:o(e),properties:d(r).map(e=>s(e,"params.attributes"))}),exports.buildFetchUserInfoByUserIdRequest=e=>({targets:o(e)}),exports.buildUpdateOwnInfoByAttributeFormBody=(e,r)=>{const t=s(e,"attribute"),a=i(r,"value");if("gender"!==t&&"string"!=typeof a)throw n("value must be a string","value","invalid_format");return c([[t,String(a)]])},exports.buildUpdateOwnInfoFormBody=e=>{const r=[];if(f(r,"nickname",e.nickname,"params.nickname"),f(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),f(r,"mail",e.mail,"params.mail"),f(r,"phone",e.phone,"params.phone"),f(r,"gender",e.gender,"params.gender"),f(r,"sign",e.sign,"params.sign"),f(r,"birth",e.birth,"params.birth"),f(r,"ext",e.ext,"params.ext"),0===r.length)throw n("params must include at least one updatable field","params","required");return c(r)},exports.buildUserInfoFetchEndpoint=e=>{const{orgName:t,appName:n}=r.parseAppKey(e.appKey);return`/${t}/${n}/metadata/user/get`},exports.buildUserInfoUpdateEndpoint=e=>{const{orgName:t,appName:n}=r.parseAppKey(e.appKey);return`/${t}/${n}/metadata/user/${encodeURIComponent(e.userId)}`},exports.normalizeFetchedUserInfos=(e,r)=>m(e,r).map(e=>e.profile),exports.normalizeUserInfoAttributes=d,exports.normalizeUserInfoFetchRecords=m,exports.normalizeUserInfoTargetIds=o;