easemob-websdk 5.0.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-manager.d.ts +3 -0
- package/cache/cache-store.d.ts +6 -4
- package/cache/cache-utils.d.ts +1 -1
- package/chat-client.d.ts +25 -12
- package/chunks/cache-utils-B99glc0H.js +1 -0
- package/chunks/cache-utils-gowrxNr8.cjs +1 -0
- package/chunks/chat-manager-DCqgMxLm.js +2 -0
- package/chunks/chat-manager-D_KF5qM1.cjs +1 -0
- package/chunks/common-BIpcR2uQ.cjs +1 -0
- package/chunks/common-D_DfwSd3.js +1 -0
- package/chunks/{group-user-info-resolver-C5pdiqox.cjs → group-user-info-resolver-Ds35Z1Uf.cjs} +1 -1
- package/chunks/{group-user-info-resolver-FNRqDg18.js → group-user-info-resolver-lEtRdWli.js} +1 -1
- package/chunks/index-BmwQgZ3E.js +1 -0
- package/chunks/index-BsIqq7LU.cjs +1 -0
- package/chunks/index-CFMcR5a_.js +1 -0
- package/chunks/index-Dvvh1nf6.cjs +1 -0
- package/chunks/light-Dg9A1Xmd.js +1 -0
- package/chunks/light-dJjIln5b.cjs +1 -0
- package/chunks/query-params-BHyPuD2k.cjs +1 -0
- package/chunks/query-params-Bu3Xq4b6.js +1 -0
- package/chunks/reflection-proto-codec-BerStgkC.cjs +1 -0
- package/chunks/reflection-proto-codec-CjRraw85.js +1 -0
- package/chunks/{session-list-query-B6dh-b4Y.cjs → session-list-query-C4OQMvPf.cjs} +1 -1
- package/chunks/{session-list-query-Dnp2HbpW.js → session-list-query-rynxSxtv.js} +1 -1
- package/chunks/{user-info-BfRwS4ZA.js → user-info-DfbCp80h.js} +1 -1
- package/chunks/{user-info-icpL0Eaw.cjs → user-info-DsDDTJrw.cjs} +1 -1
- package/index.cjs +1 -1
- package/index.js +2 -2
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-manager.d.ts +3 -2
- package/managers/chat-thread/index.cjs +1 -1
- package/managers/chat-thread/index.js +1 -1
- package/managers/chat-thread-manager.d.ts +3 -2
- package/managers/chatroom/index.cjs +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.cjs +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.cjs +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.cjs +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.js +1 -1
- package/managers/user-info/index.cjs +1 -1
- package/managers/user-info/index.js +1 -1
- package/package.json +1 -1
- package/platform/env.d.ts +1 -0
- package/rest/dns-config.d.ts +10 -2
- package/types/chat-client.d.ts +28 -3
- package/utils/query-params.d.ts +16 -0
- package/utils/runtime-global.d.ts +13 -0
- package/utils/storage-error.d.ts +8 -0
- package/validators/chat-client.d.ts +13 -5
- package/chunks/cache-utils-BwRPIZ7n.js +0 -1
- package/chunks/cache-utils-CKbcYPlM.cjs +0 -1
- package/chunks/chat-manager-ChdK26ck.cjs +0 -1
- package/chunks/chat-manager-DH8a6Qj9.js +0 -2
- package/chunks/common-CfAlncj9.cjs +0 -1
- package/chunks/common-DN_g4O3n.js +0 -1
- package/chunks/index-BKg4EGcI.cjs +0 -1
- package/chunks/index-CK3GHdGU.cjs +0 -1
- package/chunks/index-CjofwvEQ.js +0 -1
- package/chunks/index-uKWbjx-u.js +0 -1
- package/chunks/reflection-proto-codec-64ocOTHU.js +0 -1
- package/chunks/reflection-proto-codec-BnQFQdZC.cjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{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-D_DfwSd3.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-DfbCp80h.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
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;
|
package/rest/dns-config.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { DnsConfig } from '../types/chat-client';
|
|
|
5
5
|
import type { RequestAdapter } from '../platform/types';
|
|
6
6
|
export declare const DEFAULT_DNS_CONFIG_URLS: string[];
|
|
7
7
|
export interface DnsConfigResult {
|
|
8
|
+
appKey: string;
|
|
8
9
|
websocketUrl: string;
|
|
9
10
|
websocketUrls: string[];
|
|
10
11
|
syncWebsocketUrls: string[];
|
|
@@ -12,9 +13,16 @@ export interface DnsConfigResult {
|
|
|
12
13
|
restBaseUrl: string;
|
|
13
14
|
dnsConfig: DnsConfig;
|
|
14
15
|
}
|
|
15
|
-
|
|
16
|
-
appKey: string;
|
|
16
|
+
type DnsConfigIdentity = {
|
|
17
|
+
readonly appKey: string;
|
|
18
|
+
readonly appId?: never;
|
|
19
|
+
} | {
|
|
20
|
+
readonly appId: string;
|
|
21
|
+
readonly appKey?: never;
|
|
22
|
+
};
|
|
23
|
+
export declare function resolveDnsConfig(options: DnsConfigIdentity & {
|
|
17
24
|
baseUrls?: string[];
|
|
18
25
|
pageProtocol?: 'http' | 'https';
|
|
19
26
|
requestAdapter?: RequestAdapter;
|
|
20
27
|
}): Promise<DnsConfigResult>;
|
|
28
|
+
export {};
|
package/types/chat-client.d.ts
CHANGED
|
@@ -58,12 +58,30 @@ export interface SyncConversationListConfig {
|
|
|
58
58
|
readonly includeEmpty?: boolean;
|
|
59
59
|
}
|
|
60
60
|
/**
|
|
61
|
-
* [zh-CN]
|
|
62
|
-
* [en-US]
|
|
61
|
+
* [zh-CN] 使用 App Key 初始化的应用身份。
|
|
62
|
+
* [en-US] Application identity initialized with an App Key.
|
|
63
63
|
*/
|
|
64
|
-
export interface
|
|
64
|
+
export interface AppKeyIdentity {
|
|
65
65
|
/** [zh-CN] 应用唯一标识,格式为 `org#app`。 [en-US] Unique application key in `org#app` format. */
|
|
66
66
|
appKey: string;
|
|
67
|
+
/** [zh-CN] 使用 appKey 初始化时不能同时提供 appId。 [en-US] appId cannot be provided when initializing with appKey. */
|
|
68
|
+
appId?: never;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* [zh-CN] 使用 App ID 初始化的应用身份;SDK 会通过 DNSConfig 解析对应的 App Key。
|
|
72
|
+
* [en-US] Application identity initialized with an App ID; the SDK resolves its App Key through DNSConfig.
|
|
73
|
+
*/
|
|
74
|
+
export interface AppIdIdentity {
|
|
75
|
+
/** [zh-CN] 应用唯一 ID。 [en-US] Unique application ID. */
|
|
76
|
+
appId: string;
|
|
77
|
+
/** [zh-CN] 使用 appId 初始化时不能同时提供 appKey。 [en-US] appKey cannot be provided when initializing with appId. */
|
|
78
|
+
appKey?: never;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* [zh-CN] ChatClient 共享初始化选项。
|
|
82
|
+
* [en-US] Shared ChatClient initialization options.
|
|
83
|
+
*/
|
|
84
|
+
export interface InitConfigOptions {
|
|
67
85
|
/** [zh-CN] 是否启用用户资料同步增强能力。 [en-US] Whether to enable enhanced user profile synchronization. */
|
|
68
86
|
enableUserInfoSync?: boolean;
|
|
69
87
|
/** [zh-CN] 登录后自动同步的数据类型。 [en-US] Data types to synchronize automatically after login. */
|
|
@@ -107,6 +125,11 @@ export interface InitConfig {
|
|
|
107
125
|
/** [zh-CN] 可选平台适配配置;缺省时 SDK 自动识别运行环境,仅在非标准宿主或需要覆盖能力时传入。 [en-US] Optional platform-adapter options; SDK auto-detects the runtime by default, so provide this only for non-standard hosts or capability overrides. */
|
|
108
126
|
platformAdapterOptions?: CreatePlatformAdapterOptions;
|
|
109
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* [zh-CN] ChatClient 初始化配置。必须且只能提供 appKey 或 appId 之一;appId 模式必须通过 DNSConfig 发现服务,不能配置固定 serverUrls。
|
|
130
|
+
* [en-US] ChatClient initialization options. Exactly one of appKey or appId is required. App ID mode must use DNSConfig discovery and cannot use fixed serverUrls.
|
|
131
|
+
*/
|
|
132
|
+
export type InitConfig = InitConfigOptions & (AppKeyIdentity | AppIdIdentity);
|
|
110
133
|
/**
|
|
111
134
|
* [zh-CN] 登录参数。
|
|
112
135
|
* [en-US] Login parameters.
|
|
@@ -201,6 +224,8 @@ export interface DnsHost {
|
|
|
201
224
|
* [en-US] DNSConfig response structure.
|
|
202
225
|
*/
|
|
203
226
|
export interface DnsConfig {
|
|
227
|
+
/** [zh-CN] appId 模式下返回的应用 App Key。 [en-US] Application App Key returned in App ID mode. */
|
|
228
|
+
app_key?: string;
|
|
204
229
|
/** [zh-CN] REST 服务地址集合。 [en-US] REST service host set. */
|
|
205
230
|
rest: {
|
|
206
231
|
hosts: DnsHost[];
|
|
@@ -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 {};
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { z } from './validator';
|
|
5
5
|
export declare const initConfigSchema: z.ZodEffects<z.ZodObject<{
|
|
6
|
-
appKey: z.ZodString
|
|
6
|
+
appKey: z.ZodOptional<z.ZodString>;
|
|
7
|
+
appId: z.ZodOptional<z.ZodString>;
|
|
7
8
|
enableUserInfoSync: z.ZodOptional<z.ZodBoolean>;
|
|
8
9
|
enableSyncData: z.ZodOptional<z.ZodArray<z.ZodEnum<["conversation", "contact", "group"]>, "many">>;
|
|
9
10
|
enableDeliveryReceipt: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -73,7 +74,8 @@ export declare const initConfigSchema: z.ZodEffects<z.ZodObject<{
|
|
|
73
74
|
overrides?: object | ((...args: ReadonlyArray<unknown>) => unknown) | undefined;
|
|
74
75
|
}>>;
|
|
75
76
|
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
76
|
-
appKey: z.ZodString
|
|
77
|
+
appKey: z.ZodOptional<z.ZodString>;
|
|
78
|
+
appId: z.ZodOptional<z.ZodString>;
|
|
77
79
|
enableUserInfoSync: z.ZodOptional<z.ZodBoolean>;
|
|
78
80
|
enableSyncData: z.ZodOptional<z.ZodArray<z.ZodEnum<["conversation", "contact", "group"]>, "many">>;
|
|
79
81
|
enableDeliveryReceipt: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -143,7 +145,8 @@ export declare const initConfigSchema: z.ZodEffects<z.ZodObject<{
|
|
|
143
145
|
overrides?: object | ((...args: ReadonlyArray<unknown>) => unknown) | undefined;
|
|
144
146
|
}>>;
|
|
145
147
|
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
146
|
-
appKey: z.ZodString
|
|
148
|
+
appKey: z.ZodOptional<z.ZodString>;
|
|
149
|
+
appId: z.ZodOptional<z.ZodString>;
|
|
147
150
|
enableUserInfoSync: z.ZodOptional<z.ZodBoolean>;
|
|
148
151
|
enableSyncData: z.ZodOptional<z.ZodArray<z.ZodEnum<["conversation", "contact", "group"]>, "many">>;
|
|
149
152
|
enableDeliveryReceipt: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -213,7 +216,8 @@ export declare const initConfigSchema: z.ZodEffects<z.ZodObject<{
|
|
|
213
216
|
overrides?: object | ((...args: ReadonlyArray<unknown>) => unknown) | undefined;
|
|
214
217
|
}>>;
|
|
215
218
|
}, z.ZodTypeAny, "passthrough">>, z.objectOutputType<{
|
|
216
|
-
appKey: z.ZodString
|
|
219
|
+
appKey: z.ZodOptional<z.ZodString>;
|
|
220
|
+
appId: z.ZodOptional<z.ZodString>;
|
|
217
221
|
enableUserInfoSync: z.ZodOptional<z.ZodBoolean>;
|
|
218
222
|
enableSyncData: z.ZodOptional<z.ZodArray<z.ZodEnum<["conversation", "contact", "group"]>, "many">>;
|
|
219
223
|
enableDeliveryReceipt: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -283,7 +287,8 @@ export declare const initConfigSchema: z.ZodEffects<z.ZodObject<{
|
|
|
283
287
|
overrides?: object | ((...args: ReadonlyArray<unknown>) => unknown) | undefined;
|
|
284
288
|
}>>;
|
|
285
289
|
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
286
|
-
appKey: z.ZodString
|
|
290
|
+
appKey: z.ZodOptional<z.ZodString>;
|
|
291
|
+
appId: z.ZodOptional<z.ZodString>;
|
|
287
292
|
enableUserInfoSync: z.ZodOptional<z.ZodBoolean>;
|
|
288
293
|
enableSyncData: z.ZodOptional<z.ZodArray<z.ZodEnum<["conversation", "contact", "group"]>, "many">>;
|
|
289
294
|
enableDeliveryReceipt: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -389,6 +394,7 @@ export declare const dnsHostSchema: z.ZodObject<{
|
|
|
389
394
|
port: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodNumber]>>;
|
|
390
395
|
}, z.ZodTypeAny, "passthrough">>;
|
|
391
396
|
export declare const dnsConfigResponseSchema: z.ZodObject<{
|
|
397
|
+
app_key: z.ZodOptional<z.ZodString>;
|
|
392
398
|
rest: z.ZodObject<{
|
|
393
399
|
hosts: z.ZodArray<z.ZodObject<{
|
|
394
400
|
protocol: z.ZodString;
|
|
@@ -521,6 +527,7 @@ export declare const dnsConfigResponseSchema: z.ZodObject<{
|
|
|
521
527
|
enableMd5Check: z.ZodOptional<z.ZodEnum<["true", "false"]>>;
|
|
522
528
|
uploadinparts_enable: z.ZodOptional<z.ZodEnum<["true", "false"]>>;
|
|
523
529
|
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
530
|
+
app_key: z.ZodOptional<z.ZodString>;
|
|
524
531
|
rest: z.ZodObject<{
|
|
525
532
|
hosts: z.ZodArray<z.ZodObject<{
|
|
526
533
|
protocol: z.ZodString;
|
|
@@ -653,6 +660,7 @@ export declare const dnsConfigResponseSchema: z.ZodObject<{
|
|
|
653
660
|
enableMd5Check: z.ZodOptional<z.ZodEnum<["true", "false"]>>;
|
|
654
661
|
uploadinparts_enable: z.ZodOptional<z.ZodEnum<["true", "false"]>>;
|
|
655
662
|
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
663
|
+
app_key: z.ZodOptional<z.ZodString>;
|
|
656
664
|
rest: z.ZodObject<{
|
|
657
665
|
hosts: z.ZodArray<z.ZodObject<{
|
|
658
666
|
protocol: z.ZodString;
|
|
@@ -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;
|