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
- import{i as e}from"../../chunks/cache-utils-BwRPIZ7n.js";import{a as t}from"../../chunks/profile-version-DLMz8lqW.js";import{p as r,E as s,V as n,l as a,S as o,f as i,m as d,h as u}from"../../chunks/common-DN_g4O3n.js";import{c as l,b as c,a as p,d as h,e as f,f as b,g as m,h as y,i as I}from"../../chunks/user-info-BfRwS4ZA.js";import{a as g}from"../../chunks/event-system-D6IJA0C4.js";const U=e=>{const{orgName:t,appName:s}=r(e.appKey);return`/${t}/${s}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},_=(e,t="params.userIds")=>l(e,t),w=e=>{const t=_(e);if(t.length>100)throw((e,t,r,a=s.VALIDATION_INVALID_FORMAT)=>new n(e,{code:a,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",s.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},v=(e,t)=>{const r=(e=>_(e))(t);return`${U(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},S=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},C=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],O=d(u,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),x=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,r=t?.getCacheManager();if(!t||!r||!t.getCurrentUserId())return;const s=e.payload,n=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=S(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const o=r.applyUserInfoNotifyPatch(n);if(!o.applied)return void a.debug("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:o.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[o.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",o.record.profile);const i=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(g.CONTACT_INFO_UPDATED,{userInfo:o.record.profile,contact:i})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=c(l(e.userIds,"params.userIds")),n=p(t);a.debug("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=h(l(e.userIds,"params.userIds"),f(e.attributes,"params.attributes")),n=p(t);a.debug("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>U(e))(t),n=w(e.userIds);a.debug("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=v(t,e.userIds);a.debug("UserInfoManager unsubscribeUsersInfo",{userIds:l(e.userIds,"params.userIds")}),await r.request(s,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),r=(e=>U(e))(e);a.debug("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=/* @__PURE__ */new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=b(e),n=m(t);a.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const o=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),i=this.normalizeUpdateEnvelope(o,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([i]),this.dispatchSelfUpdate(i.profile),i.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=y(e,t),o=m(r);a.debug("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const i=await s.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),d=this.normalizeUpdateEnvelope(i,r.userId,{userId:r.userId,[e]:t});return this.writeCache([d]),this.dispatchSelfUpdate(d.profile),d.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof o?t:(a.warn("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new o(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new n("UserInfoManager is not bound to client",{code:s.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new i(e.restBaseUrl,{errorMap:O,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return I(e,t)}normalizeUpdateEnvelope(t,r,s){const n=e(t)?t:null,a=(n&&e(n.data)?n.data:null)??(n&&this.looksLikeUserInfoAttributes(n)?n:null),o=n&&"number"==typeof n.lastModified?n.lastModified:void 0;return{profile:a?this.toUserInfo(r,a):{userId:r,...s??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(t){return!!e(t)&&("nickname"in t||"avatarurl"in t||"avatarUrl"in t||"mail"in t||"phone"in t||"gender"in t||"sign"in t||"birth"in t||"ext"in t)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of C)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return C.filter(t=>t in e)}projectToSummary(e){const r=Date.now(),s=t(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:s,lastSyncAt:r,lastAccess:r,lastUpdate:e.lastModified??r}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};x.key="userInfoManager";let T=x;export{T as UserInfoManager};
1
+ import{i as e}from"../../chunks/cache-utils-B99glc0H.js";import{a as t}from"../../chunks/profile-version-DLMz8lqW.js";import{p as r,E as s,V as n,l as a,S as o,f as i,m as d,i as u}from"../../chunks/common-BW2KLpvb.js";import{c as l,b as c,a as p,d as h,e as f,f as b,g as m,h as y,i as I}from"../../chunks/user-info-22jZtcSi.js";import{a as g}from"../../chunks/event-system-D6IJA0C4.js";const U=e=>{const{orgName:t,appName:s}=r(e.appKey);return`/${t}/${s}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},_=(e,t="params.userIds")=>l(e,t),w=e=>{const t=_(e);if(t.length>100)throw((e,t,r,a=s.VALIDATION_INVALID_FORMAT)=>new n(e,{code:a,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",s.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},v=(e,t)=>{const r=(e=>_(e))(t);return`${U(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},S=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},C=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],O=d(u,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),x=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,r=t?.getCacheManager();if(!t||!r||!t.getCurrentUserId())return;const s=e.payload,n=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=S(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const o=r.applyUserInfoNotifyPatch(n);if(!o.applied)return void a.debug("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:o.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[o.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",o.record.profile);const i=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(g.CONTACT_INFO_UPDATED,{userInfo:o.record.profile,contact:i})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=c(l(e.userIds,"params.userIds")),n=p(t);a.debug("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=h(l(e.userIds,"params.userIds"),f(e.attributes,"params.attributes")),n=p(t);a.debug("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>U(e))(t),n=w(e.userIds);a.debug("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=v(t,e.userIds);a.debug("UserInfoManager unsubscribeUsersInfo",{userIds:l(e.userIds,"params.userIds")}),await r.request(s,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),r=(e=>U(e))(e);a.debug("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=/* @__PURE__ */new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=b(e),n=m(t);a.debug("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const o=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),i=this.normalizeUpdateEnvelope(o,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([i]),this.dispatchSelfUpdate(i.profile),i.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=y(e,t),o=m(r);a.debug("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const i=await s.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),d=this.normalizeUpdateEnvelope(i,r.userId,{userId:r.userId,[e]:t});return this.writeCache([d]),this.dispatchSelfUpdate(d.profile),d.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof o?t:(a.warn("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new o(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new n("UserInfoManager is not bound to client",{code:s.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new i(e.restBaseUrl,{errorMap:O,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return I(e,t)}normalizeUpdateEnvelope(t,r,s){const n=e(t)?t:null,a=(n&&e(n.data)?n.data:null)??(n&&this.looksLikeUserInfoAttributes(n)?n:null),o=n&&"number"==typeof n.lastModified?n.lastModified:void 0;return{profile:a?this.toUserInfo(r,a):{userId:r,...s??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(t){return!!e(t)&&("nickname"in t||"avatarurl"in t||"avatarUrl"in t||"mail"in t||"phone"in t||"gender"in t||"sign"in t||"birth"in t||"ext"in t)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of C)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return C.filter(t=>t in e)}projectToSummary(e){const r=Date.now(),s=t(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:s,lastSyncAt:r,lastAccess:r,lastUpdate:e.lastModified??r}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};x.key="userInfoManager";let T=x;export{T as UserInfoManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easemob-websdk",
3
- "version": "5.0.0",
3
+ "version": "5.0.1",
4
4
  "description": "High-performance, type-safe, extensible instant messaging SDK",
5
5
  "homepage": "https://www.easemob.com/",
6
6
  "type": "module",
package/platform/env.d.ts CHANGED
@@ -64,5 +64,6 @@ export interface RuntimeEnvInfo {
64
64
  }
65
65
  export declare const isMiniProgramRuntime: (value: unknown) => value is MiniProgramRuntimeLike;
66
66
  export declare const isWebRuntime: (runtime: RuntimeDetectionInput) => boolean;
67
+ export declare const hasNativeMiniProgramHost: (runtime: RuntimeDetectionInput) => boolean;
67
68
  export declare const resolveRuntimeEnv: (runtimeInput?: RuntimeDetectionInput, prefer?: RuntimePlatform) => RuntimeEnvInfo;
68
69
  export declare const isMiniProgramPlatform: (platform: RuntimePlatform) => boolean;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * 跨运行时查询参数序列化。
3
+ *
4
+ * 微信小程序等运行时可能没有 URLSearchParams;优先复用原生实现,缺失时使用
5
+ * application/x-www-form-urlencoded 兼容序列化,保持 REST 请求的编码语义一致。
6
+ */
7
+ export interface QueryParams {
8
+ set(name: string, value: string): void;
9
+ toString(): string;
10
+ }
11
+ type QueryParamsInitialValues = Readonly<Record<string, string>>;
12
+ /**
13
+ * 创建可在 Web、React Native 与小程序运行时使用的查询参数对象。
14
+ */
15
+ export declare const createQueryParams: (initialValues?: QueryParamsInitialValues) => QueryParams;
16
+ export {};
@@ -1,4 +1,17 @@
1
1
  /**
2
2
  * 统一获取跨运行时可用的全局对象。
3
3
  */
4
+ type RuntimeHostBindings = {
5
+ readonly wx?: unknown;
6
+ readonly qq?: unknown;
7
+ readonly tt?: unknown;
8
+ readonly swan?: unknown;
9
+ readonly my?: unknown;
10
+ readonly dd?: unknown;
11
+ readonly jd?: unknown;
12
+ readonly ks?: unknown;
13
+ readonly uni?: unknown;
14
+ };
15
+ export declare const createRuntimeInputOverlay: (standardGlobal: object | undefined, hostBindings: RuntimeHostBindings) => object;
4
16
  export declare const getRuntimeGlobal: <TGlobal extends object>(runtimeInput?: TGlobal) => TGlobal;
17
+ export {};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 判断跨平台存储错误是否表示容量或配额超限。
3
+ */
4
+ export declare const isStorageQuotaExceededError: (error: unknown) => boolean;
5
+ /**
6
+ * 将平台容量错误规范化为可安全 reject 的 Error,并保留原始错误作为 cause。
7
+ */
8
+ export declare const normalizeStorageQuotaExceededError: (error: unknown) => Error;
@@ -1 +0,0 @@
1
- const e=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),r=(e,r)=>{if(!e)return r;try{return JSON.parse(e)}catch{return r}},t=e=>{try{return JSON.stringify(e)}catch{return null}},n=e=>!!e&&("undefined"!=typeof DOMException&&e instanceof DOMException?"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name:e instanceof Error&&("QuotaExceededError"===e.name||e.message.includes("quota")));export{t as a,n as b,e as i,r as s};
@@ -1 +0,0 @@
1
- "use strict";exports.isQuotaExceededError=e=>!!e&&("undefined"!=typeof DOMException&&e instanceof DOMException?"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name:e instanceof Error&&("QuotaExceededError"===e.name||e.message.includes("quota"))),exports.isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),exports.safeJsonParse=(e,r)=>{if(!e)return r;try{return JSON.parse(e)}catch{return r}},exports.safeJsonStringify=e=>{try{return JSON.stringify(e)}catch{return null}};
@@ -1 +0,0 @@
1
- "use strict";const e=require("./common-CfAlncj9.cjs"),t=require("./cache-utils-CKbcYPlM.cjs"),r=require("./session-list-query-B6dh-b4Y.cjs"),a=require("./group-user-info-resolver-C5pdiqox.cjs"),i=require("zod"),s={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",RECONNECT_FAILED:"reconnectFailed"},n=e=>{if(e)return e;const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,r={..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}};if(!t)return r;try{Object.assign(t,r)}catch{}return t},o=new WeakMap;const d=new class{constructor(){this.store=new Map}set(e,t){e&&this.store.set(e,t)}get(e){if(e)return this.store.get(e)}consume(e){const t=this.get(e);return t&&this.store.delete(e),t}delete(e){e&&this.store.delete(e)}clear(){this.store.clear()}},l=e=>{if((e=>"undefined"!=typeof File&&e instanceof File)(e)){if("undefined"==typeof URL||"function"!=typeof URL.createObjectURL)return;return URL.createObjectURL(e)}return(e=>"object"==typeof e&&null!==e&&"path"in e&&"string"==typeof e.path)(e)?e.path:(e=>"object"==typeof e&&null!==e&&"uri"in e&&"string"==typeof e.uri)(e)?e.uri:void 0},c=()=>{const e=n().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},g=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),u=(t,r,a)=>{throw new e.ValidationError(t,{code:a,details:{fields:[{path:r,message:t,rule:"invalid_format"}]}})},m=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:g(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},p=(t,r)=>{if(t.sender.userId||u(`messageList[${r}] sender.userId is required`,`messageList[${r}].sender.userId`,e.ERROR_CODES.COMBINE_INVALID_INPUT),t.conversationId&&["singleChat","groupChat","chatRoom"].includes(t.conversationType)||u(`messageList[${r}] conversation is invalid`,`messageList[${r}].conversationId`,e.ERROR_CODES.COMBINE_INVALID_INPUT),(!Number.isInteger(t.timestamp)||t.timestamp<=0)&&u(`messageList[${r}] timestamp must be positive integer`,`messageList[${r}].timestamp`,e.ERROR_CODES.COMBINE_INVALID_INPUT),g(t.body)||u(`messageList[${r}] body must be object`,`messageList[${r}].body`,e.ERROR_CODES.COMBINE_INVALID_INPUT),"combine"===t.type){const a=m(t);(!Number.isInteger(a)||a<0)&&u(`messageList[${r}] combineLevel is invalid`,`messageList[${r}].combineLevel`,e.ERROR_CODES.COMBINE_INVALID_INPUT),a>10&&u(`messageList[${r}] combineLevel exceeds limit`,`messageList[${r}].combineLevel`,e.ERROR_CODES.COMBINE_LEVEL_EXCEEDED)}},h=(t,r=300)=>{(!Number.isInteger(t)||t<=0)&&u("messageList must not be empty","messageList",e.ERROR_CODES.COMBINE_INVALID_INPUT),(!Number.isInteger(r)||r<=0||r>300)&&u("max items is invalid","maxItems",e.ERROR_CODES.COMBINE_INVALID_INPUT),t>r&&u(`messageList max length is ${r}`,"messageList",e.ERROR_CODES.COMBINE_ITEM_LIMIT_EXCEEDED)},y=t=>{h(t.length);for(let r=0;r<t.length;r+=1){const a=t[r];void 0!==a?p(a,r):u(`messageList[${r}] is required`,`messageList[${r}]`,e.ERROR_CODES.COMBINE_INVALID_INPUT)}},v=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=m(r);e>t&&(t=e)}return t+1},I=t=>{(!Number.isInteger(t)||t<=0)&&u("combineLevel must be positive integer","combineLevel",e.ERROR_CODES.COMBINE_INVALID_INPUT),t>10&&u("combineLevel must be <= 10","combineLevel",e.ERROR_CODES.COMBINE_LEVEL_EXCEEDED)};class E{static validate(t,r){try{return{success:!0,data:t.parse(r)}}catch(a){if(a instanceof i.ZodError){const t=a.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),r=`Validation failed: ${t.map(e=>`${e.path}: ${e.message}`).join("; ")}`,i=a.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received)?e.ERROR_CODES.VALIDATION_REQUIRED:e.ERROR_CODES.VALIDATION_INVALID_FORMAT;return{success:!1,error:new e.ValidationError(r,{code:i,details:{fields:t}})}}return{success:!1,error:new e.ValidationError("Unknown validation error",{code:e.ERROR_CODES.VALIDATION_UNKNOWN,details:{fields:[]}})}}}static validateOrThrow(t,r){const a=this.validate(t,r);if(a.success&&void 0!==a.data)return a.data;if(a.error)throw a.error;throw new e.ValidationError("Unknown validation error",{code:e.ERROR_CODES.VALIDATION_UNKNOWN,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const f=(t,r)=>new e.ValidationError(r,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:r,rule:"invalid_format"}]}}),_=(t,r)=>{if("string"!=typeof t||0===t.trim().length)throw(t=>new e.ValidationError(`${t} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}))(r);return t.trim()},R=e=>`mark_${String(e)}`,b=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw f(t,`${t} must be one of singleChat, groupChat, chatRoom`)},C=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",T=e=>"string"==typeof e&&e.length>0?e:void 0,O=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}},w=e=>t.isRecord(e)?e:void 0,L=(e,r)=>{const a=w(e);if(!a)return;const i=(e=>"string"==typeof e?t.safeJsonParse(e,{}):w(e)??{})(a.payload),s=Array.isArray(i.bodies)?i.bodies:[],n=w(s[0])??w(i.body),o=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(n?.type??i.type);if(!n||!o)return;const d=((e,t)=>{if("text"===e)return{content:T(t.msg)??T(t.content)??""};if("custom"===e){const e=w(t.customExts)??w(t.params)??{},r={};for(const[t,a]of Object.entries(e))"string"==typeof a&&(r[t]=a);return{event:T(t.customEvent)??T(t.event)??"",params:r}}if("cmd"===e)return{action:T(t.action)??""};if("image"===e){const e=T(t.url)??T(t.remotePath)??"";return{localUrl:"",filename:T(t.filename)??T(t.displayName),filetype:T(t.filetype)??"application/octet-stream",width:O(t.width),height:O(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:T(t.bigImageUrl),thumbnailUrl:T(t.thumbnailUrl)??T(t.thumbnailRemotePath),secret:T(t.secret)??T(t.secretKey),fileLength:O(t.fileLength)}}return"file"===e?{url:T(t.url)??T(t.remotePath),filename:T(t.filename)??T(t.displayName),filetype:T(t.filetype)??"application/octet-stream",fileSize:O(t.fileSize),fileLength:O(t.fileLength),secret:T(t.secret)??T(t.secretKey)}:"voice"===e?{url:T(t.url)??T(t.remotePath),filename:T(t.filename)??T(t.displayName),filetype:T(t.filetype)??"application/octet-stream",duration:O(t.duration)??0,fileLength:O(t.fileLength),secret:T(t.secret)??T(t.secretKey)}:"video"===e?{url:T(t.url)??T(t.remotePath),filename:T(t.filename)??T(t.displayName),filetype:T(t.filetype)??"application/octet-stream",duration:O(t.duration)??0,width:O(t.width),height:O(t.height),fileLength:O(t.fileLength),secret:T(t.secret)??T(t.secretKey),thumbnailUrl:T(t.thumbnailUrl)??T(t.thumbnailRemotePath)}:"location"===e?{latitude:O(t.latitude)??0,longitude:O(t.longitude)??0,address:T(t.address),buildingName:T(t.buildingName)}:null})(o,n);if(!d)return;const l=T(i.from)??T(a.from)??"",c=T(i.to)??r.conversationId,g=w(i.sender),u={userId:T(g?.userId)??l,nickname:T(g?.nickname),avatarUrl:T(g?.avatarUrl)},m=w(i.ext)??{},p=(e=>{const t=w(e);if(!t)return;const r=T(t.operatorId)??T(t.operator),a=O(t.operationCount)??O(t.count),i=O(t.operationTime)??O(t.edit_time);return r&&void 0!==a&&void 0!==i?{operatorId:r,operationCount:a,operationTime:i}:void 0})(i.modifiedInfo??w(i.meta)?.edit_msg);return{msgServerId:T(a.id)??r.messageId,msgLocalId:T(a.msgLocalId)??"",from:l,to:c,sender:u,conversationId:r.conversationId,conversationType:r.conversationType,type:o,sendStatus:"sent",ext:m,timestamp:O(a.timestamp)??r.timestamp,body:d,direct:l===r.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},S=e=>`${e.conversationType}:${e.conversationId}`,N=t=>{const{orgName:r,appName:a}=e.parseAppKey(t.appKey);return{orgName:r,appName:a,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},A=async(e,r,a,i)=>{const s=N(r),n=(e=>{const r=e,a=r.conversations;if(void 0!==a){if(!Array.isArray(a)||0===a.length)throw f("params.conversations","params.conversations must be a non-empty array");return a.map((e,r)=>{if(!t.isRecord(e))throw f(`params.conversations.${String(r)}`,`params.conversations.${String(r)} must be an object`);return{conversationId:_(e.conversationId,`params.conversations.${String(r)}.conversationId`),conversationType:b(e.conversationType,`params.conversations.${String(r)}.conversationType`)}})}return[{conversationId:_(r.conversationId,"params.conversationId"),conversationType:b(r.conversationType,"params.conversationType")}]})(a),o=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw f(t,`${t} must be an integer between 0 and 19`);return e})(a.mark,"params.mark"),d=await e.request(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channels/mark?resource=${s.encodedResource}`,{method:i?"POST":"DELETE",body:{mark:R(o),targets:n.map(e=>({to:e.conversationId,type:C(e.conversationType)}))},operation:i?"addConversationMark":"removeConversationMark"}),l=(e=>{if(!Array.isArray(e))return new Set;const r=new Set;return e.forEach(e=>{if(!t.isRecord(e))return;const a="string"==typeof e.to?e.to.trim():"",i=(e=>"chat"===e||"singleChat"===e?"singleChat":"groupchat"===e||"groupChat"===e?"groupChat":"chatroom"===e||"chatRoom"===e?"chatRoom":null)(e.type);a&&i&&r.add(S({conversationId:a,conversationType:i}))}),r})((t.isRecord(d)&&t.isRecord(d.data)?d.data:{}).ignore),c=[],g=[];for(const t of n){const e={conversationId:t.conversationId,conversationType:t.conversationType};l.has(S(t))?g.push({...e,reason:"ignored_by_server"}):c.push(e)}return{succeeded:c,failed:g,mark:o,operation:i?"addMark":"removeMark"}},M=async(e,t,r,a)=>{const i=N(t),s=_(r.conversationId,"params.conversationId"),n=b(r.conversationType,"params.conversationType"),o=_(r.messageId,"params.messageId");return await e.request(`/${i.orgName}/${i.appName}/sdk/user/${i.encodedUserId}/user_channel/pin?resource=${i.encodedResource}`,{method:a?"POST":"DELETE",body:{to:s,type:C(n),pin_msg_id:o},operation:a?"pinMessage":"unpinMessage"}),{conversationId:s,conversationType:n,messageId:o,operation:a?"pin":"unpin"}},D=i.z.enum(["singleChat","groupChat","chatRoom"]),U=i.z.record(i.z.unknown()).refine(e=>(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e),"ext must be an object").refine(e=>(e=>{try{return JSON.stringify(e),!0}catch{return!1}})(e),"ext must be JSON serializable"),x=i.z.object({path:i.z.string().min(1,"data.path is required"),size:i.z.number().optional(),name:i.z.string().optional(),type:i.z.string().optional()}),z=i.z.object({uri:i.z.string().min(1,"data.uri is required"),size:i.z.number().optional(),name:i.z.string().optional(),type:i.z.string().optional()}),$="undefined"!=typeof File?i.z.instanceof(File):i.z.never(),k=i.z.union([$,x,z]),V=i.z.object({conversationId:i.z.string().min(1,"conversationId is required"),conversationType:D,ext:U.optional(),timestamp:i.z.number().int().positive("timestamp must be a positive integer").optional(),receiverList:i.z.array(i.z.string().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:i.z.boolean().optional(),webhookEnv:i.z.string().optional(),priority:i.z.enum(["high","normal","low"]).optional(),needReadReceipt:i.z.boolean().optional(),isChatThread:i.z.boolean().optional()}),P=i.z.object({type:i.z.string().min(1,"messageList.type is required"),sender:i.z.object({userId:i.z.string().min(1,"messageList.sender.userId is required"),nickname:i.z.string().optional(),avatarUrl:i.z.string().optional()}),conversationId:i.z.string().min(1,"messageList.conversationId is required"),conversationType:D,timestamp:i.z.number().int().positive("messageList.timestamp must be positive"),body:i.z.record(i.z.unknown()),combineLevel:i.z.number().int().min(0).max(10).optional()}).passthrough(),q=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:i.z.ZodIssueCode.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:i.z.ZodIssueCode.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:i.z.ZodIssueCode.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),F=q(V.extend({content:i.z.string().min(1,"content is required"),targetLanguages:i.z.array(i.z.string().min(1)).optional()})),B=q(V.extend({originalUrl:i.z.string().min(1,"originalUrl is required").optional(),filename:i.z.string().min(1,"filename is required").optional(),filetype:i.z.string().min(1,"filetype is required").optional(),width:i.z.number().positive("width must be positive").optional(),height:i.z.number().positive("height must be positive").optional(),isGif:i.z.boolean().optional(),isOriginalImage:i.z.boolean().optional(),fileLength:i.z.number().positive("fileLength must be positive").optional(),data:k.optional(),thumbnailUrl:i.z.string().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),G=q(V.extend({originalUrl:i.z.string().min(1,"originalUrl is required").optional(),filename:i.z.string().min(1,"filename is required").optional(),filetype:i.z.string().min(1,"filetype is required").optional(),fileSize:i.z.number().positive("fileSize must be positive").optional(),fileLength:i.z.number().positive("fileLength must be positive").optional(),data:k.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),K=q(V.extend({originalUrl:i.z.string().min(1,"originalUrl is required").optional(),filename:i.z.string().min(1,"filename is required").optional(),filetype:i.z.string().min(1,"filetype is required").optional(),duration:i.z.number().positive("duration must be positive"),fileLength:i.z.number().positive("fileLength must be positive").optional(),data:k.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),j=q(V.extend({originalUrl:i.z.string().min(1,"originalUrl is required").optional(),filename:i.z.string().min(1,"filename is required").optional(),filetype:i.z.string().min(1,"filetype is required").optional(),duration:i.z.number().positive("duration must be positive"),width:i.z.number().positive("width must be positive").optional(),height:i.z.number().positive("height must be positive").optional(),fileLength:i.z.number().positive("fileLength must be positive").optional(),thumbnailUrl:i.z.string().min(1).optional(),data:k.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),H=q(V.extend({latitude:i.z.number(),longitude:i.z.number(),address:i.z.string().min(1).optional(),buildingName:i.z.string().min(1).optional()})),X=q(V.extend({action:i.z.string().min(1,"action is required")})),Q=q(V.extend({event:i.z.string().min(1,"event is required"),params:i.z.record(i.z.string()).optional()})),W=q(V.extend({title:i.z.string().min(1,"title is required"),summary:i.z.string().min(1,"summary is required"),compatibleText:i.z.string().min(1).optional(),messageList:i.z.array(P).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),Y=t=>{const r=t?.userId?.trim();if(!r)throw new e.ValidationError("sender.userId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:r,nickname:t?.nickname,avatarUrl:t?.avatarUrl}},Z=()=>c(),J=(t,r)=>{if(t)return t;if(!r)throw new e.ValidationError("url or data is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const a=l(r);if(!a)throw new e.ValidationError("Failed to resolve local url",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return a},ee=e=>!!e.isGif||(e.isOriginalImage??!1),te=(e,t,r,a,i)=>({msgServerId:"",msgLocalId:i??c(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:r,sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:a,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}),re=(e,t)=>{const r=E.validateOrThrow(W,e),a=r.messageList,i=Y(t);y(a);const s=v(a);I(s);const n={title:r.title,summary:r.summary,messageList:a,filename:"combine",filetype:"application/octet-stream",combineLevel:s},d=te(r,i,"combine",n);return((e,t)=>{t&&o.set(e,t)})(d,r.compatibleText),d},ae=t=>{const{orgName:r,appName:a}=e.parseAppKey(t.appKey);return`/${r}/${a}`},ie=e=>{if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.charCodeAt(a);return r},se=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ne=async t=>{try{return await t()}catch(r){if(!(r instanceof e.RestBusinessError))throw r;const t=(t=>{const r="string"==typeof t.details?.serverMessage?t.details.serverMessage:void 0;switch(t.code){case e.ERROR_CODES.SERVICE_NOT_ENABLED:case e.ERROR_CODES.TRANSLATE_SERVICE_NOT_ENABLED:return"Translation service is not enabled";case e.ERROR_CODES.TRANSLATE_PARAM_INVALID:return r?.includes("too long")?"Translation text is too long":r?.includes("target language")?"Invalid target language":"Invalid translation request";case e.ERROR_CODES.TRANSLATE_USAGE_LIMIT:return"Translation quota has been reached";case e.ERROR_CODES.TRANSLATE_FAILED:return"Translation service error";default:return}})(r);if(!t)throw r;throw new e.RestBusinessError(`REST business error: ${t}`,{code:r.code,details:r.details})}},oe=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",de=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},le=e=>({userId:e}),ce=(t,r)=>{if(!se(t)||!se(t.data))throw e.createRestBusinessError({apiName:r,message:`${r} response data is invalid`,mapped:!1});return t.data},ge=(t,r)=>{if(!se(t)||!Array.isArray(t.data))throw e.createRestBusinessError({apiName:r,message:`${r} response data is invalid`,mapped:!1});return t.data},ue=(e,t)=>Array.isArray(e)?e:ge(e,t),me={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},pe={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},he={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},ye=(t,r,a)=>{if(!r)return"";if(r.includes("em-redirect"))return r;const{orgName:i,appName:s}=e.parseAppKey(t.appKey),n=r.indexOf("/chatfiles/"),o=n>=0?r.slice(n):r,d=`${t.restBaseUrl}/${i}/${s}${o}`;return e.appendAttachUrlParams(d,a)},ve=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e))return e;const t=Object.values(e),r=[];for(const a of t)Array.isArray(a)&&r.push(...a);return r.length>0?r:void 0},Ie=(e,t,r)=>{const a=oe(r.contentType??r.type),i=pe[a];if(!i)return null;const s=se(r.content)?r.content:{},n=((e,t)=>{const r=oe(t.conversationType);if("groupchat"===r||"chatroom"===r)return oe(t.receiverId);const a=oe(t.senderId);return a===e?oe(t.receiverId):a})(t,r),o=he[oe(r.conversationType)]??"singleChat",d={msgServerId:oe(r.messageId),msgLocalId:oe(r.messageId),from:oe(r.senderId),to:oe(r.receiverId),conversationId:n,conversationType:o,type:i,ext:se(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(oe(r.sentTime)).getTime(),sender:{userId:oe(r.senderId)},highlight:ve(r.highlight),text:"string"==typeof r.text?r.text:void 0};let l;const c=oe(s.remotePath??s.url),g=oe(s.secret??s.secretKey);switch(i){case"txt":l={type:"txt",content:oe(s.message??r.text)};break;case"img":{const t=ye(e,c,g);l={type:"img",url:t,thumb:s.thumb?ye(e,oe(s.thumb),oe(s.thumb_secret??s.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:g,width:Number(s.width??(se(s.size)?s.size.width:0))||0,height:Number(s.height??(se(s.size)?s.size.height:0))||0,fileLength:Number(s.file_length??s.fileLength??0)};break}case"video":l={type:"video",url:ye(e,c,g),thumb:s.thumb||s.thumbnailRemotePath?ye(e,oe(s.thumb??s.thumbnailRemotePath),oe(s.thumb_secret??s.thumbnailSecretKey)):"",secret:g,filename:oe(s.filename??s.displayName),duration:Number(s.length??s.duration??0),fileLength:Number(s.file_length??s.fileLength??0)};break;case"file":l={type:"file",url:ye(e,c,g),secret:g,filename:oe(s.filename??s.displayName),fileLength:Number(s.file_length??s.fileLength??0)};break;case"loc":l={type:"loc",latitude:Number(s.lat??s.latitude??0),longitude:Number(s.lng??s.longitude??0),address:oe(s.addr??s.address),buildingName:oe(s.buildingName)};break;case"custom":l={type:"custom",customEvent:oe(s.customEvent),customExts:se(s.customExts)?s.customExts:{}};break;default:return null}return{...d,body:l}},Ee=async(e,t,r)=>{const a=`${ae(t)}/users/${t.userId}/messages/search/get`,i=((e,t)=>{const{option:r,pageNum:a=1,pageSize:i=20}=e,s=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),n={searchMode:"default",highlightEnable:!0,page:a,size:i};return 1===s.length?n.keyword=s[0]:(n.keywords=s,n.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?n.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?n.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(n.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(n.contentType=r.msgTypes.map(e=>me[e]??e).join(",")),void 0!==r.startTime&&(n.startTime=r.startTime),void 0!==r.endTime&&(n.endTime=r.endTime),r.searchScope&&(n.searchExt=r.searchScope),r.direction&&(n.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:n}})(r,t.userId),s=await e.post(a,i,{operation:"searchMessages"}),n=se(s)?s:{},o=se(n.data)?n.data:n,d=se(o.data)?o.data:o,l=Array.isArray(d.items)?d.items:Array.isArray(d.list)?d.list:[],c=se(d.pagination)?d.pagination:d,g=Number(c.pageNum??c.page??r.pageNum??1),u=Number(c.pageSize??c.size??r.pageSize??20),m=Number(c.totalPages??0),p=1===c.isFinished||g>=m,h=[];for(const y of l){if(!se(y))continue;const e=Ie(t,t.userId,y);e&&h.push(e)}return{messages:h,pageNum:g,pageSize:u,totalPages:m,isLast:p}},fe=t=>{const{orgName:r,appName:a}=e.parseAppKey(t.appKey);return`/api/sdk/v1/${r}/${a}`},_e=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Re=e=>_e(e)&&"string"==typeof e.path&&e.path.trim().length>0,be=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||Re(e),Ce=e=>{if(!_e(e))return;return{data:_e(e.data)?e.data:void 0,error:_e(e.error)?e.error:void 0}},Te=(t,r)=>{const a=Ce(t),i=a?.data?.text;if("string"!=typeof i)throw new e.SDKError(`${r} response data is invalid`,e.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{api:r,response:t}});return i},Oe=(t,r,a,i="sdk")=>"auth"===i?new e.AuthenticationError(t,{code:r,details:a}):"validation"===i?new e.ValidationError(t,{code:r,details:a}):new e.SDKError(t,r,{details:a}),we=e=>!(void 0===e||_e(e)&&!Array.isArray(e))||(void 0!==e?.format&&"string"!=typeof e.format||(void 0!==e?.sampleRate&&"number"!=typeof e.sampleRate||(void 0!==e?.bitsPerSample&&"number"!=typeof e.bitsPerSample||void 0!==e?.channels&&"number"!=typeof e.channels))),Le=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},Se=t=>{const{serviceCode:r,serviceMessage:a}=(t=>{const r=t instanceof e.SDKError&&_e(t.details)?t.details:void 0,a=Ce(r?.rawResponse??r?.response??t),i=r?.serverCode??a?.error?.code,s=r?.serverMessage??a?.error?.message;return{serviceCode:"string"==typeof i||"number"==typeof i?String(i):void 0,serviceMessage:"string"==typeof s?s:void 0}})(t);if(t instanceof e.UploadError)return Oe("File upload failed",e.ERROR_CODES.UPLOAD_REQUEST_FAILED,{cause:t.details});if(t instanceof e.SDKError&&!r)return t;if(r)switch(r){case"4041001":return Oe("File not found",e.ERROR_CODES.VOICE_TO_TEXT_FILE_NOT_FOUND,{serviceCode:r,serviceMessage:a});case"4001002":return Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{serviceCode:r,serviceMessage:a},"validation");case"5021001":return Oe("File upload failed",e.ERROR_CODES.UPLOAD_REQUEST_FAILED,{serviceCode:r,serviceMessage:a});case"4001003":return Oe("Voice duration exceeds 60 seconds",e.ERROR_CODES.VOICE_TO_TEXT_FILE_DURATION_TOO_LONG,{serviceCode:r,serviceMessage:a},"validation");case"4031001":return Oe("Voice-to-text service is not enabled",e.ERROR_CODES.SERVICE_NOT_ENABLED,{serviceCode:r,serviceMessage:a});case"4031002":return Oe("Beta service usage limit exceeded",e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,{serviceCode:r,serviceMessage:a});case"4001001":return"string"==typeof(i=a)&&i.toLowerCase().includes("uploaded file exceeds")?Oe("File too large",e.ERROR_CODES.VOICE_TO_TEXT_FILE_TOO_LARGE,{serviceCode:r,serviceMessage:a}):Oe(a||"Missing or invalid request parameter",e.ERROR_CODES.VALIDATION_REQUIRED,{serviceCode:r,serviceMessage:a},"validation");case"5021003":case"5001003":return Oe("Voice-to-text failed",e.ERROR_CODES.VOICE_TO_TEXT_FAILED,{serviceCode:r,serviceMessage:a});case"4011001":return Oe(a||"Unauthorized or invalid token",e.ERROR_CODES.AUTH_UNAUTHORIZED,{serviceCode:r,serviceMessage:a},"auth");default:return Oe(a||(t instanceof Error?t.message:"Voice-to-text failed"),e.ERROR_CODES.VOICE_TO_TEXT_FAILED,{serviceCode:r,serviceMessage:a})}var i;return t instanceof e.SDKError?Oe(t.message,t.code,t.details):Oe(t instanceof Error?t.message:"Voice-to-text failed",e.ERROR_CODES.VOICE_TO_TEXT_FAILED)},Ne=(t,r)=>{if(!_e(a=t)||"string"!=typeof a.filename||"string"!=typeof a.filetype||"number"!=typeof a.duration||"type"in a&&void 0!==a.type&&"voice"!==a.type)throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody"},"validation");var a;if(we(r))throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!t.url)throw Oe("File not found",e.ERROR_CODES.VOICE_TO_TEXT_FILE_NOT_FOUND,{path:"voiceMessageBody.url"});if(!Le(t.url))throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody.url"},"validation");return t},Ae=(t,r)=>{if(we(r))throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!be(t))throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"file"},"validation");return t},Me=async(t,r,a,i)=>{const s=Ne(a,i),n=Le(s.url);if(!n)throw((t,r,a,i="invalid")=>new e.ValidationError(t,{code:r,details:{fields:[{path:a,message:t,rule:i}]}}))("File not found",e.ERROR_CODES.VOICE_TO_TEXT_FILE_NOT_FOUND,"voiceMessageBody.url");try{const e=await t.post(`${fe(r)}/speech/transcriptions`,{data:{fileId:n,username:r.userId,...i?{audio:i}:{}}},{operation:"voiceMessageToText"});return{text:Te(e,"voiceMessageToText")}}catch(o){throw Se(o)}},De=i.z.object({keywordList:i.z.array(i.z.string()).min(1,"keywordList must not be empty").max(5,"keywordList must have at most 5 keywords").refine(e=>e.map(e=>e.trim()).filter(e=>e.length>0).length>0,"keywordList must contain at least one non-empty keyword"),keywordListMatchType:i.z.enum(["or","and"]).optional(),conversationId:i.z.string().min(1).optional(),conversationType:i.z.enum(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:i.z.array(i.z.enum(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:i.z.number().optional(),endTime:i.z.number().optional(),searchScope:i.z.enum(["none","with","only"]).optional(),direction:i.z.enum(["up","down"]).optional()}).refine(e=>void 0!==e.conversationId===(void 0!==e.conversationType),{message:"conversationId and conversationType must be provided together"}).refine(e=>void 0!==e.startTime===(void 0!==e.endTime),{message:"startTime and endTime must be provided together"}).refine(e=>void 0===e.startTime||void 0===e.endTime||e.endTime>=e.startTime,{message:"endTime must be >= startTime"}),Ue=i.z.object({option:De,pageNum:i.z.number().int().min(1).default(1),pageSize:i.z.number().int().min(1).max(100).default(20)}),xe=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{sendMessage:{range:"1,4,100,108,110,202,210,213-215,219-222,300-301,303,305,402,405-406,500-501,505-510,602-603,606-607,1200,1299",localErrors:{sendMessage:{operation_cancelled:{code:1,retryable:!1},upload_invalid_appkey:{code:100,retryable:!1},validation_invalid:{code:110,retryable:!1},not_connected:{code:300,retryable:!0},request_timeout:{code:301,retryable:!0},send_failed:{code:303,retryable:!1},upload_failed:{code:402,retryable:!0},file_too_large:{code:405,retryable:!1},file_content_improper:{code:406,retryable:!1},encode_failed:{code:500,retryable:!1}}},errors:{SERVICE_LIMIT_EXCEEDED:{code:4,retryable:!1},TOKEN_EXPIRED:{code:108,retryable:!1},AUTH_FAILED:{code:202,retryable:!1},PERMISSION_DENIED:{code:210,retryable:!1},BIND_ANOTHER_DEVICE:{code:213,retryable:!1},TOO_MANY_DEVICES:{code:214,retryable:!1},USER_MUTED:{code:215,retryable:!1},USER_MUTED_BY_ADMIN:{code:219,retryable:!1},USER_DEVICE_CHANGED:{code:220,retryable:!1},USER_NOT_ON_ROSTER:{code:221,retryable:!1},BLOCKED_BY_RECIPIENT:{code:222,retryable:!1,aliases:["blocked"]},SERVER_SERVING_DISABLED:{code:305,retryable:!1},MESSAGE_INCLUDE_ILLEGAL_CONTENT:{code:501,retryable:!1},SERVICE_NOT_ENABLED:{code:505,retryable:!1},MESSAGE_EXPIRED:{code:506,retryable:!1},MESSAGE_ILLEGAL_WHITELIST:{code:507,retryable:!1},MESSAGE_EXTERNAL_LOGIC_BLOCKED:{code:508,retryable:!1},MESSAGE_CURRENT_LIMITING:{code:509,retryable:!0},MESSAGE_SIZE_LIMIT:{code:510,retryable:!1},GROUP_NOT_JOINED:{code:602,retryable:!1},GROUP_PERMISSION_DENIED:{code:603,retryable:!1},GROUP_NOT_EXIST:{code:606,retryable:!1},GROUP_DISABLED:{code:607,retryable:!1},MESSAGE_BLOCKED:{code:1200,retryable:!1},THIRD_DEFAULT_FAILED:{code:1299,retryable:!1}}},getHistoryMessages:{range:"4,110,202,505",localErrors:{getHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},page_size_exceeded:{code:110,aliases:["pull number cannot be greater","limit is to large"],retryable:!1}}},removeHistoryMessages:{range:"110,112,202,505",localErrors:{removeHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},query_param_reaches_limit:{code:112,aliases:["delete msg list limit"],retryable:!1}}},getGroupMessageReadUsers:{range:"4,110,500",localErrors:{getGroupMessageReadUsers:{validation_invalid:{code:110,retryable:!1}}},errors:{message_not_found:{code:500,retryable:!1}}},recallMessage:{range:"110,201,300,504,505",localErrors:{recallMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},recall_time_limit:{code:504,retryable:!1},recall_disabled:{code:505,retryable:!1}}},updateMessage:{range:"110,111,201,210,300,511",localErrors:{modifyMessage:{validation_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1},not_login:{code:201,retryable:!0},permission_denied:{code:210,retryable:!1},not_connected:{code:300,retryable:!0},edit_failed:{code:511,retryable:!0}}},downloadMessageAttachment:{range:"400,401,403,407",localErrors:{downloadAttachment:{validation_invalid:{code:401,retryable:!1}}},errors:{not_found:{code:400,httpStatus:404,retryable:!1},invalid:{code:401,retryable:!1},download_failed:{code:403,retryable:!0},expired:{code:407,httpStatus:404,retryable:!1}}},downloadAndParseCombineMessage:{range:"110,401,403,500",localErrors:{downloadAndParseCombineMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_param:{code:110,retryable:!1},invalid_type:{code:500,retryable:!1},parse_failed:{code:401,retryable:!0},download_failed:{code:403,retryable:!0}}},addReaction:{range:"110,302,505,600,602,1300-1302",localErrors:{addReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{reaction_already_operated:{code:1301,retryable:!1},reaction_reach_limit:{code:1300,retryable:!1},group_not_joined:{code:602,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1},service_not_enabled:{code:505,retryable:!1},server_busy:{code:302,retryable:!0}}},removeReaction:{range:"110,505,1301,1302",localErrors:{removeReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},getReactionList:{range:"110,505,600",localErrors:{getReactionList:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},group_invalid_id:{code:600,retryable:!1}}},getReactionDetail:{range:"110,505,1302",localErrors:{getReactionDetail:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},pinMessage:{range:"4,110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_limit:{code:4,aliases:["91101"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102"],retryable:!1}}},unpinMessage:{range:"110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getPinnedMessageList:{range:"110,111",errors:{operation_unsupported:{code:111,aliases:["15002"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getSupportedTranslationLanguages:{range:"505",errors:{service_not_enabled:{code:505,aliases:["service not open!"],retryable:!1}}},translateMessage:{range:"505,1110-1113",localErrors:{translateMessage:{validation_invalid:{code:1110,retryable:!1}}},errors:{translate_text_too_long:{code:1110,runtimeMessage:"Translation text is too long",retryable:!1},translate_param_invalid:{code:1110,runtimeMessage:"Invalid target language",retryable:!1},service_not_enabled:{code:1111,runtimeMessage:"Translation service is not enabled",aliases:["service not open!"],retryable:!1},translate_usage_limit:{code:1112,runtimeMessage:"Translation quota has been reached",aliases:["The request has reached the maximum limit"],retryable:!1},translate_failed:{code:1113,runtimeMessage:"Translation service error",aliases:["The request failed, please try again later."],retryable:!1}}},voiceMessageToText:{range:"4,110,202,407-411,505",localErrors:{voiceMessageToText:{validation_invalid:{code:407,retryable:!1},file_not_found:{code:410,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},file_not_found:{code:410,retryable:!1,aliases:["4041001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},voiceFileToText:{range:"4,110,202,402,407-411,505",localErrors:{voiceFileToText:{validation_invalid:{code:407,retryable:!1},upload_required:{code:110,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},upload_failed:{code:402,retryable:!0,aliases:["5021001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},getConversationList:{range:"110",localErrors:{getConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPinnedConversationList:{range:"110",localErrors:{getPinnedConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getConversationListByMark:{range:"110",localErrors:{getConversationListByMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},deleteConversation:{range:"110",localErrors:{deleteConversation:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearConversationUnreadMessageCount:{range:"110,201,300,500",localErrors:{clearConversationUnreadMessageCount:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},clearAllConversationUnreadMessageCount:{range:"201,300,500",errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},sendMessageReadReceipts:{range:"110,300",localErrors:{sendMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_direction:{code:110,retryable:!1},not_connected:{code:300,retryable:!0}}},getGroupMessageReadReceipts:{range:"110,202,210,303",localErrors:{getGroupMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},auth_bad_access_token:{code:202,httpStatus:401,retryable:!1},forbidden_op:{code:210,httpStatus:403,retryable:!1},unknown_exception_error:{code:303,httpStatus:500,retryable:!0}}},setConversationPinned:{range:"110",localErrors:{setConversationPinned:{validation_invalid:{code:110,retryable:!1}}},errors:{}},addConversationMark:{range:"110",localErrors:{addConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},removeConversationMark:{range:"110",localErrors:{removeConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearAllMessagesAndConversations:{range:"",errors:{}},searchMessages:{range:"110,202,303,505",localErrors:{searchMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{parameter_error:{code:110,httpStatus:400,retryable:!1,aliases:["4000005","4000006"]},token_invalid:{code:202,httpStatus:401,retryable:!1,aliases:["4010101"]},service_not_enabled:{code:505,httpStatus:403,retryable:!1,aliases:["4030204"]},app_not_found:{code:110,httpStatus:404,retryable:!1,aliases:["4040302"]},server_error:{code:303,httpStatus:500,retryable:!0,aliases:["5000701","5020801"]}}}}}),ze=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}async sendMessage(e,t){return this.getClientOrThrow().sendMessage(e,t)}createTextMessage(e){return((e,t)=>{const r=E.validateOrThrow(F,e),a=Y(t),i=Z(),s={content:r.content};return r.targetLanguages&&(s.targetLanguages=r.targetLanguages),te(r,a,"text",s,i)})(e,this.buildMessageSenderOrThrow())}createImageMessage(t){return((t,r,a)=>{const i=E.validateOrThrow(B,t),s=Y(r),n=Z(),o=i.data?J(void 0,i.data):"",l=i.originalUrl?e.deriveImageUrls(i.originalUrl,{deriveVariants:!a?.useCustomAttachmentUpload}):void 0;i.data&&d.set(n,i.data);const c=i.isGif??!1,g={localUrl:o,filename:i.filename,filetype:i.filetype,width:i.width,height:i.height,isGif:c,isOriginalImage:ee({isGif:c,isOriginalImage:i.isOriginalImage})};return l?.originalImageUrl&&(g.originalImageUrl=l.originalImageUrl,g.bigImageUrl=l.bigImageUrl,g.thumbnailUrl=l.thumbnailUrl),void 0!==i.fileLength&&(g.fileLength=i.fileLength),i.thumbnailUrl&&(g.thumbnailUrl=i.thumbnailUrl),te(i,s,"image",g,n)})(t,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=E.validateOrThrow(G,e),a=Y(t),i=Z(),s=J(r.originalUrl,r.data);r.data&&d.set(i,r.data);const n={url:s,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(n.fileSize=r.fileSize),void 0!==r.fileLength&&(n.fileLength=r.fileLength),te(r,a,"file",n,i)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=E.validateOrThrow(K,e),a=Y(t),i=Z(),s=J(r.originalUrl,r.data);r.data&&d.set(i,r.data);const n={url:s,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(n.fileLength=r.fileLength),te(r,a,"voice",n,i)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=E.validateOrThrow(j,e),a=Y(t),i=Z(),s=J(r.originalUrl,r.data);r.data&&d.set(i,r.data);const n={url:s,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(n.width=r.width),void 0!==r.height&&(n.height=r.height),void 0!==r.fileLength&&(n.fileLength=r.fileLength),r.thumbnailUrl&&(n.thumbnailUrl=r.thumbnailUrl),te(r,a,"video",n,i)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=E.validateOrThrow(H,e),a=Y(t),i={latitude:r.latitude,longitude:r.longitude};return r.address&&(i.address=r.address),r.buildingName&&(i.buildingName=r.buildingName),te(r,a,"location",i)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=E.validateOrThrow(X,e),a=Y(t),i={action:r.action};return void 0!==r.deliverOnlineOnly&&(i.deliverOnlineOnly=r.deliverOnlineOnly),te(r,a,"cmd",i)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=E.validateOrThrow(Q,e),a=Y(t),i={event:r.event};return r.params&&(i.params=r.params),te(r,a,"custom",i)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return re(e,this.buildMessageSenderOrThrow())}getConversationList(t){if(void 0!==t?.mark&&(!Number.isInteger(t.mark)||t.mark<0||t.mark>19))throw new e.ValidationError("filter.mark must be an integer between 0 and 19",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const a=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(e=>null!==e.lastMessage&&((void 0===t?.isPinned||e.isPinned===t.isPinned)&&!(void 0!==t?.mark&&!r.hasSessionMark(e,t.mark)))).map(r.toConversationItem);return this.getClientOrThrow().markConversationAccess(a.map(e=>({conversationId:e.conversationId,type:e.conversationType}))),a}setCurrentConversation(e){this.validateConversationLocator(e),this.getClientOrThrow().getCacheManager()?.setCurrentConversation({conversationId:e.conversationId,type:e.conversationType})}resetCurrentConversation(){this.getClientOrThrow().getCacheManager()?.resetCurrentConversation()}getCurrentConversation(){const e=this.getClientOrThrow().getCacheManager()?.getCurrentConversation()??null;return e?{conversationId:e.conversationId,conversationType:e.type}:null}refreshSessionList(e){return this.getClientOrThrow().refreshSessionList(e)}async deleteConversation(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const a=N(t),i=_(r.conversationId,"params.conversationId"),s=b(r.conversationType,"params.conversationType"),n=r.deleteRoamingMessages??!1;if("boolean"!=typeof n)throw f("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${a.orgName}/${a.appName}/user/${a.encodedUserId}/user_channel?resource=${a.encodedResource}`,{method:"DELETE",body:{channel:i,type:"groupChat"===s?"groupChat":C(s),delete_roam:n},operation:"deleteConversation"}),{conversationId:i,conversationType:s,operation:"delete"}})(this.getRestClient(t),t,e),a=this.getClientOrThrow(),i=a.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return i?.changed&&a.emitConversationListUpdate("local"),r}async setConversationPinned(e){const r=this.getRestContextOrThrow(),a=await(async(e,r,a)=>{const i=N(r),s=_(a.conversationId,"params.conversationId"),n=b(a.conversationType,"params.conversationType");if("boolean"!=typeof a.pinned)throw f("params.pinned","params.pinned must be a boolean");const o="groupChat"===n?"groupChat":C(n),d=a.pinned?await e.post(`/${i.orgName}/${i.appName}/sdk/user/${i.encodedUserId}/user_channel/top?resource=${i.encodedResource}`,{type:o,to:s},{operation:"setConversationPinned"}):await e.delete(`/${i.orgName}/${i.appName}/sdk/user/${i.encodedUserId}/user_channel/top?type=${encodeURIComponent(o)}&to=${encodeURIComponent(s)}&resource=${i.encodedResource}`,{operation:"setConversationPinned"}),l=t.isRecord(d)&&t.isRecord(d.data)?d.data:{};return{conversationId:s,conversationType:n,operation:"setPinned",isPinned:"boolean"==typeof l.is_top?l.is_top:a.pinned,pinnedTime:"number"==typeof l.update_top_status_time?l.update_top_status_time:a.pinned?Date.now():0}})(this.getRestClient(r),r,e),i=this.getClientOrThrow().getCacheManager(),s=i?.applyConversationPinnedMutation({conversationId:a.conversationId,type:a.conversationType,isPinned:a.isPinned??e.pinned,pinnedTime:a.pinnedTime});return s?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),a}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>A(e,t,r,!0))(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),i=a?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return i?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async removeConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>A(e,t,r,!1))(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),i=a?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return i?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async clearAllMessagesAndConversations(){const e=this.getRestContextOrThrow();await(async(e,t)=>{const r=N(t);await e.post(`/${r.orgName}/${r.appName}/sdk/message/roaming/user/${r.encodedUserId}/delete/all?resource=${r.encodedResource}`,void 0,{operation:"clearAllMessagesAndConversations"})})(this.getRestClient(e),e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversations();r?.changed&&t.emitConversationListUpdate("local")}async pinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>M(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>M(e,t,r,!1))(this.getRestClient(t),t,e))}async getPinnedMessageList(e){const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,r,a)=>{const i=N(r),s=_(a.conversationId,"params.conversationId"),n=b(a.conversationType,"params.conversationType"),o=await e.get(`/${i.orgName}/${i.appName}/sdk/user/${i.encodedUserId}/user_channel/pin?to=${encodeURIComponent(s)}&type=${encodeURIComponent(C(n))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),d=t.isRecord(o)&&t.isRecord(o.data)?o.data:{};return{items:(Array.isArray(d.msg_infos)?d.msg_infos:[]).reduce((e,a)=>{if(!t.isRecord(a))return e;const i="string"==typeof a.pin_msg_id?a.pin_msg_id:t.isRecord(a.message)&&"string"==typeof a.message.id?a.message.id:"";if(!i)return e;const o="number"==typeof a.pin_opt_at?a.pin_opt_at:0,d=L(a.message,{messageId:i,conversationId:s,conversationType:n,currentUserId:r.userId,timestamp:o});return d?(e.push({messageId:i,conversationId:s,conversationType:n,operatorId:"string"==typeof a.pin_operator?a.pin_operator:void 0,pinnedAt:o,message:d}),e):e},[])}})(this.getRestClient(r),r,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(t){this.validateUnreadConversationLocator(t);const r=this.getClientOrThrow(),a=r.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:t.conversationId,type:t.conversationType});a?.changed&&r.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:t.conversationId,conversationType:t.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(i){if(!a?.matched)throw i;e.logger.warn("Conversation unread remote sync failed after local clear",{conversationId:t.conversationId,conversationType:t.conversationType,error:i})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(t){if(this.validateConversationLocator(t),this.requireNonEmptyString(t.messageId,"messageId"),"text"!==t.message.type&&"custom"!==t.message.type)throw new e.ValidationError("only text and custom messages are editable",{code:e.ERROR_CODES.OPERATION_UNSUPPORTED});await this.requireConnectedClient().sendMessageAction({kind:"update",conversationId:t.conversationId,conversationType:t.conversationType,messageId:t.messageId,body:t.message.body,messageType:t.message.type,ext:t.message.ext},(e,t)=>this.buildActionError(e,t));const r=Date.now(),a=this.getCurrentUserIdOrThrow(),i={operatorId:a,operationCount:1,operationTime:r};return{msgServerId:t.messageId,msgLocalId:"",from:a,to:t.conversationId,sender:{userId:a},conversationId:t.conversationId,conversationType:t.conversationType,type:t.message.type,sendStatus:"sent",ext:t.message.ext,timestamp:r,body:t.message.body,direct:"SEND",modifiedInfo:i}}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,a)=>{const i=`${ae(t)}/users/${t.userId}/messageroaming`,s=await e.post(i,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),n=ce(s,"getHistoryMessages"),o=Array.isArray(n.msgs)?n.msgs:[],d=[];for(const l of o){if(!se(l)||"string"!=typeof l.msg||0===l.msg.length)continue;const e=a(ie(l.msg));e&&d.push(e)}return{items:d,cursor:de(n.next_key),hasMore:!0!==n.is_last&&d.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=E.validateOrThrow(Ue,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>Ee(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const a="singleChat"===r.conversationType?"userId":"groupId",i="singleChat"===r.conversationType?"chat":"group",s=encodeURIComponent(t.clientResource),n=r.messageIds?`${ae(t)}/sdk/message/roaming/${i}/user/${t.userId}?${a}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${s}`:`${ae(t)}/sdk/message/roaming/${i}/user/${t.userId}/time?${a}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${s}`;await e.delete(n,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const a=new URLSearchParams;a.set("limit",String(r.pageSize??10)),r.cursor&&a.set("key",r.cursor);const i=`${ae(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${a.toString()}`,s=await e.get(i,{operation:"getGroupMessageReadUsers"}),n=ce(s,"getGroupMessageReadUsers"),o=se(n.group_ack)?n.group_ack:n,d=(Array.isArray(o.userlist)?o.userlist:[]).map(e=>se(e)&&"string"==typeof e.username?{userId:e.username,user:le(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof n.ackmid?n.ackmid:r.messageId,users:d,count:"number"==typeof o.total?o.total:d.length,cursor:de(o.next_key),hasMore:!0!==o.is_last&&d.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=`${ae(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,i=await e.post(a,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return ge(i,"getGroupMessageReadReceipts").map(e=>se(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${ae(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const a=`${ae(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(a,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=new URLSearchParams,i="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");a.set("msgIdList",i),a.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&a.set("groupId",r.groupId);const s=await e.get(`${ae(t)}/reaction/user/${t.userId}?${a.toString()}`,{operation:"getReactionList"});return ge(s,"getReactionList").map(e=>{if(!se(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>se(e)&&"string"==typeof e.reaction?{reaction:e.reaction,count:"number"==typeof e.count?e.count:0,isAddedBySelf:!0===e.state,userIds:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[]}:null).filter(e=>null!==e)}}).filter(e=>null!==e)})(this.getRestClient(t),t,e))}async getReactionDetail(e){if(this.validateReactionParams(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=new URLSearchParams;a.set("msgId",r.messageId),a.set("message",r.reaction),a.set("cursor",r.cursor??""),a.set("limit",String(r.pageSize??20));const i=await e.get(`${ae(t)}/reaction/user/${t.userId}/detail?${a.toString()}`,{operation:"getReactionDetail"}),s=ce(i,"getReactionDetail"),n=Array.isArray(s.reactionUserList)?s.reactionUserList.map(e=>se(e)&&"string"==typeof e.userId?{userId:e.userId,user:le(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],o=Array.isArray(s.userList)?s.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:le(e)})):[],d=n.length>0?n:o;return{reaction:"string"==typeof s.reaction?s.reaction:r.reaction,count:"number"==typeof s.count?s.count:d.length,isAddedBySelf:!0===s.state,reactionUsers:d,cursor:de(s.cursor),hasMore:de(s.cursor).length>0,createdAt:"string"==typeof s.createdAt?s.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await ne(()=>e.get(`${ae(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return ue(r,"getSupportedTranslationLanguages").map(e=>se(e)&&"string"==typeof e.code?{code:e.code,name:"string"==typeof e.name?e.name:e.code,nativeName:"string"==typeof e.nativeName?e.nativeName:e.code}:null).filter(e=>null!==e)})(this.getRestClient(e),e))}async translateMessage(t){if("text"!==t.message.type)throw new e.ValidationError("only text messages can be translated",{code:e.ERROR_CODES.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.type",message:"must be text",rule:"message_type"}]}});const r=t.message.body.content.trim();if(0===r.length)throw new e.ValidationError("message text is required",{code:e.ERROR_CODES.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(t.targetLanguages)||0===t.targetLanguages.length)throw new e.ValidationError("targetLanguages is required",{code:e.ERROR_CODES.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(t.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new e.ValidationError("targetLanguages contains invalid language code",{code:e.ERROR_CODES.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"contains invalid language code",rule:"language_code"}]}});const a=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(t,r,a)=>{const i=await ne(()=>t.post(`${ae(r)}/users/${r.userId}/translate`,{text:a.text,to:[...a.targetLanguages]},{operation:"translateMessage"})),s=ue(i,"translateMessage"),n=se(s[0])?s[0]:null;if(!n)throw e.createRestBusinessError({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(n.translations)?n.translations:[],d=se(n.detectedLanguage)?n.detectedLanguage:void 0;return{detectedLanguage:d&&"string"==typeof d.language?{language:d.language,score:"number"==typeof d.score?d.score:Number(d.score??0)}:void 0,translations:o.map(e=>se(e)&&"string"==typeof e.text&&"string"==typeof e.to?{text:e.text,to:e.to}:null).filter(e=>null!==e)}})(this.getRestClient(a),a,{text:r,targetLanguages:t.targetLanguages}))}async voiceMessageToText(e,t){Ne(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>Me(this.getRestClient(r),r,e,t))}async voiceFileToText(t,r){Ae(t,r);const i=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new e.SDKError("Upload capability is missing for current platform",e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING);return this.executeRestOperation(()=>(async(t,r,i,s)=>{const n=Ae(i,s),o=e.normalizeUploadSource({file:n,fallbackName:Re(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const a=await t.upload({url:`${r.restBaseUrl}${fe(r)}/speech/recognitions`,headers:{Authorization:`Bearer ${r.token}`,Accept:"application/json",[e.REQUEST_ID_HEADER]:e.createTraceId()},source:o.source,fields:{username:r.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let i=a.body;try{i=JSON.parse(a.body)}catch{i=a.body}if(a.status<200||a.status>=300)throw new e.SDKError("Voice-to-text failed",e.ERROR_CODES.VOICE_TO_TEXT_FAILED,{details:{httpStatus:a.status,rawResponse:i}});return{text:Te(i,"voiceFileToText")}}catch(d){if(d instanceof e.SDKError)throw Se(d);throw Se(a.mapUploadAdapterError(d))}})(s,i,t,r))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(t){if("message"in t){if("combine"!==t.message.type)throw new e.ValidationError("message must be a combine message",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT});const r=t.message.body;return{url:r.url??"",secret:r.secret,timeoutMs:t.timeoutMs,maxItems:t.maxItems}}return{url:t.url,secret:t.secret,timeoutMs:t.timeoutMs,maxItems:t.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(t,r){return t===e.ERROR_CODES.AUTH_NOT_LOGIN||t===e.ERROR_CODES.AUTH_UNAUTHORIZED?new e.AuthenticationError(r??"authentication failed",{code:t}):t===e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR||t===e.ERROR_CODES.CONNECTION_TIMEOUT?new e.ConnectionError(r??"connection unavailable",{code:t}):107===t||110===t||205===t||500===t||t===e.ERROR_CODES.VALIDATION_REQUIRED||t===e.ERROR_CODES.VALIDATION_INVALID_FORMAT?new e.ValidationError(r??"invalid parameter",{code:t}):t===e.ERROR_CODES.MESSAGE_RECALL_TIME_LIMIT?new e.SDKError(r??"message recall time limit reached",t):t===e.ERROR_CODES.MESSAGE_EDIT_FAILED?new e.SDKError(r??"message update failed",t):t===e.ERROR_CODES.OPERATION_UNSUPPORTED?new e.ValidationError(r??"operation unsupported",{code:t}):new e.SDKError(r??"message action failed",t)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(t,r){return new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:t,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new e.ValidationError("ChatManager is not bound to event context",{code:e.ERROR_CODES.VALIDATION_REQUIRED});return this.eventContext}getClientOrThrow(){if(!this.client)throw new e.ValidationError("ChatManager is not bound to client",{code:e.ERROR_CODES.VALIDATION_REQUIRED});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:xe,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}requireConnectedClient(){const t=this.getClientOrThrow();if(t.getConnectionState()!==s.CONNECTED)throw new e.ConnectionError("client is not connected",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR});return t}getCurrentUserIdOrThrow(){const t=this.getClientOrThrow().getCurrentUserId();if(!t)throw new e.AuthenticationError("user is not logged in",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return t}buildMessageSenderOrThrow(){const e=this.getClientOrThrow(),t=this.getCurrentUserIdOrThrow(),r=e.getCacheManager()?.getUserInfoSummaries([t],!1)[0];return{userId:t,nickname:r?.nickname,avatarUrl:r?.avatarUrl}}async hydrateGroupMessageReadUsers(e,t){const r=this.getClientOrThrow();if(!r.isUserInfoSyncEnabled()||0===t.users.length)return t;const i=r.getCacheManager(),s=await a.resolveGroupUserInfoMap({groupId:e,users:t.users.map(e=>e.user),includeNameCard:!0,cacheManager:i,fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoReadCapability(r);return t?await t.getUserInfoByUserId({userIds:e}):[]},hydrateGroupNamecards:async(e,t)=>{const a=this.getGroupNamecardHydrationCapability(r);a&&await a.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))}});return this.dispatchFetchedUserInfoUpdates(r,s.fetchedUserInfos),{...t,users:t.users.map(e=>{const t=s.usersById.get(e.userId)??e.user;return{...e,user:t}})}}getUserInfoReadCapability(e){const t=e.getManagerByCapability("userInfo:read");return t&&"function"==typeof t.getUserInfoByUserId?t:null}getGroupNamecardHydrationCapability(e){const t=e.getManagerByCapability("group:namecard");return t&&"function"==typeof t.hydrateMessageProfileGroupNamecards?t:null}dispatchFetchedUserInfoUpdates(e,t){if(0===t.length)return;const r=e.getCurrentUserId(),a=t.find(e=>e.userId===r),i=t.filter(e=>e.userId!==r);a&&e.dispatchOwnInfoUpdated(a),e.dispatchUserInfoUpdated(i),t.length>0&&e.refreshConversationDisplayFromUserInfos(t.map(e=>({userId:e.userId})),"profile")}async executeRestOperation(e){try{return await e()}catch(t){throw this.mapRestError(t)}}mapRestError(t){return t instanceof e.ValidationError||t instanceof e.AuthenticationError||t instanceof e.ConnectionError||t instanceof e.NetworkError?t:t instanceof e.RestTransportError?new e.NetworkError(t.message,{code:t.code,details:t.details}):t instanceof e.RestBusinessError||t instanceof e.SDKError?t:new e.SDKError(String(t),e.ERROR_CODES.UNKNOWN)}};ze.key="chatManager";let $e=ze;exports.ChatManager=$e,exports.ConnectionEventName={CONNECTING:"onConnecting",CONNECTED:"onConnected",DISCONNECTED:"onDisconnected",RECONNECT_FAILED:"onReconnectFailed",TOKEN_WILL_EXPIRE:"onTokenWillExpire",TOKEN_EXPIRED:"onTokenExpired",OFFLINE_MESSAGE_SYNC_START:"onOfflineMessageSyncStart",OFFLINE_MESSAGE_SYNC_FINISH:"onOfflineMessageSyncFinish"},exports.ConnectionEventReason={LOGIN:"login",RECONNECT:"reconnect",ONLINE:"online",OFFLINE_RECOVER:"offline-recover",HEARTBEAT_FAILED:"heartbeat-failed",SEND_TIMEOUT:"send-timeout",CLOSE:"close",ERROR:"error",TIMEOUT:"timeout",LIMIT:"limit",OFFLINE:"offline",TOKEN_EXPIRED:"token-expired"},exports.ConnectionStatus=s,exports.InternalEventName={SEND_TIMEOUT:"onSendTimeout",GROUP_NOTIFY:"onGroupNotify",CHATROOM_NOTIFY:"onChatRoomNotify",CHAT_THREAD_NOTIFY:"onChatThreadNotify",USER_INFO_NOTIFY:"onUserInfoNotify",MESSAGE_SENT:"__internal:onMessageSent"},exports.MAX_COMBINE_MESSAGE_COUNT=300,exports.Validator=E,exports.attachmentFileStore=d,exports.calculateCombineLevel=v,exports.copyCombineCompatibleTextSidecar=(e,t)=>{const r=o.get(e);r&&o.set(t,r)},exports.createLocalFileUrl=l,exports.ensureCombineItemLimit=h,exports.ensureCombineLevel=I,exports.generateMsgLocalId=c,exports.getCombineCompatibleTextSidecar=e=>o.get(e),exports.getRuntimeGlobal=n,exports.validateCombineMessageList=y;
@@ -1,2 +0,0 @@
1
- import{V as e,E as t,p as r,d as a,c as s,R as i,a as n,n as o,b as d,e as l,S as c,A as g,U as u,l as m,C as p,f as h,N as y,g as v,m as I,h as f}from"./common-DN_g4O3n.js";import{i as b,s as T}from"./cache-utils-BwRPIZ7n.js";import{h as _,t as C}from"./session-list-query-Dnp2HbpW.js";import{m as E,r as w}from"./group-user-info-resolver-FNRqDg18.js";import{ZodError as L,z as R}from"zod";const O={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",RECONNECT_FAILED:"reconnectFailed"},N={CONNECTING:"onConnecting",CONNECTED:"onConnected",DISCONNECTED:"onDisconnected",RECONNECT_FAILED:"onReconnectFailed",TOKEN_WILL_EXPIRE:"onTokenWillExpire",TOKEN_EXPIRED:"onTokenExpired",OFFLINE_MESSAGE_SYNC_START:"onOfflineMessageSyncStart",OFFLINE_MESSAGE_SYNC_FINISH:"onOfflineMessageSyncFinish"},M={SEND_TIMEOUT:"onSendTimeout",GROUP_NOTIFY:"onGroupNotify",CHATROOM_NOTIFY:"onChatRoomNotify",CHAT_THREAD_NOTIFY:"onChatThreadNotify",USER_INFO_NOTIFY:"onUserInfoNotify",MESSAGE_SENT:"__internal:onMessageSent"},A={LOGIN:"login",RECONNECT:"reconnect",ONLINE:"online",OFFLINE_RECOVER:"offline-recover",HEARTBEAT_FAILED:"heartbeat-failed",SEND_TIMEOUT:"send-timeout",CLOSE:"close",ERROR:"error",TIMEOUT:"timeout",LIMIT:"limit",OFFLINE:"offline",TOKEN_EXPIRED:"token-expired"},U=e=>{if(e)return e;const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,r={..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}};if(!t)return r;try{Object.assign(t,r)}catch{}return t},S=/* @__PURE__ */new WeakMap,x=e=>S.get(e),D=(e,t)=>{const r=S.get(e);r&&S.set(t,r)};const $=new class{constructor(){this.store=/* @__PURE__ */new Map}set(e,t){e&&this.store.set(e,t)}get(e){if(e)return this.store.get(e)}consume(e){const t=this.get(e);return t&&this.store.delete(e),t}delete(e){e&&this.store.delete(e)}clear(){this.store.clear()}},k=e=>{if((e=>"undefined"!=typeof File&&e instanceof File)(e)){if("undefined"==typeof URL||"function"!=typeof URL.createObjectURL)return;return URL.createObjectURL(e)}return(e=>"object"==typeof e&&null!==e&&"path"in e&&"string"==typeof e.path)(e)?e.path:(e=>"object"==typeof e&&null!==e&&"uri"in e&&"string"==typeof e.uri)(e)?e.uri:void 0},V=()=>{const e=U().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},P=300,q=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),F=(t,r,a)=>{throw new e(t,{code:a,details:{fields:[{path:r,message:t,rule:"invalid_format"}]}})},B=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:q(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},G=(e,r)=>{if(e.sender.userId||F(`messageList[${r}] sender.userId is required`,`messageList[${r}].sender.userId`,t.COMBINE_INVALID_INPUT),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||F(`messageList[${r}] conversation is invalid`,`messageList[${r}].conversationId`,t.COMBINE_INVALID_INPUT),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&F(`messageList[${r}] timestamp must be positive integer`,`messageList[${r}].timestamp`,t.COMBINE_INVALID_INPUT),q(e.body)||F(`messageList[${r}] body must be object`,`messageList[${r}].body`,t.COMBINE_INVALID_INPUT),"combine"===e.type){const a=B(e);(!Number.isInteger(a)||a<0)&&F(`messageList[${r}] combineLevel is invalid`,`messageList[${r}].combineLevel`,t.COMBINE_INVALID_INPUT),a>10&&F(`messageList[${r}] combineLevel exceeds limit`,`messageList[${r}].combineLevel`,t.COMBINE_LEVEL_EXCEEDED)}},z=(e,r=300)=>{(!Number.isInteger(e)||e<=0)&&F("messageList must not be empty","messageList",t.COMBINE_INVALID_INPUT),(!Number.isInteger(r)||r<=0||r>300)&&F("max items is invalid","maxItems",t.COMBINE_INVALID_INPUT),e>r&&F(`messageList max length is ${r}`,"messageList",t.COMBINE_ITEM_LIMIT_EXCEEDED)},j=e=>{z(e.length);for(let r=0;r<e.length;r+=1){const a=e[r];void 0!==a?G(a,r):F(`messageList[${r}] is required`,`messageList[${r}]`,t.COMBINE_INVALID_INPUT)}},H=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=B(r);e>t&&(t=e)}return t+1},X=e=>{(!Number.isInteger(e)||e<=0)&&F("combineLevel must be positive integer","combineLevel",t.COMBINE_INVALID_INPUT),e>10&&F("combineLevel must be <= 10","combineLevel",t.COMBINE_LEVEL_EXCEEDED)};class K{static validate(r,a){try{return{success:!0,data:r.parse(a)}}catch(s){if(s instanceof L){const r=s.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),a=`Validation failed: ${r.map(e=>`${e.path}: ${e.message}`).join("; ")}`,i=s.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received)?t.VALIDATION_REQUIRED:t.VALIDATION_INVALID_FORMAT;return{success:!1,error:new e(a,{code:i,details:{fields:r}})}}return{success:!1,error:new e("Unknown validation error",{code:t.VALIDATION_UNKNOWN,details:{fields:[]}})}}}static validateOrThrow(r,a){const s=this.validate(r,a);if(s.success&&void 0!==s.data)return s.data;if(s.error)throw s.error;throw new e("Unknown validation error",{code:t.VALIDATION_UNKNOWN,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const Q=(r,a)=>new e(a,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:a,rule:"invalid_format"}]}}),W=(r,a)=>{if("string"!=typeof r||0===r.trim().length)throw(r=>new e(`${r} is required`,{code:t.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}}))(a);return r.trim()},Y=e=>`mark_${String(e)}`,Z=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw Q(t,`${t} must be one of singleChat, groupChat, chatRoom`)},J=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",ee=e=>"string"==typeof e&&e.length>0?e:void 0,te=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}},re=e=>b(e)?e:void 0,ae=(e,t)=>{const r=re(e);if(!r)return;const a=(e=>"string"==typeof e?T(e,{}):re(e)??{})(r.payload),s=Array.isArray(a.bodies)?a.bodies:[],i=re(s[0])??re(a.body),n=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(i?.type??a.type);if(!i||!n)return;const o=((e,t)=>{if("text"===e)return{content:ee(t.msg)??ee(t.content)??""};if("custom"===e){const e=re(t.customExts)??re(t.params)??{},r={};for(const[t,a]of Object.entries(e))"string"==typeof a&&(r[t]=a);return{event:ee(t.customEvent)??ee(t.event)??"",params:r}}if("cmd"===e)return{action:ee(t.action)??""};if("image"===e){const e=ee(t.url)??ee(t.remotePath)??"";return{localUrl:"",filename:ee(t.filename)??ee(t.displayName),filetype:ee(t.filetype)??"application/octet-stream",width:te(t.width),height:te(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:ee(t.bigImageUrl),thumbnailUrl:ee(t.thumbnailUrl)??ee(t.thumbnailRemotePath),secret:ee(t.secret)??ee(t.secretKey),fileLength:te(t.fileLength)}}return"file"===e?{url:ee(t.url)??ee(t.remotePath),filename:ee(t.filename)??ee(t.displayName),filetype:ee(t.filetype)??"application/octet-stream",fileSize:te(t.fileSize),fileLength:te(t.fileLength),secret:ee(t.secret)??ee(t.secretKey)}:"voice"===e?{url:ee(t.url)??ee(t.remotePath),filename:ee(t.filename)??ee(t.displayName),filetype:ee(t.filetype)??"application/octet-stream",duration:te(t.duration)??0,fileLength:te(t.fileLength),secret:ee(t.secret)??ee(t.secretKey)}:"video"===e?{url:ee(t.url)??ee(t.remotePath),filename:ee(t.filename)??ee(t.displayName),filetype:ee(t.filetype)??"application/octet-stream",duration:te(t.duration)??0,width:te(t.width),height:te(t.height),fileLength:te(t.fileLength),secret:ee(t.secret)??ee(t.secretKey),thumbnailUrl:ee(t.thumbnailUrl)??ee(t.thumbnailRemotePath)}:"location"===e?{latitude:te(t.latitude)??0,longitude:te(t.longitude)??0,address:ee(t.address),buildingName:ee(t.buildingName)}:null})(n,i);if(!o)return;const d=ee(a.from)??ee(r.from)??"",l=ee(a.to)??t.conversationId,c=re(a.sender),g={userId:ee(c?.userId)??d,nickname:ee(c?.nickname),avatarUrl:ee(c?.avatarUrl)},u=re(a.ext)??{},m=(e=>{const t=re(e);if(!t)return;const r=ee(t.operatorId)??ee(t.operator),a=te(t.operationCount)??te(t.count),s=te(t.operationTime)??te(t.edit_time);return r&&void 0!==a&&void 0!==s?{operatorId:r,operationCount:a,operationTime:s}:void 0})(a.modifiedInfo??re(a.meta)?.edit_msg);return{msgServerId:ee(r.id)??t.messageId,msgLocalId:ee(r.msgLocalId)??"",from:d,to:l,sender:g,conversationId:t.conversationId,conversationType:t.conversationType,type:n,sendStatus:"sent",ext:u,timestamp:te(r.timestamp)??t.timestamp,body:o,direct:d===t.currentUserId?"SEND":"RECEIVE",...m?{modifiedInfo:m}:{}}},se=e=>`${e.conversationType}:${e.conversationId}`,ie=e=>{const{orgName:t,appName:a}=r(e.appKey);return{orgName:t,appName:a,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},ne=async(e,t,r,a)=>{const s=ie(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw Q("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!b(e))throw Q(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:W(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:Z(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:W(t.conversationId,"params.conversationId"),conversationType:Z(t.conversationType,"params.conversationType")}]})(r),n=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw Q(t,`${t} must be an integer between 0 and 19`);return e})(r.mark,"params.mark"),o=await e.request(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channels/mark?resource=${s.encodedResource}`,{method:a?"POST":"DELETE",body:{mark:Y(n),targets:i.map(e=>({to:e.conversationId,type:J(e.conversationType)}))},operation:a?"addConversationMark":"removeConversationMark"}),d=(e=>{if(!Array.isArray(e))/* @__PURE__ */
2
- return new Set;const t=/* @__PURE__ */new Set;return e.forEach(e=>{if(!b(e))return;const r="string"==typeof e.to?e.to.trim():"",a=(e=>"chat"===e||"singleChat"===e?"singleChat":"groupchat"===e||"groupChat"===e?"groupChat":"chatroom"===e||"chatRoom"===e?"chatRoom":null)(e.type);r&&a&&t.add(se({conversationId:r,conversationType:a}))}),t})((b(o)&&b(o.data)?o.data:{}).ignore),l=[],c=[];for(const g of i){const e={conversationId:g.conversationId,conversationType:g.conversationType};d.has(se(g))?c.push({...e,reason:"ignored_by_server"}):l.push(e)}return{succeeded:l,failed:c,mark:n,operation:a?"addMark":"removeMark"}},oe=async(e,t,r,a)=>{const s=ie(t),i=W(r.conversationId,"params.conversationId"),n=Z(r.conversationType,"params.conversationType"),o=W(r.messageId,"params.messageId");return await e.request(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?resource=${s.encodedResource}`,{method:a?"POST":"DELETE",body:{to:i,type:J(n),pin_msg_id:o},operation:a?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:n,messageId:o,operation:a?"pin":"unpin"}},de=R.enum(["singleChat","groupChat","chatRoom"]),le=R.record(R.unknown()).refine(e=>(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e),"ext must be an object").refine(e=>(e=>{try{return JSON.stringify(e),!0}catch{return!1}})(e),"ext must be JSON serializable"),ce=R.object({path:R.string().min(1,"data.path is required"),size:R.number().optional(),name:R.string().optional(),type:R.string().optional()}),ge=R.object({uri:R.string().min(1,"data.uri is required"),size:R.number().optional(),name:R.string().optional(),type:R.string().optional()}),ue="undefined"!=typeof File?R.instanceof(File):R.never(),me=R.union([ue,ce,ge]),pe=R.object({conversationId:R.string().min(1,"conversationId is required"),conversationType:de,ext:le.optional(),timestamp:R.number().int().positive("timestamp must be a positive integer").optional(),receiverList:R.array(R.string().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:R.boolean().optional(),webhookEnv:R.string().optional(),priority:R.enum(["high","normal","low"]).optional(),needReadReceipt:R.boolean().optional(),isChatThread:R.boolean().optional()}),he=R.object({type:R.string().min(1,"messageList.type is required"),sender:R.object({userId:R.string().min(1,"messageList.sender.userId is required"),nickname:R.string().optional(),avatarUrl:R.string().optional()}),conversationId:R.string().min(1,"messageList.conversationId is required"),conversationType:de,timestamp:R.number().int().positive("messageList.timestamp must be positive"),body:R.record(R.unknown()),combineLevel:R.number().int().min(0).max(10).optional()}).passthrough(),ye=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:R.ZodIssueCode.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:R.ZodIssueCode.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:R.ZodIssueCode.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),ve=ye(pe.extend({content:R.string().min(1,"content is required"),targetLanguages:R.array(R.string().min(1)).optional()})),Ie=ye(pe.extend({originalUrl:R.string().min(1,"originalUrl is required").optional(),filename:R.string().min(1,"filename is required").optional(),filetype:R.string().min(1,"filetype is required").optional(),width:R.number().positive("width must be positive").optional(),height:R.number().positive("height must be positive").optional(),isGif:R.boolean().optional(),isOriginalImage:R.boolean().optional(),fileLength:R.number().positive("fileLength must be positive").optional(),data:me.optional(),thumbnailUrl:R.string().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),fe=ye(pe.extend({originalUrl:R.string().min(1,"originalUrl is required").optional(),filename:R.string().min(1,"filename is required").optional(),filetype:R.string().min(1,"filetype is required").optional(),fileSize:R.number().positive("fileSize must be positive").optional(),fileLength:R.number().positive("fileLength must be positive").optional(),data:me.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),be=ye(pe.extend({originalUrl:R.string().min(1,"originalUrl is required").optional(),filename:R.string().min(1,"filename is required").optional(),filetype:R.string().min(1,"filetype is required").optional(),duration:R.number().positive("duration must be positive"),fileLength:R.number().positive("fileLength must be positive").optional(),data:me.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),Te=ye(pe.extend({originalUrl:R.string().min(1,"originalUrl is required").optional(),filename:R.string().min(1,"filename is required").optional(),filetype:R.string().min(1,"filetype is required").optional(),duration:R.number().positive("duration must be positive"),width:R.number().positive("width must be positive").optional(),height:R.number().positive("height must be positive").optional(),fileLength:R.number().positive("fileLength must be positive").optional(),thumbnailUrl:R.string().min(1).optional(),data:me.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),_e=ye(pe.extend({latitude:R.number(),longitude:R.number(),address:R.string().min(1).optional(),buildingName:R.string().min(1).optional()})),Ce=ye(pe.extend({action:R.string().min(1,"action is required")})),Ee=ye(pe.extend({event:R.string().min(1,"event is required"),params:R.record(R.string()).optional()})),we=ye(pe.extend({title:R.string().min(1,"title is required"),summary:R.string().min(1,"summary is required"),compatibleText:R.string().min(1).optional(),messageList:R.array(he).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),Le=r=>{const a=r?.userId?.trim();if(!a)throw new e("sender.userId is required",{code:t.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:a,nickname:r?.nickname,avatarUrl:r?.avatarUrl}},Re=()=>V(),Oe=(r,a)=>{if(r)return r;if(!a)throw new e("url or data is required",{code:t.VALIDATION_REQUIRED,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const s=k(a);if(!s)throw new e("Failed to resolve local url",{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return s},Ne=e=>!!e.isGif||(e.isOriginalImage??!1),Me=(e,t,r,a,s)=>({msgServerId:"",msgLocalId:s??V(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:r,sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:a,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}),Ae=(e,t)=>{const r=K.validateOrThrow(we,e),a=r.messageList,s=Le(t);j(a);const i=H(a);X(i);const n={title:r.title,summary:r.summary,messageList:a,filename:"combine",filetype:"application/octet-stream",combineLevel:i},o=Me(r,s,"combine",n);return((e,t)=>{t&&S.set(e,t)})(o,r.compatibleText),o},Ue=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}`},Se=e=>{if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.charCodeAt(a);return r},xe=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),De=async e=>{try{return await e()}catch(r){if(!(r instanceof i))throw r;const e=(e=>{const r="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case t.SERVICE_NOT_ENABLED:case t.TRANSLATE_SERVICE_NOT_ENABLED:return"Translation service is not enabled";case t.TRANSLATE_PARAM_INVALID:return r?.includes("too long")?"Translation text is too long":r?.includes("target language")?"Invalid target language":"Invalid translation request";case t.TRANSLATE_USAGE_LIMIT:return"Translation quota has been reached";case t.TRANSLATE_FAILED:return"Translation service error";default:return}})(r);if(!e)throw r;throw new i(`REST business error: ${e}`,{code:r.code,details:r.details})}},$e=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",ke=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},Ve=e=>({userId:e}),Pe=(e,t)=>{if(!xe(e)||!xe(e.data))throw s({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},qe=(e,t)=>{if(!xe(e)||!Array.isArray(e.data))throw s({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},Fe=(e,t)=>Array.isArray(e)?e:qe(e,t),Be={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},Ge={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},ze={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},je=(e,t,a)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:i}=r(e.appKey),o=t.indexOf("/chatfiles/"),d=o>=0?t.slice(o):t,l=`${e.restBaseUrl}/${s}/${i}${d}`;return n(l,a)},He=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e))return e;const t=Object.values(e),r=[];for(const a of t)Array.isArray(a)&&r.push(...a);return r.length>0?r:void 0},Xe=(e,t,r)=>{const a=$e(r.contentType??r.type),s=Ge[a];if(!s)return null;const i=xe(r.content)?r.content:{},n=((e,t)=>{const r=$e(t.conversationType);if("groupchat"===r||"chatroom"===r)return $e(t.receiverId);const a=$e(t.senderId);return a===e?$e(t.receiverId):a})(t,r),o=ze[$e(r.conversationType)]??"singleChat",d={msgServerId:$e(r.messageId),msgLocalId:$e(r.messageId),from:$e(r.senderId),to:$e(r.receiverId),conversationId:n,conversationType:o,type:s,ext:xe(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date($e(r.sentTime)).getTime(),sender:{userId:$e(r.senderId)},highlight:He(r.highlight),text:"string"==typeof r.text?r.text:void 0};let l;const c=$e(i.remotePath??i.url),g=$e(i.secret??i.secretKey);switch(s){case"txt":l={type:"txt",content:$e(i.message??r.text)};break;case"img":{const t=je(e,c,g);l={type:"img",url:t,thumb:i.thumb?je(e,$e(i.thumb),$e(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:g,width:Number(i.width??(xe(i.size)?i.size.width:0))||0,height:Number(i.height??(xe(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":l={type:"video",url:je(e,c,g),thumb:i.thumb||i.thumbnailRemotePath?je(e,$e(i.thumb??i.thumbnailRemotePath),$e(i.thumb_secret??i.thumbnailSecretKey)):"",secret:g,filename:$e(i.filename??i.displayName),duration:Number(i.length??i.duration??0),fileLength:Number(i.file_length??i.fileLength??0)};break;case"file":l={type:"file",url:je(e,c,g),secret:g,filename:$e(i.filename??i.displayName),fileLength:Number(i.file_length??i.fileLength??0)};break;case"loc":l={type:"loc",latitude:Number(i.lat??i.latitude??0),longitude:Number(i.lng??i.longitude??0),address:$e(i.addr??i.address),buildingName:$e(i.buildingName)};break;case"custom":l={type:"custom",customEvent:$e(i.customEvent),customExts:xe(i.customExts)?i.customExts:{}};break;default:return null}return{...d,body:l}},Ke=async(e,t,r)=>{const a=`${Ue(t)}/users/${t.userId}/messages/search/get`,s=((e,t)=>{const{option:r,pageNum:a=1,pageSize:s=20}=e,i=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),n={searchMode:"default",highlightEnable:!0,page:a,size:s};return 1===i.length?n.keyword=i[0]:(n.keywords=i,n.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?n.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?n.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(n.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(n.contentType=r.msgTypes.map(e=>Be[e]??e).join(",")),void 0!==r.startTime&&(n.startTime=r.startTime),void 0!==r.endTime&&(n.endTime=r.endTime),r.searchScope&&(n.searchExt=r.searchScope),r.direction&&(n.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:n}})(r,t.userId),i=await e.post(a,s,{operation:"searchMessages"}),n=xe(i)?i:{},o=xe(n.data)?n.data:n,d=xe(o.data)?o.data:o,l=Array.isArray(d.items)?d.items:Array.isArray(d.list)?d.list:[],c=xe(d.pagination)?d.pagination:d,g=Number(c.pageNum??c.page??r.pageNum??1),u=Number(c.pageSize??c.size??r.pageSize??20),m=Number(c.totalPages??0),p=1===c.isFinished||g>=m,h=[];for(const y of l){if(!xe(y))continue;const e=Xe(t,t.userId,y);e&&h.push(e)}return{messages:h,pageNum:g,pageSize:u,totalPages:m,isLast:p}},Qe=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/api/sdk/v1/${t}/${a}`},We=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ye=e=>We(e)&&"string"==typeof e.path&&e.path.trim().length>0,Ze=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||Ye(e),Je=e=>{if(!We(e))return;return{data:We(e.data)?e.data:void 0,error:We(e.error)?e.error:void 0}},et=(e,r)=>{const a=Je(e),s=a?.data?.text;if("string"!=typeof s)throw new c(`${r} response data is invalid`,t.REST_BUSINESS_UNKNOWN,{details:{api:r,response:e}});return s},rt=(t,r,a,s="sdk")=>"auth"===s?new g(t,{code:r,details:a}):"validation"===s?new e(t,{code:r,details:a}):new c(t,r,{details:a}),at=e=>!(void 0===e||We(e)&&!Array.isArray(e))||(void 0!==e?.format&&"string"!=typeof e.format||(void 0!==e?.sampleRate&&"number"!=typeof e.sampleRate||(void 0!==e?.bitsPerSample&&"number"!=typeof e.bitsPerSample||void 0!==e?.channels&&"number"!=typeof e.channels))),st=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},it=e=>{const{serviceCode:r,serviceMessage:a}=(e=>{const t=e instanceof c&&We(e.details)?e.details:void 0,r=Je(t?.rawResponse??t?.response??e),a=t?.serverCode??r?.error?.code,s=t?.serverMessage??r?.error?.message;return{serviceCode:"string"==typeof a||"number"==typeof a?String(a):void 0,serviceMessage:"string"==typeof s?s:void 0}})(e);if(e instanceof u)return rt("File upload failed",t.UPLOAD_REQUEST_FAILED,{cause:e.details});if(e instanceof c&&!r)return e;if(r)switch(r){case"4041001":return rt("File not found",t.VOICE_TO_TEXT_FILE_NOT_FOUND,{serviceCode:r,serviceMessage:a});case"4001002":return rt("Invalid file",t.VOICE_TO_TEXT_FILE_INVALID,{serviceCode:r,serviceMessage:a},"validation");case"5021001":return rt("File upload failed",t.UPLOAD_REQUEST_FAILED,{serviceCode:r,serviceMessage:a});case"4001003":return rt("Voice duration exceeds 60 seconds",t.VOICE_TO_TEXT_FILE_DURATION_TOO_LONG,{serviceCode:r,serviceMessage:a},"validation");case"4031001":return rt("Voice-to-text service is not enabled",t.SERVICE_NOT_ENABLED,{serviceCode:r,serviceMessage:a});case"4031002":return rt("Beta service usage limit exceeded",t.SERVICE_LIMIT_EXCEEDED,{serviceCode:r,serviceMessage:a});case"4001001":return"string"==typeof(s=a)&&s.toLowerCase().includes("uploaded file exceeds")?rt("File too large",t.VOICE_TO_TEXT_FILE_TOO_LARGE,{serviceCode:r,serviceMessage:a}):rt(a||"Missing or invalid request parameter",t.VALIDATION_REQUIRED,{serviceCode:r,serviceMessage:a},"validation");case"5021003":case"5001003":return rt("Voice-to-text failed",t.VOICE_TO_TEXT_FAILED,{serviceCode:r,serviceMessage:a});case"4011001":return rt(a||"Unauthorized or invalid token",t.AUTH_UNAUTHORIZED,{serviceCode:r,serviceMessage:a},"auth");default:return rt(a||(e instanceof Error?e.message:"Voice-to-text failed"),t.VOICE_TO_TEXT_FAILED,{serviceCode:r,serviceMessage:a})}var s;return e instanceof c?rt(e.message,e.code,e.details):rt(e instanceof Error?e.message:"Voice-to-text failed",t.VOICE_TO_TEXT_FAILED)},nt=(e,r)=>{if(!We(a=e)||"string"!=typeof a.filename||"string"!=typeof a.filetype||"number"!=typeof a.duration||"type"in a&&void 0!==a.type&&"voice"!==a.type)throw rt("Invalid file",t.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody"},"validation");var a;if(at(r))throw rt("Invalid file",t.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!e.url)throw rt("File not found",t.VOICE_TO_TEXT_FILE_NOT_FOUND,{path:"voiceMessageBody.url"});if(!st(e.url))throw rt("Invalid file",t.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody.url"},"validation");return e},ot=(e,r)=>{if(at(r))throw rt("Invalid file",t.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!Ze(e))throw rt("Invalid file",t.VOICE_TO_TEXT_FILE_INVALID,{path:"file"},"validation");return e},dt=async(r,a,s,i)=>{const n=nt(s,i),o=st(n.url);if(!o)throw((t,r,a,s="invalid")=>new e(t,{code:r,details:{fields:[{path:a,message:t,rule:s}]}}))("File not found",t.VOICE_TO_TEXT_FILE_NOT_FOUND,"voiceMessageBody.url");try{const e=await r.post(`${Qe(a)}/speech/transcriptions`,{data:{fileId:o,username:a.userId,...i?{audio:i}:{}}},{operation:"voiceMessageToText"});return{text:et(e,"voiceMessageToText")}}catch(d){throw it(d)}},lt=R.object({keywordList:R.array(R.string()).min(1,"keywordList must not be empty").max(5,"keywordList must have at most 5 keywords").refine(e=>e.map(e=>e.trim()).filter(e=>e.length>0).length>0,"keywordList must contain at least one non-empty keyword"),keywordListMatchType:R.enum(["or","and"]).optional(),conversationId:R.string().min(1).optional(),conversationType:R.enum(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:R.array(R.enum(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:R.number().optional(),endTime:R.number().optional(),searchScope:R.enum(["none","with","only"]).optional(),direction:R.enum(["up","down"]).optional()}).refine(e=>void 0!==e.conversationId===(void 0!==e.conversationType),{message:"conversationId and conversationType must be provided together"}).refine(e=>void 0!==e.startTime===(void 0!==e.endTime),{message:"startTime and endTime must be provided together"}).refine(e=>void 0===e.startTime||void 0===e.endTime||e.endTime>=e.startTime,{message:"endTime must be >= startTime"}),ct=R.object({option:lt,pageNum:R.number().int().min(1).default(1),pageSize:R.number().int().min(1).max(100).default(20)}),gt=I(f,{common:{},apis:{sendMessage:{range:"1,4,100,108,110,202,210,213-215,219-222,300-301,303,305,402,405-406,500-501,505-510,602-603,606-607,1200,1299",localErrors:{sendMessage:{operation_cancelled:{code:1,retryable:!1},upload_invalid_appkey:{code:100,retryable:!1},validation_invalid:{code:110,retryable:!1},not_connected:{code:300,retryable:!0},request_timeout:{code:301,retryable:!0},send_failed:{code:303,retryable:!1},upload_failed:{code:402,retryable:!0},file_too_large:{code:405,retryable:!1},file_content_improper:{code:406,retryable:!1},encode_failed:{code:500,retryable:!1}}},errors:{SERVICE_LIMIT_EXCEEDED:{code:4,retryable:!1},TOKEN_EXPIRED:{code:108,retryable:!1},AUTH_FAILED:{code:202,retryable:!1},PERMISSION_DENIED:{code:210,retryable:!1},BIND_ANOTHER_DEVICE:{code:213,retryable:!1},TOO_MANY_DEVICES:{code:214,retryable:!1},USER_MUTED:{code:215,retryable:!1},USER_MUTED_BY_ADMIN:{code:219,retryable:!1},USER_DEVICE_CHANGED:{code:220,retryable:!1},USER_NOT_ON_ROSTER:{code:221,retryable:!1},BLOCKED_BY_RECIPIENT:{code:222,retryable:!1,aliases:["blocked"]},SERVER_SERVING_DISABLED:{code:305,retryable:!1},MESSAGE_INCLUDE_ILLEGAL_CONTENT:{code:501,retryable:!1},SERVICE_NOT_ENABLED:{code:505,retryable:!1},MESSAGE_EXPIRED:{code:506,retryable:!1},MESSAGE_ILLEGAL_WHITELIST:{code:507,retryable:!1},MESSAGE_EXTERNAL_LOGIC_BLOCKED:{code:508,retryable:!1},MESSAGE_CURRENT_LIMITING:{code:509,retryable:!0},MESSAGE_SIZE_LIMIT:{code:510,retryable:!1},GROUP_NOT_JOINED:{code:602,retryable:!1},GROUP_PERMISSION_DENIED:{code:603,retryable:!1},GROUP_NOT_EXIST:{code:606,retryable:!1},GROUP_DISABLED:{code:607,retryable:!1},MESSAGE_BLOCKED:{code:1200,retryable:!1},THIRD_DEFAULT_FAILED:{code:1299,retryable:!1}}},getHistoryMessages:{range:"4,110,202,505",localErrors:{getHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},page_size_exceeded:{code:110,aliases:["pull number cannot be greater","limit is to large"],retryable:!1}}},removeHistoryMessages:{range:"110,112,202,505",localErrors:{removeHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},query_param_reaches_limit:{code:112,aliases:["delete msg list limit"],retryable:!1}}},getGroupMessageReadUsers:{range:"4,110,500",localErrors:{getGroupMessageReadUsers:{validation_invalid:{code:110,retryable:!1}}},errors:{message_not_found:{code:500,retryable:!1}}},recallMessage:{range:"110,201,300,504,505",localErrors:{recallMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},recall_time_limit:{code:504,retryable:!1},recall_disabled:{code:505,retryable:!1}}},updateMessage:{range:"110,111,201,210,300,511",localErrors:{modifyMessage:{validation_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1},not_login:{code:201,retryable:!0},permission_denied:{code:210,retryable:!1},not_connected:{code:300,retryable:!0},edit_failed:{code:511,retryable:!0}}},downloadMessageAttachment:{range:"400,401,403,407",localErrors:{downloadAttachment:{validation_invalid:{code:401,retryable:!1}}},errors:{not_found:{code:400,httpStatus:404,retryable:!1},invalid:{code:401,retryable:!1},download_failed:{code:403,retryable:!0},expired:{code:407,httpStatus:404,retryable:!1}}},downloadAndParseCombineMessage:{range:"110,401,403,500",localErrors:{downloadAndParseCombineMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_param:{code:110,retryable:!1},invalid_type:{code:500,retryable:!1},parse_failed:{code:401,retryable:!0},download_failed:{code:403,retryable:!0}}},addReaction:{range:"110,302,505,600,602,1300-1302",localErrors:{addReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{reaction_already_operated:{code:1301,retryable:!1},reaction_reach_limit:{code:1300,retryable:!1},group_not_joined:{code:602,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1},service_not_enabled:{code:505,retryable:!1},server_busy:{code:302,retryable:!0}}},removeReaction:{range:"110,505,1301,1302",localErrors:{removeReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},getReactionList:{range:"110,505,600",localErrors:{getReactionList:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},group_invalid_id:{code:600,retryable:!1}}},getReactionDetail:{range:"110,505,1302",localErrors:{getReactionDetail:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},pinMessage:{range:"4,110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_limit:{code:4,aliases:["91101"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102"],retryable:!1}}},unpinMessage:{range:"110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getPinnedMessageList:{range:"110,111",errors:{operation_unsupported:{code:111,aliases:["15002"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getSupportedTranslationLanguages:{range:"505",errors:{service_not_enabled:{code:505,aliases:["service not open!"],retryable:!1}}},translateMessage:{range:"505,1110-1113",localErrors:{translateMessage:{validation_invalid:{code:1110,retryable:!1}}},errors:{translate_text_too_long:{code:1110,runtimeMessage:"Translation text is too long",retryable:!1},translate_param_invalid:{code:1110,runtimeMessage:"Invalid target language",retryable:!1},service_not_enabled:{code:1111,runtimeMessage:"Translation service is not enabled",aliases:["service not open!"],retryable:!1},translate_usage_limit:{code:1112,runtimeMessage:"Translation quota has been reached",aliases:["The request has reached the maximum limit"],retryable:!1},translate_failed:{code:1113,runtimeMessage:"Translation service error",aliases:["The request failed, please try again later."],retryable:!1}}},voiceMessageToText:{range:"4,110,202,407-411,505",localErrors:{voiceMessageToText:{validation_invalid:{code:407,retryable:!1},file_not_found:{code:410,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},file_not_found:{code:410,retryable:!1,aliases:["4041001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},voiceFileToText:{range:"4,110,202,402,407-411,505",localErrors:{voiceFileToText:{validation_invalid:{code:407,retryable:!1},upload_required:{code:110,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},upload_failed:{code:402,retryable:!0,aliases:["5021001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},getConversationList:{range:"110",localErrors:{getConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPinnedConversationList:{range:"110",localErrors:{getPinnedConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getConversationListByMark:{range:"110",localErrors:{getConversationListByMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},deleteConversation:{range:"110",localErrors:{deleteConversation:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearConversationUnreadMessageCount:{range:"110,201,300,500",localErrors:{clearConversationUnreadMessageCount:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},clearAllConversationUnreadMessageCount:{range:"201,300,500",errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},sendMessageReadReceipts:{range:"110,300",localErrors:{sendMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_direction:{code:110,retryable:!1},not_connected:{code:300,retryable:!0}}},getGroupMessageReadReceipts:{range:"110,202,210,303",localErrors:{getGroupMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},auth_bad_access_token:{code:202,httpStatus:401,retryable:!1},forbidden_op:{code:210,httpStatus:403,retryable:!1},unknown_exception_error:{code:303,httpStatus:500,retryable:!0}}},setConversationPinned:{range:"110",localErrors:{setConversationPinned:{validation_invalid:{code:110,retryable:!1}}},errors:{}},addConversationMark:{range:"110",localErrors:{addConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},removeConversationMark:{range:"110",localErrors:{removeConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearAllMessagesAndConversations:{range:"",errors:{}},searchMessages:{range:"110,202,303,505",localErrors:{searchMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{parameter_error:{code:110,httpStatus:400,retryable:!1,aliases:["4000005","4000006"]},token_invalid:{code:202,httpStatus:401,retryable:!1,aliases:["4010101"]},service_not_enabled:{code:505,httpStatus:403,retryable:!1,aliases:["4030204"]},app_not_found:{code:110,httpStatus:404,retryable:!1,aliases:["4040302"]},server_error:{code:303,httpStatus:500,retryable:!0,aliases:["5000701","5020801"]}}}}}),ut=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}async sendMessage(e,t){return this.getClientOrThrow().sendMessage(e,t)}createTextMessage(e){return((e,t)=>{const r=K.validateOrThrow(ve,e),a=Le(t),s=Re(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),Me(r,a,"text",i,s)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=K.validateOrThrow(Ie,e),i=Le(t),n=Re(),o=s.data?Oe(void 0,s.data):"",d=s.originalUrl?a(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&$.set(n,s.data);const l=s.isGif??!1,c={localUrl:o,filename:s.filename,filetype:s.filetype,width:s.width,height:s.height,isGif:l,isOriginalImage:Ne({isGif:l,isOriginalImage:s.isOriginalImage})};return d?.originalImageUrl&&(c.originalImageUrl=d.originalImageUrl,c.bigImageUrl=d.bigImageUrl,c.thumbnailUrl=d.thumbnailUrl),void 0!==s.fileLength&&(c.fileLength=s.fileLength),s.thumbnailUrl&&(c.thumbnailUrl=s.thumbnailUrl),Me(s,i,"image",c,n)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=K.validateOrThrow(fe,e),a=Le(t),s=Re(),i=Oe(r.originalUrl,r.data);r.data&&$.set(s,r.data);const n={url:i,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(n.fileSize=r.fileSize),void 0!==r.fileLength&&(n.fileLength=r.fileLength),Me(r,a,"file",n,s)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=K.validateOrThrow(be,e),a=Le(t),s=Re(),i=Oe(r.originalUrl,r.data);r.data&&$.set(s,r.data);const n={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(n.fileLength=r.fileLength),Me(r,a,"voice",n,s)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=K.validateOrThrow(Te,e),a=Le(t),s=Re(),i=Oe(r.originalUrl,r.data);r.data&&$.set(s,r.data);const n={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(n.width=r.width),void 0!==r.height&&(n.height=r.height),void 0!==r.fileLength&&(n.fileLength=r.fileLength),r.thumbnailUrl&&(n.thumbnailUrl=r.thumbnailUrl),Me(r,a,"video",n,s)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=K.validateOrThrow(_e,e),a=Le(t),s={latitude:r.latitude,longitude:r.longitude};return r.address&&(s.address=r.address),r.buildingName&&(s.buildingName=r.buildingName),Me(r,a,"location",s)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=K.validateOrThrow(Ce,e),a=Le(t),s={action:r.action};return void 0!==r.deliverOnlineOnly&&(s.deliverOnlineOnly=r.deliverOnlineOnly),Me(r,a,"cmd",s)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=K.validateOrThrow(Ee,e),a=Le(t),s={event:r.event};return r.params&&(s.params=r.params),Me(r,a,"custom",s)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return Ae(e,this.buildMessageSenderOrThrow())}getConversationList(r){if(void 0!==r?.mark&&(!Number.isInteger(r.mark)||r.mark<0||r.mark>19))throw new e("filter.mark must be an integer between 0 and 19",{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const a=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(e=>null!==e.lastMessage&&((void 0===r?.isPinned||e.isPinned===r.isPinned)&&!(void 0!==r?.mark&&!_(e,r.mark)))).map(C);return this.getClientOrThrow().markConversationAccess(a.map(e=>({conversationId:e.conversationId,type:e.conversationType}))),a}setCurrentConversation(e){this.validateConversationLocator(e),this.getClientOrThrow().getCacheManager()?.setCurrentConversation({conversationId:e.conversationId,type:e.conversationType})}resetCurrentConversation(){this.getClientOrThrow().getCacheManager()?.resetCurrentConversation()}getCurrentConversation(){const e=this.getClientOrThrow().getCacheManager()?.getCurrentConversation()??null;return e?{conversationId:e.conversationId,conversationType:e.type}:null}refreshSessionList(e){return this.getClientOrThrow().refreshSessionList(e)}async deleteConversation(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const a=ie(t),s=W(r.conversationId,"params.conversationId"),i=Z(r.conversationType,"params.conversationType"),n=r.deleteRoamingMessages??!1;if("boolean"!=typeof n)throw Q("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${a.orgName}/${a.appName}/user/${a.encodedUserId}/user_channel?resource=${a.encodedResource}`,{method:"DELETE",body:{channel:s,type:"groupChat"===i?"groupChat":J(i),delete_roam:n},operation:"deleteConversation"}),{conversationId:s,conversationType:i,operation:"delete"}})(this.getRestClient(t),t,e),a=this.getClientOrThrow(),s=a.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return s?.changed&&a.emitConversationListUpdate("local"),r}async setConversationPinned(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const a=ie(t),s=W(r.conversationId,"params.conversationId"),i=Z(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw Q("params.pinned","params.pinned must be a boolean");const n="groupChat"===i?"groupChat":J(i),o=r.pinned?await e.post(`/${a.orgName}/${a.appName}/sdk/user/${a.encodedUserId}/user_channel/top?resource=${a.encodedResource}`,{type:n,to:s},{operation:"setConversationPinned"}):await e.delete(`/${a.orgName}/${a.appName}/sdk/user/${a.encodedUserId}/user_channel/top?type=${encodeURIComponent(n)}&to=${encodeURIComponent(s)}&resource=${a.encodedResource}`,{operation:"setConversationPinned"}),d=b(o)&&b(o.data)?o.data:{};return{conversationId:s,conversationType:i,operation:"setPinned",isPinned:"boolean"==typeof d.is_top?d.is_top:r.pinned,pinnedTime:"number"==typeof d.update_top_status_time?d.update_top_status_time:r.pinned?Date.now():0}})(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),s=a?.applyConversationPinnedMutation({conversationId:r.conversationId,type:r.conversationType,isPinned:r.isPinned??e.pinned,pinnedTime:r.pinnedTime});return s?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>ne(e,t,r,!0))(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),s=a?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return s?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async removeConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>ne(e,t,r,!1))(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),s=a?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return s?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async clearAllMessagesAndConversations(){const e=this.getRestContextOrThrow();await(async(e,t)=>{const r=ie(t);await e.post(`/${r.orgName}/${r.appName}/sdk/message/roaming/user/${r.encodedUserId}/delete/all?resource=${r.encodedResource}`,void 0,{operation:"clearAllMessagesAndConversations"})})(this.getRestClient(e),e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversations();r?.changed&&t.emitConversationListUpdate("local")}async pinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>oe(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>oe(e,t,r,!1))(this.getRestClient(t),t,e))}async getPinnedMessageList(e){const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=ie(t),s=W(r.conversationId,"params.conversationId"),i=Z(r.conversationType,"params.conversationType"),n=await e.get(`/${a.orgName}/${a.appName}/sdk/user/${a.encodedUserId}/user_channel/pin?to=${encodeURIComponent(s)}&type=${encodeURIComponent(J(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),o=b(n)&&b(n.data)?n.data:{};return{items:(Array.isArray(o.msg_infos)?o.msg_infos:[]).reduce((e,r)=>{if(!b(r))return e;const a="string"==typeof r.pin_msg_id?r.pin_msg_id:b(r.message)&&"string"==typeof r.message.id?r.message.id:"";if(!a)return e;const n="number"==typeof r.pin_opt_at?r.pin_opt_at:0,o=ae(r.message,{messageId:a,conversationId:s,conversationType:i,currentUserId:t.userId,timestamp:n});return o?(e.push({messageId:a,conversationId:s,conversationType:i,operatorId:"string"==typeof r.pin_operator?r.pin_operator:void 0,pinnedAt:n,message:o}),e):e},[])}})(this.getRestClient(t),t,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(e){this.validateUnreadConversationLocator(e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:e.conversationId,type:e.conversationType});r?.changed&&t.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(a){if(!r?.matched)throw a;m.warn("Conversation unread remote sync failed after local clear",{conversationId:e.conversationId,conversationType:e.conversationType,error:a})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(r){if(this.validateConversationLocator(r),this.requireNonEmptyString(r.messageId,"messageId"),"text"!==r.message.type&&"custom"!==r.message.type)throw new e("only text and custom messages are editable",{code:t.OPERATION_UNSUPPORTED});await this.requireConnectedClient().sendMessageAction({kind:"update",conversationId:r.conversationId,conversationType:r.conversationType,messageId:r.messageId,body:r.message.body,messageType:r.message.type,ext:r.message.ext},(e,t)=>this.buildActionError(e,t));const a=Date.now(),s=this.getCurrentUserIdOrThrow(),i={operatorId:s,operationCount:1,operationTime:a};return{msgServerId:r.messageId,msgLocalId:"",from:s,to:r.conversationId,sender:{userId:s},conversationId:r.conversationId,conversationType:r.conversationType,type:r.message.type,sendStatus:"sent",ext:r.message.ext,timestamp:a,body:r.message.body,direct:"SEND",modifiedInfo:i}}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,a)=>{const s=`${Ue(t)}/users/${t.userId}/messageroaming`,i=await e.post(s,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),n=Pe(i,"getHistoryMessages"),o=Array.isArray(n.msgs)?n.msgs:[],d=[];for(const l of o){if(!xe(l)||"string"!=typeof l.msg||0===l.msg.length)continue;const e=a(Se(l.msg));e&&d.push(e)}return{items:d,cursor:ke(n.next_key),hasMore:!0!==n.is_last&&d.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=K.validateOrThrow(ct,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>Ke(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const a="singleChat"===r.conversationType?"userId":"groupId",s="singleChat"===r.conversationType?"chat":"group",i=encodeURIComponent(t.clientResource),n=r.messageIds?`${Ue(t)}/sdk/message/roaming/${s}/user/${t.userId}?${a}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${Ue(t)}/sdk/message/roaming/${s}/user/${t.userId}/time?${a}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${i}`;await e.delete(n,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const a=new URLSearchParams;a.set("limit",String(r.pageSize??10)),r.cursor&&a.set("key",r.cursor);const s=`${Ue(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${a.toString()}`,i=await e.get(s,{operation:"getGroupMessageReadUsers"}),n=Pe(i,"getGroupMessageReadUsers"),o=xe(n.group_ack)?n.group_ack:n,d=(Array.isArray(o.userlist)?o.userlist:[]).map(e=>xe(e)&&"string"==typeof e.username?{userId:e.username,user:Ve(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof n.ackmid?n.ackmid:r.messageId,users:d,count:"number"==typeof o.total?o.total:d.length,cursor:ke(o.next_key),hasMore:!0!==o.is_last&&d.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=`${Ue(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,s=await e.post(a,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return qe(s,"getGroupMessageReadReceipts").map(e=>xe(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${Ue(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const a=`${Ue(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(a,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=new URLSearchParams,s="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");a.set("msgIdList",s),a.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&a.set("groupId",r.groupId);const i=await e.get(`${Ue(t)}/reaction/user/${t.userId}?${a.toString()}`,{operation:"getReactionList"});return qe(i,"getReactionList").map(e=>{if(!xe(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>xe(e)&&"string"==typeof e.reaction?{reaction:e.reaction,count:"number"==typeof e.count?e.count:0,isAddedBySelf:!0===e.state,userIds:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[]}:null).filter(e=>null!==e)}}).filter(e=>null!==e)})(this.getRestClient(t),t,e))}async getReactionDetail(e){if(this.validateReactionParams(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=new URLSearchParams;a.set("msgId",r.messageId),a.set("message",r.reaction),a.set("cursor",r.cursor??""),a.set("limit",String(r.pageSize??20));const s=await e.get(`${Ue(t)}/reaction/user/${t.userId}/detail?${a.toString()}`,{operation:"getReactionDetail"}),i=Pe(s,"getReactionDetail"),n=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>xe(e)&&"string"==typeof e.userId?{userId:e.userId,user:Ve(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],o=Array.isArray(i.userList)?i.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:Ve(e)})):[],d=n.length>0?n:o;return{reaction:"string"==typeof i.reaction?i.reaction:r.reaction,count:"number"==typeof i.count?i.count:d.length,isAddedBySelf:!0===i.state,reactionUsers:d,cursor:ke(i.cursor),hasMore:ke(i.cursor).length>0,createdAt:"string"==typeof i.createdAt?i.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await De(()=>e.get(`${Ue(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return Fe(r,"getSupportedTranslationLanguages").map(e=>xe(e)&&"string"==typeof e.code?{code:e.code,name:"string"==typeof e.name?e.name:e.code,nativeName:"string"==typeof e.nativeName?e.nativeName:e.code}:null).filter(e=>null!==e)})(this.getRestClient(e),e))}async translateMessage(r){if("text"!==r.message.type)throw new e("only text messages can be translated",{code:t.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.type",message:"must be text",rule:"message_type"}]}});const a=r.message.body.content.trim();if(0===a.length)throw new e("message text is required",{code:t.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(r.targetLanguages)||0===r.targetLanguages.length)throw new e("targetLanguages is required",{code:t.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(r.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new e("targetLanguages contains invalid language code",{code:t.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"contains invalid language code",rule:"language_code"}]}});const i=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=await De(()=>e.post(`${Ue(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),i=Fe(a,"translateMessage"),n=xe(i[0])?i[0]:null;if(!n)throw s({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(n.translations)?n.translations:[],d=xe(n.detectedLanguage)?n.detectedLanguage:void 0;return{detectedLanguage:d&&"string"==typeof d.language?{language:d.language,score:"number"==typeof d.score?d.score:Number(d.score??0)}:void 0,translations:o.map(e=>xe(e)&&"string"==typeof e.text&&"string"==typeof e.to?{text:e.text,to:e.to}:null).filter(e=>null!==e)}})(this.getRestClient(i),i,{text:a,targetLanguages:r.targetLanguages}))}async voiceMessageToText(e,t){nt(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>dt(this.getRestClient(r),r,e,t))}async voiceFileToText(e,r){ot(e,r);const a=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new c("Upload capability is missing for current platform",t.UPLOAD_REQUIRED_FIELD_MISSING);return this.executeRestOperation(()=>(async(e,r,a,s)=>{const i=ot(a,s),n=o({file:i,fallbackName:Ye(i)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const a=await e.upload({url:`${r.restBaseUrl}${Qe(r)}/speech/recognitions`,headers:{Authorization:`Bearer ${r.token}`,Accept:"application/json",[d]:l()},source:n.source,fields:{username:r.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let i=a.body;try{i=JSON.parse(a.body)}catch{i=a.body}if(a.status<200||a.status>=300)throw new c("Voice-to-text failed",t.VOICE_TO_TEXT_FAILED,{details:{httpStatus:a.status,rawResponse:i}});return{text:et(i,"voiceFileToText")}}catch(g){if(g instanceof c)throw it(g);throw it(E(g))}})(s,a,e,r))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(r){if("message"in r){if("combine"!==r.message.type)throw new e("message must be a combine message",{code:t.VALIDATION_INVALID_FORMAT});const a=r.message.body;return{url:a.url??"",secret:a.secret,timeoutMs:r.timeoutMs,maxItems:r.maxItems}}return{url:r.url,secret:r.secret,timeoutMs:r.timeoutMs,maxItems:r.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(r,a){return r===t.AUTH_NOT_LOGIN||r===t.AUTH_UNAUTHORIZED?new g(a??"authentication failed",{code:r}):r===t.CONNECTION_WEBSOCKET_ERROR||r===t.CONNECTION_TIMEOUT?new p(a??"connection unavailable",{code:r}):107===r||110===r||205===r||500===r||r===t.VALIDATION_REQUIRED||r===t.VALIDATION_INVALID_FORMAT?new e(a??"invalid parameter",{code:r}):r===t.MESSAGE_RECALL_TIME_LIMIT?new c(a??"message recall time limit reached",r):r===t.MESSAGE_EDIT_FAILED?new c(a??"message update failed",r):r===t.OPERATION_UNSUPPORTED?new e(a??"operation unsupported",{code:r}):new c(a??"message action failed",r)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(r,a){return new e(r,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:a,message:r,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new e("ChatManager is not bound to event context",{code:t.VALIDATION_REQUIRED});return this.eventContext}getClientOrThrow(){if(!this.client)throw new e("ChatManager is not bound to client",{code:t.VALIDATION_REQUIRED});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new h(e.restBaseUrl,{errorMap:gt,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireConnectedClient(){const e=this.getClientOrThrow();if(e.getConnectionState()!==O.CONNECTED)throw new p("client is not connected",{code:t.CONNECTION_WEBSOCKET_ERROR});return e}getCurrentUserIdOrThrow(){const e=this.getClientOrThrow().getCurrentUserId();if(!e)throw new g("user is not logged in",{code:t.AUTH_NOT_LOGIN});return e}buildMessageSenderOrThrow(){const e=this.getClientOrThrow(),t=this.getCurrentUserIdOrThrow(),r=e.getCacheManager()?.getUserInfoSummaries([t],!1)[0];return{userId:t,nickname:r?.nickname,avatarUrl:r?.avatarUrl}}async hydrateGroupMessageReadUsers(e,t){const r=this.getClientOrThrow();if(!r.isUserInfoSyncEnabled()||0===t.users.length)return t;const a=r.getCacheManager(),s=await w({groupId:e,users:t.users.map(e=>e.user),includeNameCard:!0,cacheManager:a,fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoReadCapability(r);return t?await t.getUserInfoByUserId({userIds:e}):[]},hydrateGroupNamecards:async(e,t)=>{const a=this.getGroupNamecardHydrationCapability(r);a&&await a.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))}});return this.dispatchFetchedUserInfoUpdates(r,s.fetchedUserInfos),{...t,users:t.users.map(e=>{const t=s.usersById.get(e.userId)??e.user;return{...e,user:t}})}}getUserInfoReadCapability(e){const t=e.getManagerByCapability("userInfo:read");return t&&"function"==typeof t.getUserInfoByUserId?t:null}getGroupNamecardHydrationCapability(e){const t=e.getManagerByCapability("group:namecard");return t&&"function"==typeof t.hydrateMessageProfileGroupNamecards?t:null}dispatchFetchedUserInfoUpdates(e,t){if(0===t.length)return;const r=e.getCurrentUserId(),a=t.find(e=>e.userId===r),s=t.filter(e=>e.userId!==r);a&&e.dispatchOwnInfoUpdated(a),e.dispatchUserInfoUpdated(s),t.length>0&&e.refreshConversationDisplayFromUserInfos(t.map(e=>({userId:e.userId})),"profile")}async executeRestOperation(e){try{return await e()}catch(t){throw this.mapRestError(t)}}mapRestError(r){return r instanceof e||r instanceof g||r instanceof p||r instanceof y?r:r instanceof v?new y(r.message,{code:r.code,details:r.details}):r instanceof i||r instanceof c?r:new c(String(r),t.UNKNOWN)}};ut.key="chatManager";let mt=ut;export{mt as C,M as I,P as M,K as V,O as a,N as b,x as c,A as d,H as e,X as f,U as g,k as h,$ as i,D as j,z as k,V as l,j as v};