easemob-websdk 5.1.2 → 5.1.3
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 +11 -3
- package/cache/cache-types.d.ts +13 -2
- package/chat-client.d.ts +6 -0
- package/chunks/{chat-manager-BFd2Z4oY.cjs → chat-manager-BI-6bEor.cjs} +1 -1
- package/chunks/{chat-manager-CId_M_e5.js → chat-manager-nXOTpJ01.js} +2 -2
- package/chunks/{common-BvlDAw4a.js → common-DHQukb7J.js} +1 -1
- package/chunks/{event-system-B62vbKqG.js → event-system-DguqwFpc.js} +1 -1
- package/chunks/{group-user-info-resolver-DMccCqez.js → group-user-info-resolver-D6AQAHEE.js} +1 -1
- package/chunks/{index-BBFJYOM8.js → index-CneY58NJ.js} +1 -1
- package/chunks/index-DxjmfFL7.js +1 -0
- package/chunks/push-manager-CSIKhoPe.js +1 -0
- package/chunks/push-manager-D7RDsKuv.cjs +1 -0
- package/chunks/session-list-query-C3iQvQxK.cjs +1 -0
- package/chunks/session-list-query-Cdpiw_IZ.js +1 -0
- package/chunks/{user-info-AlshAvdy.js → user-info-7QzMa7bR.js} +1 -1
- package/core/session-list-sync/session-list-message-events.d.ts +9 -0
- 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-thread/index.js +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.js +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.js +1 -1
- package/message/message-snapshot.d.ts +8 -0
- package/package.json +1 -1
- package/protocol/msync/codec.d.ts +1 -21
- package/protocol/msync/message-identity.d.ts +2 -0
- package/protocol/msync/message-payload-decoder.d.ts +35 -0
- package/protocol/session-list/gateway.d.ts +8 -1
- package/protocol/session-list/payload-decoder.d.ts +12 -0
- package/types/conversation.d.ts +27 -20
- package/utils/session-message-recipient.d.ts +11 -0
- package/chunks/index-l_BUKi77.js +0 -1
- package/chunks/session-list-query-Cvr6rlme.js +0 -1
- package/chunks/session-list-query-Dslj2k3t.cjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={VALIDATION_REQUIRED:110,VALIDATION_INVALID_FORMAT:110,VALIDATION_UNKNOWN:110,AUTH_ALREADY_LOGIN:200,AUTH_NOT_LOGIN:201,AUTH_UNAUTHORIZED:202,AUTH_FORBIDDEN:210,AUTH_TOKEN_EXPIRED:108,AUTH_BIND_ANOTHER_DEVICE:213,AUTH_LOGIN_TOO_MANY_DEVICES:214,AUTH_USER_MUTED:215,CONNECTION_TIMEOUT:301,CONNECTION_LOGIN_TIMEOUT:301,CONNECTION_WEBSOCKET_ERROR:300,CONNECTION_NOT_CREATED:1,CONNECTION_CLOSED_BEFORE_READY:300,CONNECTION_CANCELLED:1,CONNECTION_PROVISION_TIMEOUT:301,CONNECTION_PROVISION_REJECTED:202,CONNECTION_PROVISION_CLOSED:300,CONNECTION_DNSLIST_FAILED:304,STORAGE_OPERATION_FAILED:3,MESSAGE_NOT_CONNECTED:300,MESSAGE_ACK_TIMEOUT:301,MESSAGE_SEND_FAILED:303,MESSAGE_SENDER_DESTROYED:1,MESSAGE_ENCODE_FAILED:500,MESSAGE_DECODE_FAILED:500,MESSAGE_ACK_MISSING:301,MESSAGE_BLOCKED_BY_RECIPIENT:222,OPERATION_UNSUPPORTED:111,SERVER_BUSY:302,ATTACHMENT_NOT_FOUND:400,ATTACHMENT_INVALID:401,ATTACHMENT_EXPIRED:407,MESSAGE_INCLUDE_ILLEGAL_CONTENT:501,MESSAGE_SEND_TRAFFIC_LIMIT:502,MESSAGE_RECALL_TIME_LIMIT:504,SERVICE_NOT_ENABLED:505,MESSAGE_EXPIRED:506,MESSAGE_ILLEGAL_WHITELIST:507,MESSAGE_EXTERNAL_LOGIC_BLOCKED:508,MESSAGE_CURRENT_LIMITING:509,MESSAGE_SIZE_LIMIT:510,MESSAGE_EDIT_FAILED:511,INVALID_CONVERSATION:107,USER_LOGIN_ANOTHER_DEVICE:206,USER_REMOVED:207,USER_KICKED_BY_CHANGE_PASSWORD:216,USER_KICKED_BY_OTHER_DEVICE:217,USER_ALREADY_LOGIN_ANOTHER:218,USER_MUTED_BY_ADMIN:219,USER_DEVICE_CHANGED:220,USER_NOT_ON_ROSTER:221,SERVER_SERVING_DISABLED:305,FILE_DOWNLOAD_FAILED:403,FILE_TOO_LARGE:405,FILE_CONTENT_IMPROPER:406,THIRD_MODERATION_FAILED:1200,THIRD_DEFAULT_FAILED:1299,STREAM_SEND_NOT_SUPPORTED:303,STREAM_CHUNK_INVALID:500,STREAM_TIMEOUT_BY_SERVER:500,STREAM_STATE_CONFLICT:500,COMBINE_INVALID_INPUT:110,COMBINE_LEVEL_EXCEEDED:4,COMBINE_ITEM_LIMIT_EXCEEDED:4,COMBINE_ENCODE_FAILED:500,COMBINE_UPLOAD_FAILED:402,COMBINE_DOWNLOAD_FAILED:2,COMBINE_PARSE_FAILED:500,REST_NETWORK_ERROR:2,REST_TIMEOUT:301,REST_HTTP_ERROR:303,REST_BUSINESS_UNKNOWN:303,PUSH_TOKEN_UPLOAD_FAILED:1500,PUSH_SILENT_MODE_OPERATION_FAILED:1501,PUSH_LANGUAGE_OPERATION_FAILED:1502,USER_INFO_SUBSCRIPTION_LIMIT_EXCEEDED:1600,USER_INFO_SUBSCRIPTION_TARGET_LIMIT_EXCEEDED:1601,USERINFO_USERCOUNT_EXCEED:900,USERINFO_DATALENGTH_EXCEED:901,CONTACT_ADD_USER_NOT_FOUND:204,CONTACT_ADD_ALREADY_FRIEND:1e3,CONTACT_ADD_BLOCKED_BY_USER:210,CONTACT_SET_REMARK_NOT_FRIEND:223,CONTACT_REACH_LIMIT:1001,CONTACT_REACH_LIMIT_PEER:1002,CONTACT_BLOCKLIST_USER_NOT_FOUND:204,GROUP_INVALID_ID:600,GROUP_ALREADY_JOINED:601,GROUP_NOT_JOINED:602,GROUP_PERMISSION_DENIED:603,GROUP_MEMBERS_FULL:604,GROUP_SHARED_FILE_INVALID_ID:605,GROUP_NOT_EXIST:606,GROUP_DISABLED:607,GROUP_NAME_VIOLATION:608,GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT:609,GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED:610,GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT:611,GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT:612,GROUP_USER_IN_BLOCKLIST:613,CHATROOM_INVALID_ID:700,CHATROOM_NOT_JOINED:702,CHATROOM_PERMISSION_DENIED:703,CHATROOM_MEMBERS_FULL:704,CHATROOM_NOT_EXIST:705,CHATROOM_OWNER_NOT_ALLOW_LEAVE:706,CHATROOM_USER_IN_BLOCKLIST:707,CONTACT_SYNC_METADATA_FAILED:1700,CONTACT_SYNC_SOCKET_FAILED:1701,CONTACT_SYNC_CURSOR_INVALID:1702,CONTACT_SYNC_PROTO_DECODE_FAILED:1703,CONTACT_SYNC_CANCELLED:1704,SESSION_LIST_SOCKET_FAILED:300,SESSION_LIST_PROTO_DECODE_FAILED:500,SESSION_LIST_REQUEST_INVALID:110,SESSION_LIST_FETCH_FAILED:303,SESSION_LIST_SERVICE_DISABLED:305,SESSION_LIST_CANCELLED:1,PRESENCE_PARAM_LENGTH_EXCEED:1100,PRESENCE_CANNOT_SUBSCRIBE_YOURSELF:1101,TRANSLATE_PARAM_INVALID:1110,TRANSLATE_SERVICE_NOT_ENABLED:1111,TRANSLATE_USAGE_LIMIT:1112,TRANSLATE_FAILED:1113,VOICE_TO_TEXT_FILE_INVALID:407,VOICE_TO_TEXT_FILE_DURATION_TOO_LONG:408,VOICE_TO_TEXT_FAILED:409,VOICE_TO_TEXT_FILE_NOT_FOUND:410,VOICE_TO_TEXT_FILE_TOO_LARGE:411,REACTION_REACH_LIMIT:1300,REACTION_ALREADY_OPERATED:1301,REACTION_OPERATION_ILLEGAL:1302,UPLOAD_REQUIRED_FIELD_MISSING:110,UPLOAD_INVALID_APPKEY:100,UPLOAD_SIZE_EXCEEDED:405,UPLOAD_REQUEST_FAILED:402,UPLOAD_TIMEOUT:301,UPLOAD_ABORTED:1,SERVICE_LIMIT_EXCEEDED:4,UNKNOWN:1},t="[REDACTED]",o=e=>{if(!e)return"";const o=e.includes("?"),r=e.includes("#");try{return((e,o,r)=>(e.username&&(e.username=t),e.password&&(e.password=t),e.search=o?`?${t}`:"",e.hash=r?`#${t}`:"",e.toString()))(new URL(e),o,r)}catch{const o=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===o?"[invalid-url]":`${e.slice(0,o)}?${t}`}},r=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,o(t)]:[e,t]));class s extends Error{constructor(t,o=e.UNKNOWN,i){super(t),this.name="SDKError",this.code=o,this.details=i?.details?r(i.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,s)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class i extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="NetworkError"}}class a extends s{constructor(t,o){super(t,o?.code??e.CONNECTION_WEBSOCKET_ERROR,o),this.name="ConnectionError"}}class n extends s{constructor(t,o){super(t,o?.code??e.AUTH_UNAUTHORIZED,o),this.name="AuthenticationError"}}class p extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class E extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_SEND_FAILED,o),this.name="MessageSendError"}}class c extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_DECODE_FAILED,o),this.name="MessageReceiveError"}}class T extends s{constructor(t,o){super(t,o?.code??e.STORAGE_OPERATION_FAILED,o),this.name="StorageError"}}class u extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="RestTransportError"}}class d extends s{constructor(t,o){super(t,o?.code??e.REST_BUSINESS_UNKNOWN,o),this.name="RestBusinessError"}}class l extends s{constructor(t,o){super(t,o?.code??e.UPLOAD_REQUEST_FAILED,o),this.name="UploadError"}}function O(e){if(e instanceof s)return!0;if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&"string"==typeof t.message&&"number"==typeof t.code&&"function"==typeof t.toJSON}const _=15e3,R=1e4,m=15e3,h=3e5,N=6e4,I=3e5,A=1e4,f=1e4,S=3e4,y=5e3,C=12e4,M=3e4,g=6e4,D=1e3,U=6e4,L=2,b=5e3,P=1e4,G=1e3,H=5e3,w=2,v=0,F=2e4,B=7e3,k=20,K=3,q=1,V=7e3,$=1e3,x=50,j=5,z=5e3,W=2,Y=[1e3,2e3],X=2500,J=1,Q=500,Z=6e3,ee={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",heic:"image/heic",heif:"image/heif",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",mp3:"audio/mpeg",m4a:"audio/mp4",wav:"audio/wav",aac:"audio/aac",amr:"audio/amr",pdf:"application/pdf",txt:"text/plain",json:"application/json"},te=e=>"undefined"!=typeof Blob&&e instanceof Blob,oe=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),o=t.length>0?t[t.length-1]:void 0;if(o)return o},re=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const o=e.slice(t+1).toLowerCase();return ee[o]},se=(e,t)=>{for(const o of t){const t=e[o];if("string"==typeof t&&t.length>0)return t}},ie=e=>{const t=e.file,o=e.sourceMeta,r=t.name||(o?se(o,["name","fileName","filename"]):void 0),s=e.file.type||(o?se(o,["type","mimeType","filetype"]):void 0),i=e.file.size||(o?((e,t)=>{for(const o of t){const t=e[o];if("number"==typeof t&&Number.isFinite(t))return t}})(o,["size","fileSize","fileLength"]):void 0),a=ae({fileName:r,fileType:s,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize,webFile:e.file}},ae=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),ne=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(te(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const o of["file","originFileObj","raw","blob"]){const e=t[o];if(te(e))return e}})(t);if(i)return ie({file:i,fallbackName:o,fallbackMimeType:r,fallbackSize:s,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=oe(t.path),i=ae({fileName:t.name??e,fileType:t.type??re(t.name??e),fileSize:t.size,fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"miniapp-path",path:t.path,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}if((e=>"object"==typeof e&&null!==e&&"uri"in e)(t)){const e=oe(t.uri),i=ae({fileName:t.name??e,fileType:t.type??re(t.name??e),fileSize:t.size,fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"rn-uri",uri:t.uri,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}const a=ae({fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"web-file",name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize}},pe=5242880,Ee=5242880,ce=4,Te="CHAT",ue="GROUP",de="ROOM",le="original",Oe="large",_e=e=>/^https?:\/\//i.test(e),Re=(e,t)=>!!t||(!e||!_e(e)),me=t=>{const o=t.split("#");if(2!==o.length||!o[0]||!o[1])throw new l("Invalid appKey for upload",{code:e.UPLOAD_INVALID_APPKEY,details:{appKey:t}});return{orgName:o[0],appName:o[1]}},he=e=>"singleChat"===e?Te:"groupChat"===e?ue:de,Ne=(e,t)=>Ae(e,{size:t}),Ie=e=>{try{return decodeURIComponent(e)}catch{return e}},Ae=(e,t)=>{const[o="",r]=e.split("#",2),[s,i=""]=o.split("?",2),a=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const o=encodeURIComponent(e),r=a.filter(t=>{const[r=""]=t.split("=",2);return r!==o&&Ie(r)!==e});a.length=0,a.push(...r),void 0!==t&&a.push(`${o}=${encodeURIComponent(String(t))}`)}),`${s}${a.length>0?`?${a.join("&")}`:""}${r?`#${r}`:""}`},fe=(e,t)=>{if(!e)return"";const o={};return e.includes("em-redirect")||(o["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(o["share-secret"]=t),0===Object.keys(o).length?e:Ae(e,o)},Se=e=>e.isGif?{resolvedImageType:le,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:le,reason:"explicit-original"}:{resolvedImageType:Oe,reason:"default-large"},ye=e=>{const t=(o=e.messageType,r=e.imageType,"image"!==o?"attachment":r===le?"image-origin":"image-big");var o,r;const s=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>s;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:s,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},Ce=t=>{const o=t.entities?.[0],r=!0===o?.exists,s="string"==typeof o?.uuid&&o.uuid.length>0?o.uuid:void 0,i=o,a=i?.["exists-type"]??i?.existsType,n="origin"===a?le:a===Oe||a===le?a:void 0,p="string"==typeof o?.["share-secret"]?o["share-secret"]:void 0;if(r&&!s)throw new l("Upload precheck response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{uuid:s,exists:r,existsType:n,shareSecret:p,hit:(E={exists:r,uuid:s},E.exists&&"string"==typeof E.uuid&&E.uuid.length>0)};var E},Me=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const o=(e=>{const[t="",o]=e.split("#",2),[r,s=""]=t.split("?",2),i=s.split("&").filter(Boolean).filter(e=>{const[t="",o=""]=e.split("=",2),r=Ie(t),s=Ie(o);return"size"!==r||!["big","large","thumbnail","small"].includes(s)}).join("&");return`${r}${i?`?${i}`:""}${o?`#${o}`:""}`})(e);return{originalImageUrl:o,bigImageUrl:Ne(o,"large"),thumbnailUrl:Ne(o,"small")}},ge=e=>e===le?"origin":"large",De=e=>e===le?1:2,Ue=e=>2===e?Oe:le,Le=t=>{const o=t.response.entities?.[0];if(!o?.uuid)throw new l("Upload response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t.response}});const r=o["share-secret"],s=o["file-metadata"]??{},i="number"==typeof s["content-length"]?s["content-length"]:t.fallbackSize,a="string"==typeof s["content-type"]?s["content-type"]:t.fileType,n=`${t.restBaseUrl}/${t.orgName}/${t.appName}/chatfiles/${o.uuid}`;if("image"===t.messageType){const e=(t.imageType??Oe)===le;return{...Me(n,{deriveVariants:!t.useCustomAttachmentUpload}),isOriginalImage:e,secret:r,fileLength:i,filetype:a,filename:t.fileName,width:t.width,height:t.height}}const p="video"===t.messageType?`${n}?vframe=true`:void 0;return{url:n,secret:r,fileLength:i,filetype:a,filename:t.fileName,thumbnailUrl:p}},be=(t,o)=>{if(!t)throw new l("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"file missing"}});const r=("number"==typeof o.fileLength?o.fileLength:void 0)??("fileSize"in o&&"number"==typeof o.fileSize?o.fileSize:void 0),s=ne({file:t,fallbackName:o.filename,fallbackMimeType:o.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new l("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s},Pe=e=>new Promise(t=>{setTimeout(t,e)});const Ge=new class{constructor(e){this.state="disabled",this.timerId=null,this.reporting=!1,this.context={},this.buffer=[],this.bufferBytes=0,this.reportIntervalMs=this.normalizeReportInterval(e?.reportIntervalMs),this.reportTimeoutMs=e?.reportTimeoutMs??15e3,this.chunkDelayMs=e?.chunkDelayMs??3e3,this.maxChunkBytes=e?.maxChunkBytes??2097152,this.maxBufferBytes=e?.maxBufferBytes??3145728}setEnabled(e){this.setState(e?"enabled":"disabled")}setState(e){this.state=e,"enabled"!==e?(this.stop(),this.clearBuffer()):this.start()}updateContext(e){this.context={...this.context,...e}}updateReportInterval(e){this.reportIntervalMs=this.normalizeReportInterval(e),"enabled"===this.state&&this.start()}append(e){if("disabled"===this.state)return;const t=this.formatEntry(e);this.pushBuffer(t)}async reportNow(){await this.reportLogs()}stop(){this.timerId&&(clearInterval(this.timerId),this.timerId=null)}clearBuffer(){this.buffer=[],this.bufferBytes=0}start(){this.stop(),this.timerId=setInterval(()=>{this.reportLogs()},this.reportIntervalMs)}normalizeReportInterval(e){const t=void 0!==e&&Number.isFinite(e)&&e>0?e:3e5;return Math.max(t,6e4)}canReport(){return Boolean(this.context.restBaseUrl&&this.context.appKey&&this.context.userId&&this.context.token&&this.context.requestAdapter)}formatEntry(e){const t=e.args.length>0?e.args.map(e=>(e=>{if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}})(e)).join(" "):"",o=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${o}`}pushBuffer(e){const t=e.length;if(!(t>=this.maxBufferBytes)){for(;this.bufferBytes+t>this.maxBufferBytes&&this.buffer.length>0;){const e=this.buffer.shift();e&&(this.bufferBytes-=e.length)}this.buffer.push(e),this.bufferBytes+=t}}consumeBuffer(){if(0===this.buffer.length)return[];const e=`${this.buffer.join("\n")}\n`;this.clearBuffer();const t=[];let o=e;for(;o.length>this.maxChunkBytes;)t.push(o.slice(0,this.maxChunkBytes)),o=o.slice(this.maxChunkBytes);return o.length>0&&t.push(o),t}requeueChunk(e){this.pushBuffer(e)}async reportLogs(){if("enabled"===this.state&&!this.reporting&&0!==this.buffer.length){this.reporting=!0;try{const e=this.consumeBuffer();if(0===e.length)return;if(!this.canReport())return void e.forEach(e=>this.requeueChunk(e));for(const t of e){await this.reportChunk(t)||this.requeueChunk(t),await Pe(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:o,userId:r,token:s,resource:i,requestAdapter:a}=this.context;if(!(t&&o&&r&&s&&a))return!1;let n="",p="";try{const e=me(o);n=e.orgName,p=e.appName}catch{return!1}const E=`${t}/${n}/${p}/sdk/users/${r}/client/logs`,c={resource:i??"webim",logContent:e};try{const e=await a.request({url:E,method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body:c,responseType:"json",timeoutMs:this.reportTimeoutMs});if(e.status<200||e.status>=300)return!1;const t="string"==typeof e.data?(e=>{try{return JSON.parse(e)}catch{return}})(e.data):e.data;return!t||!t.status||"ok"===t.status}catch{return!1}}},He="[MASKED]",we=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),ve=e=>!!e&&we.has((e=>e.toLowerCase())(e)),Fe=(e,t,o)=>{const r=o??/* @__PURE__ */new WeakSet;if("string"==typeof e)return((e,t)=>ve(t)?He:e)(e,t);if("number"==typeof e||"boolean"==typeof e||null==e)return e;if("bigint"==typeof e||"symbol"==typeof e)return e.toString();if("function"==typeof e)return`[Function ${e.name||"anonymous"}]`;if(e instanceof Error)return{name:(s=e).name,message:s.message};var s;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>Fe(e,void 0,r));if("object"==typeof e){if(r.has(e))return"[Circular]";if(r.add(e),(e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Date||e instanceof Error))(e)){const t={};for(const[o,s]of Object.entries(e))ve(o)?t[o]=He:t[o]=Fe(s,o,r);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},Be="undefined"!=typeof document;let ke=null,Ke=!1;const qe={DEBUG:0,WARN:1,ERROR:2};class Ve{constructor(e="WARN"){this.consoleEnabled=!0,this.level=e}setLevel(e){this.level=e}setConsoleEnabled(e){this.consoleEnabled=e}shouldLog(e){return qe[e]>=qe[this.level]}emit(e,t,o){const r=(e=>{const t=/* @__PURE__ */new WeakSet;return e.map(e=>Fe(e,void 0,t))})(o),s=((e,t,o)=>({timestamp:/* @__PURE__ */(new Date).toISOString(),level:e,message:t,args:o}))(e,t,r);if(Ge.append(s),this.consoleEnabled){const o=/* @__PURE__ */new Date,s=`[Chat][${e}][${`${String(o.getHours()).padStart(2,"0")}:${String(o.getMinutes()).padStart(2,"0")}:${String(o.getSeconds()).padStart(2,"0")}.${String(o.getMilliseconds()).padStart(3,"0")}`}]`;Be?console.log(`%c${s}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(s,t,...r)}const i=ke;i&&!Ke&&Promise.resolve().then(()=>{if(i===ke){Ke=!0;try{i(s)}catch{}finally{Ke=!1}}})}debug(e,...t){this.shouldLog("DEBUG")&&this.emit("DEBUG",e,t)}warn(e,...t){this.shouldLog("WARN")&&this.emit("WARN",e,t)}error(e,...t){this.shouldLog("ERROR")&&this.emit("ERROR",e,t)}}let $e=new Ve;function xe(e){$e instanceof Ve&&$e.setLevel(e)}function je(e){$e instanceof Ve&&$e.setConsoleEnabled(e)}function ze(e){ke=e}function We(e){Ge.setState(e)}function Ye(e){Ge.updateContext(e)}function Xe(e){Ge.updateReportInterval(e)}async function Je(){await Ge.reportNow()}function Qe(){Ge.stop()}const Ze={debug:(e,...t)=>$e.debug(e,...t),warn:(e,...t)=>$e.warn(e,...t),error:(e,...t)=>$e.error(e,...t)},et={WEB:"web",WECHAT_MINIAPP:"wechat-miniapp",QQ_MINIAPP:"qq-miniapp",TOUTIAO_MINIAPP:"toutiao-miniapp",BAIDU_MINIAPP:"baidu-miniapp",ALIPAY_MINIAPP:"alipay-miniapp",DINGTALK_MINIAPP:"dingtalk-miniapp",LARK_MINIAPP:"lark-miniapp",KUAISHOU_MINIAPP:"kuaishou-miniapp",JD_MINIAPP:"jd-miniapp",MINIAPP_360:"360-miniapp",HARMONY_MINIAPP:"harmony-miniapp",QUICKAPP:"quickapp",UNIAPP:"uniapp",REACT_NATIVE:"react-native",ELECTRON_RENDERER:"electron-renderer",ELECTRON_MAIN:"electron-main",UNKNOWN:"unknown"},ot={INIT:"init",REQUEST:"request",UPLOAD:"upload",SOCKET:"socket",PROTO:"proto",RUNTIME:"runtime",STORAGE:"storage"},rt={INIT_FAILED:"PLATFORM_INIT_FAILED",MISSING_CAPABILITY:"PLATFORM_MISSING_CAPABILITY",REQUEST_FAILED:"PLATFORM_REQUEST_FAILED",UPLOAD_FAILED:"PLATFORM_UPLOAD_FAILED",SOCKET_FAILED:"PLATFORM_SOCKET_FAILED",PROTO_FAILED:"PLATFORM_PROTO_FAILED"},st=(e,t)=>{const o=new Error(e);return o.name="PlatformAdapterError",o.code=t.code,o.stage=t.stage,o.retryable=t.retryable,t.details&&(o.details=r(t.details)),o},it={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},at=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],nt=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const o={},r=e;for(const s of at)try{const e=r[s];void 0!==e&&(o[s]=e)}catch{}for(const s of Object.keys(t))o[s]=t[s];return o})("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,{..."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}:{}})},pt=e=>{const t={};if(!e)return t;if("function"==typeof e.forEach)return e.forEach((e,o)=>{t[o]=e}),t;const o=e.get?.("content-type");return o&&(t["content-type"]=o),t},Et=async(e,t)=>{const o=e;if("function"!=typeof o.text){if("function"!=typeof o.json)return"";const e=await o.json();return t?e:JSON.stringify(e)}const r=await o.text();if(!t||0===r.length)return r;try{return JSON.parse(r)}catch{return r}},ct=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(o){const r=o.method??"GET",s={...o.headers??{}},i=new AbortController,a=o.timeoutMs??e?.timeoutMs??15e3;let n=!1;const p=()=>i.abort(o.signal?.reason);o.signal?.aborted?p():o.signal?.addEventListener("abort",p,{once:!0});const E=setTimeout(()=>{n=!0,i.abort()},a),c=((e,t,o)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==o)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(o,s,r);try{const e=await t(o.url,{method:r,headers:s,body:c,signal:i.signal});let a;if("arraybuffer"===o.responseType)a=await e.arrayBuffer();else if("text"===o.responseType)a=await e.text();else if("json"===o.responseType)a=await Et(e,!0);else{const t=e.headers.get("content-type")??"";a=await Et(e,t.includes("application/json"))}return{status:e.status,statusText:e.statusText,headers:pt(e.headers),data:a}}catch(T){const e=((e,t,o)=>t?"timeout":o?.aborted||e instanceof Error&&"AbortError"===e.name?"abort":"network")(T,n,o.signal);throw st("Request adapter execution failed.",{code:rt.REQUEST_FAILED,stage:ot.REQUEST,retryable:"abort"!==e,details:{url:o.url,method:r,reason:e,cause:T instanceof Error?T.message:String(T)}})}finally{clearTimeout(E),o.signal?.removeEventListener("abort",p)}}}},Tt=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,ut="X-Request-Id",dt=1e3,lt="direct";class Ot{constructor(e){this.events=[],this.enabled=!1,this.acceptedInWindow=0,this.capacityDiagnosticEmitted=!1,this.rateDiagnosticEmitted=!1,this.sendBatch=e.send,this.capacity=e.capacity??1e3,this.batchSize=e.batchSize??10,this.rateLimit=e.rateLimit??1e3,this.flushIntervalMs=e.flushIntervalMs??1e3,this.now=e.now??Date.now,this.onDrop=e.onDrop,this.windowStartedAt=this.now()}get size(){return this.events.length}enqueue(e){return this.refreshRateWindow(),this.acceptedInWindow>=this.rateLimit?(this.rateDiagnosticEmitted||(this.rateDiagnosticEmitted=!0,this.onDrop?.("rate-limit")),!1):this.events.length>=this.capacity?(this.capacityDiagnosticEmitted||(this.capacityDiagnosticEmitted=!0,this.onDrop?.("capacity")),!1):(this.events.push(e),this.acceptedInWindow+=1,this.schedule(),!0)}enable(){this.enabled=!0,this.schedule()}updateAppKey(e,t){for(let o=0;o<this.events.length;o+=1){const r=this.events[o];r&&r.appKey===e&&(this.events[o]={appKey:t,wire:{...r.wire,body:{...r.wire.body,appkey:t}}})}}pause(){this.enabled=!1,this.clearTimer()}clear(){this.pause(),this.events.splice(0,this.events.length),this.acceptedInWindow=0,this.windowStartedAt=this.now(),this.capacityDiagnosticEmitted=!1,this.rateDiagnosticEmitted=!1}refreshRateWindow(){const e=this.now();e-this.windowStartedAt<6e4||(this.windowStartedAt=e,this.acceptedInWindow=0,this.rateDiagnosticEmitted=!1)}schedule(){this.enabled&&0!==this.events.length&&!this.timer&&(this.timer=setTimeout(()=>{this.timer=void 0,this.consume()},this.flushIntervalMs))}async consume(){if(!this.enabled||0===this.events.length)return;const e=this.events[0];if(!e)return;const t=[];for(let o=0;o<this.events.length&&t.length<this.batchSize;){const r=this.events[o];r?.appKey===e.appKey?(t.push(r.wire),this.events.splice(o,1)):o+=1}this.events.length<this.capacity&&(this.capacityDiagnosticEmitted=!1);try{await this.sendBatch(e.appKey,t)}catch{}finally{this.schedule()}}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}}class _t{constructor(e){this.requestAdapter=e.requestAdapter,this.debug=e.debug??!1,this.now=e.now??Date.now,this.onFailure=e.onFailure}async send(e,t){if(this.requestAdapter&&0!==t.length)try{const o=await this.requestAdapter.request({url:this.debug?"https://data-reporting.realtimemesh.com/report":"https://data-reporting.rtnsvc.com/report",method:"POST",headers:{"Content-Type":"application/json",token:"32f24ab2ddb74f508aa9286c356cec84",appid:e,sendts:String(Math.floor(this.now()/1e3)),biz:"im",debug:String(this.debug)},body:JSON.stringify(t),responseType:"text",timeoutMs:15e3});(o.status<200||o.status>=300)&&this.onFailure?.({reason:"non-success-response",status:o.status})}catch(o){this.onFailure?.({reason:"transport-error",message:o instanceof Error?o.message:String(o)})}else this.onFailure?.({reason:"request-adapter-unavailable",eventCount:t.length})}}const Rt={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},mt=()=>{const e=nt(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class ht{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??mt;const t=new _t({requestAdapter:e.requestAdapter,debug:e.debug,now:this.now,onFailure:t=>{e.onDiagnostic?.("DataReport transport failed",t)}}),o=e.send??((e,o)=>t.send(e,o));this.queue=new Ot({send:o,now:this.now,onDrop:t=>{e.onDiagnostic?.("DataReport event dropped",{reason:t})}})}get state(){return this.currentState}get queuedEventCount(){return this.queue.size}get serviceId(){return this.session?.serviceId}startSession(e){this.queue.clear(),this.currentState="unknown";const t=this.randomId();return this.session={...e,sessionId:`session_${t}`,serviceId:`sid_${t}`},this.enqueue(9674,{did:e.did??"",os:e.os??e.platform,sdkVersion:e.sdkVersion,deviceId:e.deviceId??""}),this.session.serviceId}updateSession(e){this.session&&(e.appKey&&e.appKey!==this.session.appKey&&this.queue.updateAppKey(this.session.appKey,e.appKey),this.session={...this.session,...e})}updateNetworkType(e){this.networkType=(e=>"number"==typeof e&&Number.isFinite(e)?e:"string"!=typeof e?-1:Rt[e.trim().toLowerCase()]??-1)(e)}applyDnsSwitch(e){if(this.session){if("true"===e)return this.currentState="enabled",void this.queue.enable();this.currentState="disabled",this.queue.clear()}else this.currentState="disabled"}startOperation(e){const t=this.session?.sessionId;if(!t||"disabled"===this.currentState)return this.createNoopOperation();const o=`opr_${this.randomId()}`,r=this.now();let s=!1,i=!1,a=`req_${this.randomId()}`,n=0,p="";const E=()=>!s&&!i&&this.session?.sessionId===t,c=(t,r,s,i,a)=>{E()&&(n=a.success?0:a.code,p=a.success?"":a.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:r,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(s),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:a.code,codeDesc:a.description??"",isLastApi:0,isSuccess:a.success?1:0,accessChannel:this.session?.accessChannel??lt,msgId:e.msgId,messageType:e.messageType,resultCount:a.resultCount}))},T=(e,t,o,r)=>{const s=this.now();let i=!1;return{retry:()=>(r.next+=1,T(e,t,r.next,r)),finish:r=>{i||(i=!0,c(e,t,o,s,r))}}};return{startRequest:(e={})=>(a=`req_${this.randomId()}`,T(e,a,1,{next:1})),finish:t=>{E()&&(s=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:a,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-r),code:t.success?0:t.code??n,codeDesc:t.success?"":t.description??p,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??lt,msgId:e.msgId,messageType:e.messageType,resultCount:t.resultCount}))},discard:()=>{i=!0}}}reset(){this.currentState="disabled",this.session=void 0,this.queue.clear()}enqueue(e,t){const o=this.session;if(!o||"disabled"===this.currentState)return;const r={lts:this.now(),net:this.networkType,appkey:o.appKey,sdkServiceId:o.serviceId,sdkProduct:0,uikitVersion:o.uikitVersion??"",...t},s={eventId:e,body:Object.fromEntries(Object.entries(r).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:o.appKey,wire:s})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let Nt;const It=e=>(Nt?.reset(),Nt=new ht(e),Nt),At=e=>Nt?.startSession(e),ft=e=>{Nt?.updateSession(e)},St=e=>{Nt?.applyDnsSwitch(e)},yt=e=>{Nt?.updateNetworkType(e)},Ct=e=>{if("disabled"!==Nt?.state)return Nt?.startOperation(e)},Mt=()=>{Nt?.reset(),Nt=void 0},gt=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},Dt=()=>ct({fetchImpl:gt()})??{request:e=>Promise.reject(st("Request capability is missing for current platform.",{code:rt.MISSING_CAPABILITY,stage:ot.REQUEST,retryable:!1,details:{capability:"request"}}))},Ut=e=>e??Dt(),Lt=(e,t)=>{if(!e.matchField)return!1;const o=t[e.matchField];return void 0!==e.matchPattern?"string"==typeof o&&o.includes(e.matchPattern):void 0===e.matchValue?void 0!==o:o===e.matchValue||!("string"!=typeof o&&"number"!=typeof o||"string"!=typeof e.matchValue&&"number"!=typeof e.matchValue)&&String(o)===String(e.matchValue)};function bt(e,t,o){if(!e)return;const r=o&&"object"==typeof o?o:{},s="string"==typeof r.error?r.error:void 0,i=(e=>"string"==typeof e.error_code||"number"==typeof e.error_code?e.error_code:"string"==typeof e.errorCode||"number"==typeof e.errorCode?e.errorCode:"string"==typeof e.error||"number"==typeof e.error?e.error:"string"==typeof e.code||"number"==typeof e.code?e.code:void 0)(r),a="string"==typeof r.error_description?r.error_description:"string"==typeof r.message?r.message:"string"==typeof r.desc?r.desc:void 0,n=(e,t=!1)=>{const o=(e,o,r)=>({reasonKey:e,entry:o,matchedBy:t?"common":r});if(s&&e[s])return o(s,e[s],"key");for(const[s,i]of Object.entries(e))if(Lt(i,r))return o(s,i,"field");if(void 0!==i)for(const[r,s]of Object.entries(e)){if(s.code===i||s.canonicalCode===i)return o(r,s,"code");if(Array.isArray(s.aliases)&&s.aliases.includes(String(i)))return o(r,s,"alias")}if(a)for(const[r,s]of Object.entries(e))if(Array.isArray(s.aliases)&&s.aliases.includes(a))return o(r,s,"alias")},p=t?e.apis[t]:void 0,E=p?n(p.errors):void 0;if(E)return E;for(const c of Object.values(e.common)){const e=n(c.errors,!0);if(e)return e}}function Pt(t){const o=t.entry?.code??e.REST_BUSINESS_UNKNOWN,r=t.message??function(e){const t=e.apiName?`${e.apiName} failed`:"request failed";if(e.entry?.runtimeMessage)return`REST business error: ${e.entry.runtimeMessage}`;if(e.mapped??Boolean(e.entry)){if(e.reasonKey){const t=e.reasonKey.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split("_").join(" ").split("-").join(" ").toLowerCase();return`REST business error: ${t.charAt(0).toUpperCase()}${t.slice(1)}`}return`REST business error: ${t}`}return e.reasonKey?`REST business error: ${t} (${e.reasonKey})`:`REST business error: ${t}`}({apiName:t.apiName,entry:t.entry,mapped:t.mapped,reasonKey:t.reasonKey});return new d(r,{code:o,details:{api:t.apiName,serverCode:t.serverCode,serverMessage:t.serverMessage,httpStatus:t.httpStatus,mapped:t.mapped??Boolean(t.entry),reasonKey:t.reasonKey,matchedBy:t.matchedBy,retryable:t.entry?.retryable,canonicalCode:t.entry?.canonicalCode??t.entry?.code}})}const Gt={getHistoryMessages:{operationName:"REST_GET_HISTORY_MESSAGE",operationType:"REST"},removeHistoryMessages:{operationName:"REST_DELETE_MESSAGES_CONVERSATIONS",operationType:"REST"},searchMessages:{operationName:"REST_SEARCH_MESSAGES",operationType:"REST"},addContact:{operationName:"ROSTER_ADD",operationType:"ROSTER"},deleteContact:{operationName:"ROSTER_REMOVE",operationType:"ROSTER"},acceptContactInvite:{operationName:"ROSTER_ACCEPT",operationType:"ROSTER"},declineContactInvite:{operationName:"ROSTER_DECLINE",operationType:"ROSTER"},addUsersToBlocklist:{operationName:"ROSTER_BAN",operationType:"ROSTER"},removeUserFromBlocklist:{operationName:"ROSTER_ALLOW",operationType:"ROSTER"},getBlocklist:{operationName:"ROSTER_BLACKLIST",operationType:"ROSTER"},getContactList:{operationName:"ROSTER_CONTACTS",operationType:"ROSTER"},setContactRemark:{operationName:"ROSTER_SET_CONTACT_REMARK",operationType:"ROSTER"},updateOwnInfo:{operationName:"USER_UPDATE_USERINFO",operationType:"USER"},getUserInfoByUserId:{operationName:"USER_FETCH_USERINFO",operationType:"USER"},uploadPushToken:{operationName:"USER_UPLOAD_PUSH_TOKEN",operationType:"USER"},createGroup:{operationName:"GROUP_CREATEGROUP",operationType:"GROUP"},destroyGroup:{operationName:"GROUP_DESTOTYGROUP",operationType:"GROUP"},leaveGroup:{operationName:"GROUP_LEAVEGROUP",operationType:"GROUP"},joinGroup:{operationName:"GROUP_JOIN_PUBLICGROUP",operationType:"GROUP"},getGroupMemberList:{operationName:"GROUP_FETCH_MEMEBERS",operationType:"GROUP"},uploadGroupSharedFile:{operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"},downloadGroupSharedFile:{operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"},getChatRoomList:{operationName:"CHATROOM_FETCH_CHATROOMSWITHPAGE",operationType:"CHATROOM"},getChatRoomInfo:{operationName:"CHATROOM_FETCH_SPECIFICATION",operationType:"CHATROOM"},joinChatRoom:{operationName:"CHATROOM_JOINCAHTROOM",operationType:"CHATROOM"},leaveChatRoom:{operationName:"CHATROOM_LEAVECAHTROOM",operationType:"CHATROOM"},getConversationList:{operationName:"REST_GET_SESSION_LIST",operationType:"REST"},deleteConversation:{operationName:"REST_DEL_SESSION",operationType:"REST"},setConversationPinned:{operationName:"REST_PIN_CONVERSATION",operationType:"REST"},getPinnedMessageList:{operationName:"REST_FETCH_PINMESSAGES",operationType:"REST"},clearAllMessagesAndConversations:{operationName:"REST_DELETE_MESSAGES_CONVERSATIONS",operationType:"REST"},setPinned:{operationName:"REST_PIN_MESSAGE",operationType:"REST"},getSelfIdsOnOtherPlatform:{operationName:"USER_LOGGEDIN_OTHER_PLATFORM",operationType:"USER"},getJoinedGroupList:{operationName:"GROUP_FETCH_USERS_GROUP",operationType:"GROUP"},changeGroupOwner:{operationName:"GROUP_CHANGE_OWNER",operationType:"GROUP"},getGroupInfo:{operationName:"GROUP_FETCH_SPECIFICATION",operationType:"GROUP"},getGroupInfoList:{operationName:"GROUP_FETCH_SPECIFICATION",operationType:"GROUP"},updateGroupInfo:{operationName:"GROUP_CHANGE_GROUPATTRIBUTE",operationType:"GROUP"},getGroupAdminList:{operationName:"GROUP_GET_ADMIN",operationType:"GROUP"},addGroupAdmin:{operationName:"GROUP_SET_ADMIN",operationType:"GROUP"},removeGroupAdmin:{operationName:"GROUP_REMOVE_ADMIN",operationType:"GROUP"},inviteUsersToGroup:{operationName:"GROUP_INVITE_TO_GROUP",operationType:"GROUP"},acceptGroupJoinRequest:{operationName:"GROUP_ACCEPT_JOINPUBLICGROUPAPPL",operationType:"GROUP"},rejectGroupJoinRequest:{operationName:"GROUP_DECLINE_JOINPUBLICGROUPAPPL",operationType:"GROUP"},acceptInvitation:{operationName:"GROUP_ACCEPT_INVITATION",operationType:"GROUP"},rejectInvitation:{operationName:"GROUP_DECLINE_INVITATION",operationType:"GROUP"},removeGroupMembers:{operationName:"GROUP_REMOVE_MEMBERS",operationType:"GROUP"},muteGroupMembers:{operationName:"GROUP_MUTE_MEMBERS",operationType:"GROUP"},unmuteGroupMembers:{operationName:"GROUP_UNMUTE_MEMBERS",operationType:"GROUP"},getGroupMuteList:{operationName:"GROUP_FETCH_MUTES",operationType:"GROUP"},blockGroupMembers:{operationName:"GROUP_BLOCK_MEMBERS",operationType:"GROUP"},unblockGroupMembers:{operationName:"GROUP_UNBLOCK_MEMBERS",operationType:"GROUP"},getGroupBlocklist:{operationName:"GROUP_GET_BLOCK_LIST",operationType:"GROUP"},muteAllGroupMembers:{operationName:"GROUP_MUTE_ALLMEMBERS",operationType:"GROUP"},unmuteAllGroupMembers:{operationName:"GROUP_UNMUTE_ALLMEMBERS",operationType:"GROUP"},addUsersToGroupAllowlist:{operationName:"GROUP_ADD_WHITELIST",operationType:"GROUP"},removeUsersFromGroupAllowlist:{operationName:"GROUP_REMOVE_WHITELIST",operationType:"GROUP"},getGroupAllowlist:{operationName:"GROUP_FETCH_WHITELIST",operationType:"GROUP"},checkIfInGroupAllowList:{operationName:"GROUP_IS_IN_WHITELIST",operationType:"GROUP"},getGroupMessageReadUsers:{operationName:"GROUP_GET_READ_USERS",operationType:"GROUP"},getGroupAnnouncement:{operationName:"GROUP_FETCH_ANNOUNCEMENT",operationType:"GROUP"},updateGroupAnnouncement:{operationName:"GROUP_UPDATE_ANNOUNCEMENT",operationType:"GROUP"},deleteGroupSharedFile:{operationName:"GROUP_DELETE_SHAREDFILE",operationType:"GROUP"},getGroupSharedFileList:{operationName:"GROUP_FETCH_SHAREDFILE",operationType:"GROUP"},setGroupMemberAttributes:{operationName:"GROUP_MEMBER_SET_META_DATA",operationType:"GROUP"},getGroupMembersAttributes:{operationName:"GROUP_MEMBER_FETCH_META_DATA",operationType:"GROUP"},destroyChatRoom:{operationName:"CHATROOM_DESTORYCHATROOM",operationType:"CHATROOM"},updateChatRoomInfo:{operationName:"CHATROOM_CHANGE_ATTRIBUTE",operationType:"CHATROOM"},removeChatRoomMembers:{operationName:"CHATROOM_REMOVE_MEMBERS",operationType:"CHATROOM"},addChatRoomMembers:{operationName:"CHATROOM_ADD_MEMBERS",operationType:"CHATROOM"},getChatRoomMemberList:{operationName:"CHATROOM_FETCH_MEMBERS",operationType:"CHATROOM"},getChatRoomAdminList:{operationName:"CHATROOM_GET_ADMIN",operationType:"CHATROOM"},setChatRoomAdmin:{operationName:"CHATROOM_SET_ADMIN",operationType:"CHATROOM"},removeChatRoomAdmin:{operationName:"CHATROOM_REMOVE_ADMIN",operationType:"CHATROOM"},muteChatRoomMembers:{operationName:"CHATROOM_MUTE_USER",operationType:"CHATROOM"},unmuteChatRoomMembers:{operationName:"CHATROOM_UNMUTE_USER",operationType:"CHATROOM"},getChatRoomMuteList:{operationName:"CHATROOM_FETCH_MUTES",operationType:"CHATROOM"},blockChatRoomMembers:{operationName:"CHATROOM_BLOCK_USERS",operationType:"CHATROOM"},unblockChatRoomMembers:{operationName:"CHATROOM_UNBLOCK_USERS",operationType:"CHATROOM"},getChatRoomBlocklist:{operationName:"CHATROOM_FETCH_BANS",operationType:"CHATROOM"},muteAllChatRoomMembers:{operationName:"CHATROOM_MUTE_ALLMEMEBERS",operationType:"CHATROOM"},unmuteAllChatRoomMembers:{operationName:"CHATROOM_UNMUTE_ALLMEMEBERS",operationType:"CHATROOM"},addUsersToChatRoomAllowlist:{operationName:"CHATROOM_ADD_WHITELIST",operationType:"CHATROOM"},removeUsersFromChatRoomAllowlist:{operationName:"CHATROOM_REMOVE_WHITELIST",operationType:"CHATROOM"},getChatRoomAllowlist:{operationName:"CHATROOM_FETCH_WHITELIST",operationType:"CHATROOM"},checkIfInChatRoomAllowList:{operationName:"CHATROOM_FETCH_MEMBERIN_WHITELIST",operationType:"CHATROOM"},getChatRoomAnnouncement:{operationName:"CHATROOM_FETCH_ANNOUNCEMENT",operationType:"CHATROOM"},updateChatRoomAnnouncement:{operationName:"CHATROOM_UPDATE_ANNOUNCEMENT",operationType:"CHATROOM"},deleteChatRoomSharedFile:{operationName:"CHATROOM_REMOVE_SHARE_FILE",operationType:"CHATROOM"},getChatRoomSharedFileList:{operationName:"CHATROOM_GET_SHARE_FILE_LIST",operationType:"CHATROOM"},setChatRoomAttributes:{operationName:"CHATROOM_SET_META_DATA",operationType:"CHATROOM"},removeChatRoomAttributes:{operationName:"CHATROOM_DELETE_META_DATA",operationType:"CHATROOM"},getChatRoomAttributes:{operationName:"CHATROOM_FETCH_META_DATA",operationType:"CHATROOM"}},Ht=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();class wt{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=Ut(t?.requestAdapter),this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),o=t.searchParams;for(const e of o.keys())o.set(e,"***");const r=o.toString(),s=r?`?${r}`:"";return`${t.origin}${t.pathname}${s}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(t,o,r,s){const i={...o.operation?{api:o.operation}:{},url:o.url,method:o.method,httpStatus:t,serverCode:r,serverMessage:s,mapped:!1};if(400===t)return new p("Invalid request parameters",{code:e.VALIDATION_UNKNOWN,details:{...i,canonicalCode:e.VALIDATION_UNKNOWN}});if(401===t){const t=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),o=t?e.AUTH_TOKEN_EXPIRED:e.AUTH_UNAUTHORIZED;return new n(t?"Authentication token expired":"Authentication failed",{code:o,details:{...i,reasonKey:t?"token_expired":"unauthorized",canonicalCode:o}})}return 403===t?new n("Access forbidden",{code:e.AUTH_FORBIDDEN,details:{...i,canonicalCode:e.AUTH_FORBIDDEN}}):429===t?new d("REST rate limit exceeded",{code:e.SERVICE_LIMIT_EXCEEDED,details:{...i,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:e.SERVICE_LIMIT_EXCEEDED}}):t>=500?new d("REST business error: request failed",{code:e.REST_BUSINESS_UNKNOWN,details:{...i,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:e.REST_BUSINESS_UNKNOWN}}):void 0}async request(t,o={}){const r=`${this.baseUrl}${t}`,i=o.method??"GET",a=Date.now(),n=this.sanitizeUrl(r);Ze.debug("REST request",{method:i,url:n,operation:o.operation});const p=o.operation?(e=>{const t=Gt[e];if(t)return t;const o=(e=>{const t=e.toLowerCase();return t.includes("chatroom")||t.includes("chat_room")?"CHATROOM":t.includes("group")?"GROUP":t.includes("contact")||t.includes("blocklist")?"ROSTER":t.includes("userinfo")||t.includes("presence")?"USER":"REST"})(e);return{operationName:`REST_${Ht(e)}`,operationType:o}})(o.operation):void 0,E=p?Ct(p):void 0,c=E?.startRequest({requestName:p?.operationName,method:i,url:r});let T=0;const d={...this.defaultHeaders,...o.headers};if(this.includeRequestId&&(d[ut]=Tt()),o.body&&"GET"!==i){const e=Object.keys(d).some(e=>"content-type"===e.toLowerCase());"string"==typeof o.body?e||(d["Content-Type"]="application/x-www-form-urlencoded"):e||(d["Content-Type"]="application/json")}else if("GET"===i)for(const e of Object.keys(d))"content-type"===e.toLowerCase()&&delete d[e];try{const e=await this.requestAdapter.request({url:r,method:i,headers:d,body:o.body,timeoutMs:o.timeout??this.timeout});T=e.status;const t=((e,t)=>{if("string"!=typeof e)return e;const o=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),r=e.trim();if(!(o?.[1].includes("application/json")||r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]")))return e;try{return JSON.parse(r)}catch{return e}})(e.data,e.headers),s=Date.now()-a;(e.status<200||e.status>=300)&&(Ze.warn("REST response error",{method:i,url:n,status:e.status,duration:s}),this.handleErrorPayload(e.status,e.statusText??"",t,{operation:o.operation,url:r,method:i})),Ze.debug("REST response",{method:i,url:n,status:e.status,duration:s});const p=(e=>{if(Array.isArray(e))return e.length;if(!e||"object"!=typeof e)return;const t=e;for(const o of["entities","data","items","messages","conversations","results"]){const e=t[o];if(Array.isArray(e))return e.length}})(t);return c?.finish({code:e.status,success:!0,resultCount:p}),E?.finish({code:0,success:!0,resultCount:p}),t}catch(l){const t=0!==T?T:l instanceof s?l.code:-1,a=l instanceof Error?l.message:String(l);if(c?.finish({code:t,success:!1,description:a}),E?.finish({code:t,success:!1,description:a}),l instanceof s)throw l;const p=(e=>{if(!e||"object"!=typeof e)return;const t=e.details;if(!t||"object"!=typeof t)return;const o=t.reason;return"abort"===o||"network"===o||"timeout"===o?o:void 0})(l);if(l instanceof Error&&"AbortError"===l.name||"timeout"===p)throw Ze.warn("REST request timeout",{method:i,url:n,timeout:o.timeout??this.timeout}),new u(`Request timeout: ${r}`,{code:e.REST_TIMEOUT,details:{url:r,method:i,timeout:o.timeout??this.timeout}});throw Ze.warn("REST request failed",{method:i,url:n}),new u(`Request failed: ${r}`,{code:e.REST_NETWORK_ERROR,details:{url:r,method:i,...p?{reason:p}:{}}})}}handleErrorPayload(t,o,r,s){const i=r&&"object"==typeof r?r:{},a=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const o=e.error,r=o.code;if("number"!=typeof r&&"string"!=typeof r)return;const s=String(r);return/^\d{7}$/.test(s)&&Number(s.slice(0,3))===t?o:void 0})(i,t),n=a?{...i,code:a.code,message:a.message}:r,p=bt(this.errorMap,s.operation,n),E="string"==typeof i.error?i.error:void 0,c="number"==typeof i.error_code||"string"==typeof i.error_code?i.error_code:"number"==typeof i.errorCode||"string"==typeof i.errorCode?i.errorCode:"number"==typeof i.code||"string"==typeof i.code?i.code:"string"==typeof i.error?i.error:"number"==typeof a?.code||"string"==typeof a?.code?a.code:void 0,T="string"==typeof i.message?i.message:"string"==typeof i.error_description?i.error_description:"string"==typeof i.desc?i.desc:"string"==typeof a?.message?a.message:void 0,d=!!(401!==t&&403!==t||void 0!==E&&"unauthorized"!==E&&"auth_failed"!==E&&"forbidden"!==E)&&(void 0!==E||"string"==typeof i.error_description||"string"==typeof i.message||"string"==typeof i.desc);if(s.operation&&p)throw Pt({apiName:s.operation,entry:p.entry,serverCode:c,serverMessage:T,httpStatus:t,mapped:!0,reasonKey:p.reasonKey,matchedBy:p.matchedBy});const l=this.buildHttpStatusFallbackError(t,s,c,T);if(l)throw l;if(s.operation&&d)throw Pt({apiName:s.operation,serverCode:c,serverMessage:T,httpStatus:t,mapped:!1,reasonKey:E});throw new u(`HTTP ${t}: ${o}`,{code:e.REST_HTTP_ERROR,details:{url:s.url,method:s.method,httpStatus:t}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,o){return this.request(e,{...o,method:"POST",body:t})}put(e,t,o){return this.request(e,{...o,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,o){return this.request(e,{...o,method:"PATCH",body:t})}}const vt=(...e)=>{const t={},o={};for(const r of e)Object.assign(t,r.common),Object.assign(o,r.apis);return{common:t,apis:o}},Ft={common:{validation:{range:"100-110",errors:{MISSING_REQUIRED:{code:110},INVALID_FORMAT:{code:110},UNKNOWN:{code:110}}},auth:{range:"108,200-215",errors:{ALREADY_LOGIN:{code:200},NOT_LOGIN:{code:201},UNAUTHORIZED:{code:202},FORBIDDEN:{code:210},TOKEN_EXPIRED:{code:108},BIND_ANOTHER_DEVICE:{code:213},LOGIN_TOO_MANY_DEVICES:{code:214},USER_MUTED:{code:215}}},connection:{range:"1,100,202,300-304",errors:{TIMEOUT:{code:301},LOGIN_TIMEOUT:{code:301},WEBSOCKET_ERROR:{code:300},NOT_CREATED:{code:1},CLOSED_BEFORE_READY:{code:300},CANCELLED:{code:1},PROVISION_TIMEOUT:{code:301},PROVISION_REJECTED:{code:202},PROVISION_CLOSED:{code:300},DNSLIST_FAILED:{code:304},SERVER_BUSY:{code:302}}},storage:{range:"3",errors:{OPERATION_FAILED:{code:3}}},message:{range:"1,300-511",errors:{NOT_CONNECTED:{code:300},ACK_TIMEOUT:{code:301},SEND_FAILED:{code:303},SENDER_DESTROYED:{code:1},ENCODE_FAILED:{code:500},DECODE_FAILED:{code:500},ACK_MISSING:{code:301}}},transport:{range:"2,301,303",errors:{NETWORK_ERROR:{code:2},TIMEOUT:{code:301},HTTP_ERROR:{code:303},BUSINESS_UNKNOWN:{code:303}}},upload:{range:"1,100,110,301,402,405",errors:{REQUIRED_FIELD_MISSING:{code:110},INVALID_APPKEY:{code:100},SIZE_EXCEEDED:{code:405},REQUEST_FAILED:{code:402},TIMEOUT:{code:301},ABORTED:{code:1}}},unknown:{range:"1,4",errors:{UNKNOWN:{code:1},SERVICE_LIMIT_EXCEEDED:{code:4}}},push:{range:"1500,1501,1502",errors:{TOKEN_UPLOAD_FAILED:{code:1500},SILENT_MODE_OPERATION_FAILED:{code:1501},PUSH_LANGUAGE_OPERATION_FAILED:{code:1502}}},chatroom:{range:"700-707",errors:{CHATROOM_INVALID_ID:{code:700},CHATROOM_NOT_JOINED:{code:702},CHATROOM_PERMISSION_DENIED:{code:703},CHATROOM_MEMBERS_FULL:{code:704},CHATROOM_NOT_EXIST:{code:705},CHATROOM_OWNER_NOT_ALLOW_LEAVE:{code:706},CHATROOM_USER_IN_BLOCKLIST:{code:707}}}},apis:{}};export{be as $,n as A,Ct as B,a as C,c as D,e as E,_ as F,dt as G,M as H,le as I,Ut as J,pe as K,ce as L,E as M,i as N,Ae as O,rt as P,ge as Q,d as R,s as S,Le as T,l as U,p as V,h as W,Ee as X,he as Y,Re as Z,_e as _,ot as a,Se as a0,ye as a1,Ce as a2,F as a3,T as a4,b as a5,v as a6,P as a7,o as a8,H as a9,Z as aA,ze as aB,je as aC,xe as aD,O as aE,bt as aF,I as aG,N as aH,W as aI,z as aJ,Y as aK,J as aL,X as aM,Q as aN,G as aa,w as ab,y as ac,C as ad,m as ae,q as af,K as ag,x as ah,$ as ai,j as aj,V as ak,k as al,B as am,S as an,It as ao,At as ap,yt as aq,We as ar,ft as as,St as at,Mt as au,Ye as av,Xe as aw,Je as ax,Qe as ay,R as az,fe as b,Pt as c,Me as d,ut as e,Tt as f,nt as g,wt as h,u as i,Ft as j,et as k,Ze as l,vt as m,ne as n,st as o,me as p,it as q,ct as r,Ue as s,De as t,A as u,L as v,U as w,D as x,g as y,f as z};
|
|
1
|
+
const e={VALIDATION_REQUIRED:110,VALIDATION_INVALID_FORMAT:110,VALIDATION_UNKNOWN:110,AUTH_ALREADY_LOGIN:200,AUTH_NOT_LOGIN:201,AUTH_UNAUTHORIZED:202,AUTH_FORBIDDEN:210,AUTH_TOKEN_EXPIRED:108,AUTH_BIND_ANOTHER_DEVICE:213,AUTH_LOGIN_TOO_MANY_DEVICES:214,AUTH_USER_MUTED:215,CONNECTION_TIMEOUT:301,CONNECTION_LOGIN_TIMEOUT:301,CONNECTION_WEBSOCKET_ERROR:300,CONNECTION_NOT_CREATED:1,CONNECTION_CLOSED_BEFORE_READY:300,CONNECTION_CANCELLED:1,CONNECTION_PROVISION_TIMEOUT:301,CONNECTION_PROVISION_REJECTED:202,CONNECTION_PROVISION_CLOSED:300,CONNECTION_DNSLIST_FAILED:304,STORAGE_OPERATION_FAILED:3,MESSAGE_NOT_CONNECTED:300,MESSAGE_ACK_TIMEOUT:301,MESSAGE_SEND_FAILED:303,MESSAGE_SENDER_DESTROYED:1,MESSAGE_ENCODE_FAILED:500,MESSAGE_DECODE_FAILED:500,MESSAGE_ACK_MISSING:301,MESSAGE_BLOCKED_BY_RECIPIENT:222,OPERATION_UNSUPPORTED:111,SERVER_BUSY:302,ATTACHMENT_NOT_FOUND:400,ATTACHMENT_INVALID:401,ATTACHMENT_EXPIRED:407,MESSAGE_INCLUDE_ILLEGAL_CONTENT:501,MESSAGE_SEND_TRAFFIC_LIMIT:502,MESSAGE_RECALL_TIME_LIMIT:504,SERVICE_NOT_ENABLED:505,MESSAGE_EXPIRED:506,MESSAGE_ILLEGAL_WHITELIST:507,MESSAGE_EXTERNAL_LOGIC_BLOCKED:508,MESSAGE_CURRENT_LIMITING:509,MESSAGE_SIZE_LIMIT:510,MESSAGE_EDIT_FAILED:511,INVALID_CONVERSATION:107,USER_LOGIN_ANOTHER_DEVICE:206,USER_REMOVED:207,USER_KICKED_BY_CHANGE_PASSWORD:216,USER_KICKED_BY_OTHER_DEVICE:217,USER_ALREADY_LOGIN_ANOTHER:218,USER_MUTED_BY_ADMIN:219,USER_DEVICE_CHANGED:220,USER_NOT_ON_ROSTER:221,SERVER_SERVING_DISABLED:305,FILE_DOWNLOAD_FAILED:403,FILE_TOO_LARGE:405,FILE_CONTENT_IMPROPER:406,THIRD_MODERATION_FAILED:1200,THIRD_DEFAULT_FAILED:1299,STREAM_SEND_NOT_SUPPORTED:303,STREAM_CHUNK_INVALID:500,STREAM_TIMEOUT_BY_SERVER:500,STREAM_STATE_CONFLICT:500,COMBINE_INVALID_INPUT:110,COMBINE_LEVEL_EXCEEDED:4,COMBINE_ITEM_LIMIT_EXCEEDED:4,COMBINE_ENCODE_FAILED:500,COMBINE_UPLOAD_FAILED:402,COMBINE_DOWNLOAD_FAILED:2,COMBINE_PARSE_FAILED:500,REST_NETWORK_ERROR:2,REST_TIMEOUT:301,REST_HTTP_ERROR:303,REST_BUSINESS_UNKNOWN:303,PUSH_TOKEN_UPLOAD_FAILED:1500,PUSH_SILENT_MODE_OPERATION_FAILED:1501,PUSH_LANGUAGE_OPERATION_FAILED:1502,USER_INFO_SUBSCRIPTION_LIMIT_EXCEEDED:1600,USER_INFO_SUBSCRIPTION_TARGET_LIMIT_EXCEEDED:1601,USERINFO_USERCOUNT_EXCEED:900,USERINFO_DATALENGTH_EXCEED:901,CONTACT_ADD_USER_NOT_FOUND:204,CONTACT_ADD_ALREADY_FRIEND:1e3,CONTACT_ADD_BLOCKED_BY_USER:210,CONTACT_SET_REMARK_NOT_FRIEND:223,CONTACT_REACH_LIMIT:1001,CONTACT_REACH_LIMIT_PEER:1002,CONTACT_BLOCKLIST_USER_NOT_FOUND:204,GROUP_INVALID_ID:600,GROUP_ALREADY_JOINED:601,GROUP_NOT_JOINED:602,GROUP_PERMISSION_DENIED:603,GROUP_MEMBERS_FULL:604,GROUP_SHARED_FILE_INVALID_ID:605,GROUP_NOT_EXIST:606,GROUP_DISABLED:607,GROUP_NAME_VIOLATION:608,GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT:609,GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED:610,GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT:611,GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT:612,GROUP_USER_IN_BLOCKLIST:613,CHATROOM_INVALID_ID:700,CHATROOM_NOT_JOINED:702,CHATROOM_PERMISSION_DENIED:703,CHATROOM_MEMBERS_FULL:704,CHATROOM_NOT_EXIST:705,CHATROOM_OWNER_NOT_ALLOW_LEAVE:706,CHATROOM_USER_IN_BLOCKLIST:707,CONTACT_SYNC_METADATA_FAILED:1700,CONTACT_SYNC_SOCKET_FAILED:1701,CONTACT_SYNC_CURSOR_INVALID:1702,CONTACT_SYNC_PROTO_DECODE_FAILED:1703,CONTACT_SYNC_CANCELLED:1704,SESSION_LIST_SOCKET_FAILED:300,SESSION_LIST_PROTO_DECODE_FAILED:500,SESSION_LIST_REQUEST_INVALID:110,SESSION_LIST_FETCH_FAILED:303,SESSION_LIST_SERVICE_DISABLED:305,SESSION_LIST_CANCELLED:1,PRESENCE_PARAM_LENGTH_EXCEED:1100,PRESENCE_CANNOT_SUBSCRIBE_YOURSELF:1101,TRANSLATE_PARAM_INVALID:1110,TRANSLATE_SERVICE_NOT_ENABLED:1111,TRANSLATE_USAGE_LIMIT:1112,TRANSLATE_FAILED:1113,VOICE_TO_TEXT_FILE_INVALID:407,VOICE_TO_TEXT_FILE_DURATION_TOO_LONG:408,VOICE_TO_TEXT_FAILED:409,VOICE_TO_TEXT_FILE_NOT_FOUND:410,VOICE_TO_TEXT_FILE_TOO_LARGE:411,REACTION_REACH_LIMIT:1300,REACTION_ALREADY_OPERATED:1301,REACTION_OPERATION_ILLEGAL:1302,UPLOAD_REQUIRED_FIELD_MISSING:110,UPLOAD_INVALID_APPKEY:100,UPLOAD_SIZE_EXCEEDED:405,UPLOAD_REQUEST_FAILED:402,UPLOAD_TIMEOUT:301,UPLOAD_ABORTED:1,SERVICE_LIMIT_EXCEEDED:4,UNKNOWN:1},t="[REDACTED]",o=e=>{if(!e)return"";const o=e.includes("?"),r=e.includes("#");try{return((e,o,r)=>(e.username&&(e.username=t),e.password&&(e.password=t),e.search=o?`?${t}`:"",e.hash=r?`#${t}`:"",e.toString()))(new URL(e),o,r)}catch{const o=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===o?"[invalid-url]":`${e.slice(0,o)}?${t}`}},r=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,o(t)]:[e,t]));class s extends Error{constructor(t,o=e.UNKNOWN,i){super(t),this.name="SDKError",this.code=o,this.details=i?.details?r(i.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,s)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class i extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="NetworkError"}}class a extends s{constructor(t,o){super(t,o?.code??e.CONNECTION_WEBSOCKET_ERROR,o),this.name="ConnectionError"}}class n extends s{constructor(t,o){super(t,o?.code??e.AUTH_UNAUTHORIZED,o),this.name="AuthenticationError"}}class p extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class E extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_SEND_FAILED,o),this.name="MessageSendError"}}class c extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_DECODE_FAILED,o),this.name="MessageReceiveError"}}class T extends s{constructor(t,o){super(t,o?.code??e.STORAGE_OPERATION_FAILED,o),this.name="StorageError"}}class u extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="RestTransportError"}}class d extends s{constructor(t,o){super(t,o?.code??e.REST_BUSINESS_UNKNOWN,o),this.name="RestBusinessError"}}class l extends s{constructor(t,o){super(t,o?.code??e.UPLOAD_REQUEST_FAILED,o),this.name="UploadError"}}function O(e){if(e instanceof s)return!0;if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&"string"==typeof t.message&&"number"==typeof t.code&&"function"==typeof t.toJSON}const _=15e3,R=1e4,m=15e3,h=3e5,N=6e4,I=3e5,A=1e4,f=1e4,S=3e4,y=5e3,C=12e4,M=3e4,g=6e4,D=1e3,U=6e4,L=2,b=5e3,P=1e4,G=1e3,H=5e3,w=2,v=0,F=2e4,B=7e3,k=20,K=3,q=1,V=7e3,$=1e3,x=50,j=5,z=5e3,W=2,Y=[1e3,2e3],X=2500,J=1,Q=500,Z=6e3,ee={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",heic:"image/heic",heif:"image/heif",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",mp3:"audio/mpeg",m4a:"audio/mp4",wav:"audio/wav",aac:"audio/aac",amr:"audio/amr",pdf:"application/pdf",txt:"text/plain",json:"application/json"},te=e=>"undefined"!=typeof Blob&&e instanceof Blob,oe=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),o=t.length>0?t[t.length-1]:void 0;if(o)return o},re=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const o=e.slice(t+1).toLowerCase();return ee[o]},se=(e,t)=>{for(const o of t){const t=e[o];if("string"==typeof t&&t.length>0)return t}},ie=e=>{const t=e.file,o=e.sourceMeta,r=t.name||(o?se(o,["name","fileName","filename"]):void 0),s=e.file.type||(o?se(o,["type","mimeType","filetype"]):void 0),i=e.file.size||(o?((e,t)=>{for(const o of t){const t=e[o];if("number"==typeof t&&Number.isFinite(t))return t}})(o,["size","fileSize","fileLength"]):void 0),a=ae({fileName:r,fileType:s,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize,webFile:e.file}},ae=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),ne=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(te(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const o of["file","originFileObj","raw","blob"]){const e=t[o];if(te(e))return e}})(t);if(i)return ie({file:i,fallbackName:o,fallbackMimeType:r,fallbackSize:s,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=oe(t.path),i=ae({fileName:t.name??e,fileType:t.type??re(t.name??e),fileSize:t.size,fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"miniapp-path",path:t.path,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}if((e=>"object"==typeof e&&null!==e&&"uri"in e)(t)){const e=oe(t.uri),i=ae({fileName:t.name??e,fileType:t.type??re(t.name??e),fileSize:t.size,fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"rn-uri",uri:t.uri,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}const a=ae({fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"web-file",name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize}},pe=5242880,Ee=5242880,ce=4,Te="CHAT",ue="GROUP",de="ROOM",le="original",Oe="large",_e=e=>/^https?:\/\//i.test(e),Re=(e,t)=>!!t||(!e||!_e(e)),me=t=>{const o=t.split("#");if(2!==o.length||!o[0]||!o[1])throw new l("Invalid appKey for upload",{code:e.UPLOAD_INVALID_APPKEY,details:{appKey:t}});return{orgName:o[0],appName:o[1]}},he=e=>"singleChat"===e?Te:"groupChat"===e?ue:de,Ne=(e,t)=>Ae(e,{size:t}),Ie=e=>{try{return decodeURIComponent(e)}catch{return e}},Ae=(e,t)=>{const[o="",r]=e.split("#",2),[s,i=""]=o.split("?",2),a=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const o=encodeURIComponent(e),r=a.filter(t=>{const[r=""]=t.split("=",2);return r!==o&&Ie(r)!==e});a.length=0,a.push(...r),void 0!==t&&a.push(`${o}=${encodeURIComponent(String(t))}`)}),`${s}${a.length>0?`?${a.join("&")}`:""}${r?`#${r}`:""}`},fe=(e,t)=>{if(!e)return"";const o={};return e.includes("em-redirect")||(o["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(o["share-secret"]=t),0===Object.keys(o).length?e:Ae(e,o)},Se=e=>e.isGif?{resolvedImageType:le,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:le,reason:"explicit-original"}:{resolvedImageType:Oe,reason:"default-large"},ye=e=>{const t=(o=e.messageType,r=e.imageType,"image"!==o?"attachment":r===le?"image-origin":"image-big");var o,r;const s=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>s;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:s,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},Ce=t=>{const o=t.entities?.[0],r=!0===o?.exists,s="string"==typeof o?.uuid&&o.uuid.length>0?o.uuid:void 0,i=o,a=i?.["exists-type"]??i?.existsType,n="origin"===a?le:a===Oe||a===le?a:void 0,p="string"==typeof o?.["share-secret"]?o["share-secret"]:void 0;if(r&&!s)throw new l("Upload precheck response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{uuid:s,exists:r,existsType:n,shareSecret:p,hit:(E={exists:r,uuid:s},E.exists&&"string"==typeof E.uuid&&E.uuid.length>0)};var E},Me=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const o=(e=>{const[t="",o]=e.split("#",2),[r,s=""]=t.split("?",2),i=s.split("&").filter(Boolean).filter(e=>{const[t="",o=""]=e.split("=",2),r=Ie(t),s=Ie(o);return"size"!==r||!["big","large","thumbnail","small"].includes(s)}).join("&");return`${r}${i?`?${i}`:""}${o?`#${o}`:""}`})(e);return{originalImageUrl:o,bigImageUrl:Ne(o,"large"),thumbnailUrl:Ne(o,"small")}},ge=e=>e===le?"origin":"large",De=e=>e===le?1:2,Ue=e=>2===e?Oe:le,Le=t=>{const o=t.response.entities?.[0];if(!o?.uuid)throw new l("Upload response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t.response}});const r=o["share-secret"],s=o["file-metadata"]??{},i="number"==typeof s["content-length"]?s["content-length"]:t.fallbackSize,a="string"==typeof s["content-type"]?s["content-type"]:t.fileType,n=`${t.restBaseUrl}/${t.orgName}/${t.appName}/chatfiles/${o.uuid}`;if("image"===t.messageType){const e=(t.imageType??Oe)===le;return{...Me(n,{deriveVariants:!t.useCustomAttachmentUpload}),isOriginalImage:e,secret:r,fileLength:i,filetype:a,filename:t.fileName,width:t.width,height:t.height}}const p="video"===t.messageType?`${n}?vframe=true`:void 0;return{url:n,secret:r,fileLength:i,filetype:a,filename:t.fileName,thumbnailUrl:p}},be=(t,o)=>{if(!t)throw new l("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"file missing"}});const r=("number"==typeof o.fileLength?o.fileLength:void 0)??("fileSize"in o&&"number"==typeof o.fileSize?o.fileSize:void 0),s=ne({file:t,fallbackName:o.filename,fallbackMimeType:o.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new l("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s},Pe=e=>new Promise(t=>{setTimeout(t,e)});const Ge=new class{constructor(e){this.state="disabled",this.timerId=null,this.reporting=!1,this.context={},this.buffer=[],this.bufferBytes=0,this.reportIntervalMs=this.normalizeReportInterval(e?.reportIntervalMs),this.reportTimeoutMs=e?.reportTimeoutMs??15e3,this.chunkDelayMs=e?.chunkDelayMs??3e3,this.maxChunkBytes=e?.maxChunkBytes??2097152,this.maxBufferBytes=e?.maxBufferBytes??3145728}setEnabled(e){this.setState(e?"enabled":"disabled")}setState(e){this.state=e,"enabled"!==e?(this.stop(),this.clearBuffer()):this.start()}updateContext(e){this.context={...this.context,...e}}updateReportInterval(e){this.reportIntervalMs=this.normalizeReportInterval(e),"enabled"===this.state&&this.start()}append(e){if("disabled"===this.state)return;const t=this.formatEntry(e);this.pushBuffer(t)}async reportNow(){await this.reportLogs()}stop(){this.timerId&&(clearInterval(this.timerId),this.timerId=null)}clearBuffer(){this.buffer=[],this.bufferBytes=0}start(){this.stop(),this.timerId=setInterval(()=>{this.reportLogs()},this.reportIntervalMs)}normalizeReportInterval(e){const t=void 0!==e&&Number.isFinite(e)&&e>0?e:3e5;return Math.max(t,6e4)}canReport(){return Boolean(this.context.restBaseUrl&&this.context.appKey&&this.context.userId&&this.context.token&&this.context.requestAdapter)}formatEntry(e){const t=e.args.length>0?e.args.map(e=>(e=>{if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}})(e)).join(" "):"",o=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${o}`}pushBuffer(e){const t=e.length;if(!(t>=this.maxBufferBytes)){for(;this.bufferBytes+t>this.maxBufferBytes&&this.buffer.length>0;){const e=this.buffer.shift();e&&(this.bufferBytes-=e.length)}this.buffer.push(e),this.bufferBytes+=t}}consumeBuffer(){if(0===this.buffer.length)return[];const e=`${this.buffer.join("\n")}\n`;this.clearBuffer();const t=[];let o=e;for(;o.length>this.maxChunkBytes;)t.push(o.slice(0,this.maxChunkBytes)),o=o.slice(this.maxChunkBytes);return o.length>0&&t.push(o),t}requeueChunk(e){this.pushBuffer(e)}async reportLogs(){if("enabled"===this.state&&!this.reporting&&0!==this.buffer.length){this.reporting=!0;try{const e=this.consumeBuffer();if(0===e.length)return;if(!this.canReport())return void e.forEach(e=>this.requeueChunk(e));for(const t of e){await this.reportChunk(t)||this.requeueChunk(t),await Pe(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:o,userId:r,token:s,resource:i,requestAdapter:a}=this.context;if(!(t&&o&&r&&s&&a))return!1;let n="",p="";try{const e=me(o);n=e.orgName,p=e.appName}catch{return!1}const E=`${t}/${n}/${p}/sdk/users/${r}/client/logs`,c={resource:i??"webim",logContent:e};try{const e=await a.request({url:E,method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body:c,responseType:"json",timeoutMs:this.reportTimeoutMs});if(e.status<200||e.status>=300)return!1;const t="string"==typeof e.data?(e=>{try{return JSON.parse(e)}catch{return}})(e.data):e.data;return!t||!t.status||"ok"===t.status}catch{return!1}}},He="[MASKED]",we=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),ve=e=>!!e&&we.has((e=>e.toLowerCase())(e)),Fe=(e,t,o)=>{const r=o??/* @__PURE__ */new WeakSet;if("string"==typeof e)return((e,t)=>ve(t)?He:e)(e,t);if("number"==typeof e||"boolean"==typeof e||null==e)return e;if("bigint"==typeof e||"symbol"==typeof e)return e.toString();if("function"==typeof e)return`[Function ${e.name||"anonymous"}]`;if(e instanceof Error)return{name:(s=e).name,message:s.message};var s;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>Fe(e,void 0,r));if("object"==typeof e){if(r.has(e))return"[Circular]";if(r.add(e),(e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Date||e instanceof Error))(e)){const t={};for(const[o,s]of Object.entries(e))ve(o)?t[o]=He:t[o]=Fe(s,o,r);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},Be="undefined"!=typeof document;let ke=null,Ke=!1;const qe={DEBUG:0,WARN:1,ERROR:2};class Ve{constructor(e="WARN"){this.consoleEnabled=!0,this.level=e}setLevel(e){this.level=e}setConsoleEnabled(e){this.consoleEnabled=e}shouldLog(e){return qe[e]>=qe[this.level]}emit(e,t,o){const r=(e=>{const t=/* @__PURE__ */new WeakSet;return e.map(e=>Fe(e,void 0,t))})(o),s=((e,t,o)=>({timestamp:/* @__PURE__ */(new Date).toISOString(),level:e,message:t,args:o}))(e,t,r);if(Ge.append(s),this.consoleEnabled){const o=/* @__PURE__ */new Date,s=`[Chat][${e}][${`${String(o.getHours()).padStart(2,"0")}:${String(o.getMinutes()).padStart(2,"0")}:${String(o.getSeconds()).padStart(2,"0")}.${String(o.getMilliseconds()).padStart(3,"0")}`}]`;Be?console.log(`%c${s}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(s,t,...r)}const i=ke;i&&!Ke&&Promise.resolve().then(()=>{if(i===ke){Ke=!0;try{i(s)}catch{}finally{Ke=!1}}})}debug(e,...t){this.shouldLog("DEBUG")&&this.emit("DEBUG",e,t)}warn(e,...t){this.shouldLog("WARN")&&this.emit("WARN",e,t)}error(e,...t){this.shouldLog("ERROR")&&this.emit("ERROR",e,t)}}let $e=new Ve;function xe(e){$e instanceof Ve&&$e.setLevel(e)}function je(e){$e instanceof Ve&&$e.setConsoleEnabled(e)}function ze(e){ke=e}function We(e){Ge.setState(e)}function Ye(e){Ge.updateContext(e)}function Xe(e){Ge.updateReportInterval(e)}async function Je(){await Ge.reportNow()}function Qe(){Ge.stop()}const Ze={debug:(e,...t)=>$e.debug(e,...t),warn:(e,...t)=>$e.warn(e,...t),error:(e,...t)=>$e.error(e,...t)},et={WEB:"web",WECHAT_MINIAPP:"wechat-miniapp",QQ_MINIAPP:"qq-miniapp",TOUTIAO_MINIAPP:"toutiao-miniapp",BAIDU_MINIAPP:"baidu-miniapp",ALIPAY_MINIAPP:"alipay-miniapp",DINGTALK_MINIAPP:"dingtalk-miniapp",LARK_MINIAPP:"lark-miniapp",KUAISHOU_MINIAPP:"kuaishou-miniapp",JD_MINIAPP:"jd-miniapp",MINIAPP_360:"360-miniapp",HARMONY_MINIAPP:"harmony-miniapp",QUICKAPP:"quickapp",UNIAPP:"uniapp",REACT_NATIVE:"react-native",ELECTRON_RENDERER:"electron-renderer",ELECTRON_MAIN:"electron-main",UNKNOWN:"unknown"},ot={INIT:"init",REQUEST:"request",UPLOAD:"upload",SOCKET:"socket",PROTO:"proto",RUNTIME:"runtime",STORAGE:"storage"},rt={INIT_FAILED:"PLATFORM_INIT_FAILED",MISSING_CAPABILITY:"PLATFORM_MISSING_CAPABILITY",REQUEST_FAILED:"PLATFORM_REQUEST_FAILED",UPLOAD_FAILED:"PLATFORM_UPLOAD_FAILED",SOCKET_FAILED:"PLATFORM_SOCKET_FAILED",PROTO_FAILED:"PLATFORM_PROTO_FAILED"},st=(e,t)=>{const o=new Error(e);return o.name="PlatformAdapterError",o.code=t.code,o.stage=t.stage,o.retryable=t.retryable,t.details&&(o.details=r(t.details)),o},it={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},at=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],nt=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const o={},r=e;for(const s of at)try{const e=r[s];void 0!==e&&(o[s]=e)}catch{}for(const s of Object.keys(t))o[s]=t[s];return o})("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,{..."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}:{}})},pt=e=>{const t={};if(!e)return t;if("function"==typeof e.forEach)return e.forEach((e,o)=>{t[o]=e}),t;const o=e.get?.("content-type");return o&&(t["content-type"]=o),t},Et=async(e,t)=>{const o=e;if("function"!=typeof o.text){if("function"!=typeof o.json)return"";const e=await o.json();return t?e:JSON.stringify(e)}const r=await o.text();if(!t||0===r.length)return r;try{return JSON.parse(r)}catch{return r}},ct=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(o){const r=o.method??"GET",s={...o.headers??{}},i=new AbortController,a=o.timeoutMs??e?.timeoutMs??15e3;let n=!1;const p=()=>i.abort(o.signal?.reason);o.signal?.aborted?p():o.signal?.addEventListener("abort",p,{once:!0});const E=setTimeout(()=>{n=!0,i.abort()},a),c=((e,t,o)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==o)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(o,s,r);try{const e=await t(o.url,{method:r,headers:s,body:c,signal:i.signal});let a;if("arraybuffer"===o.responseType)a=await e.arrayBuffer();else if("text"===o.responseType)a=await e.text();else if("json"===o.responseType)a=await Et(e,!0);else{const t=e.headers.get("content-type")??"";a=await Et(e,t.includes("application/json"))}return{status:e.status,statusText:e.statusText,headers:pt(e.headers),data:a}}catch(T){const e=((e,t,o)=>t?"timeout":o?.aborted||e instanceof Error&&"AbortError"===e.name?"abort":"network")(T,n,o.signal);throw st("Request adapter execution failed.",{code:rt.REQUEST_FAILED,stage:ot.REQUEST,retryable:"abort"!==e,details:{url:o.url,method:r,reason:e,cause:T instanceof Error?T.message:String(T)}})}finally{clearTimeout(E),o.signal?.removeEventListener("abort",p)}}}},Tt=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,ut="X-Request-Id",dt=1e3,lt="direct";class Ot{constructor(e){this.events=[],this.enabled=!1,this.acceptedInWindow=0,this.capacityDiagnosticEmitted=!1,this.rateDiagnosticEmitted=!1,this.sendBatch=e.send,this.capacity=e.capacity??1e3,this.batchSize=e.batchSize??10,this.rateLimit=e.rateLimit??1e3,this.flushIntervalMs=e.flushIntervalMs??1e3,this.now=e.now??Date.now,this.onDrop=e.onDrop,this.windowStartedAt=this.now()}get size(){return this.events.length}enqueue(e){return this.refreshRateWindow(),this.acceptedInWindow>=this.rateLimit?(this.rateDiagnosticEmitted||(this.rateDiagnosticEmitted=!0,this.onDrop?.("rate-limit")),!1):this.events.length>=this.capacity?(this.capacityDiagnosticEmitted||(this.capacityDiagnosticEmitted=!0,this.onDrop?.("capacity")),!1):(this.events.push(e),this.acceptedInWindow+=1,this.schedule(),!0)}enable(){this.enabled=!0,this.schedule()}updateAppKey(e,t){for(let o=0;o<this.events.length;o+=1){const r=this.events[o];r&&r.appKey===e&&(this.events[o]={appKey:t,wire:{...r.wire,body:{...r.wire.body,appkey:t}}})}}pause(){this.enabled=!1,this.clearTimer()}clear(){this.pause(),this.events.splice(0,this.events.length),this.acceptedInWindow=0,this.windowStartedAt=this.now(),this.capacityDiagnosticEmitted=!1,this.rateDiagnosticEmitted=!1}refreshRateWindow(){const e=this.now();e-this.windowStartedAt<6e4||(this.windowStartedAt=e,this.acceptedInWindow=0,this.rateDiagnosticEmitted=!1)}schedule(){this.enabled&&0!==this.events.length&&!this.timer&&(this.timer=setTimeout(()=>{this.timer=void 0,this.consume()},this.flushIntervalMs))}async consume(){if(!this.enabled||0===this.events.length)return;const e=this.events[0];if(!e)return;const t=[];for(let o=0;o<this.events.length&&t.length<this.batchSize;){const r=this.events[o];r?.appKey===e.appKey?(t.push(r.wire),this.events.splice(o,1)):o+=1}this.events.length<this.capacity&&(this.capacityDiagnosticEmitted=!1);try{await this.sendBatch(e.appKey,t)}catch{}finally{this.schedule()}}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}}class _t{constructor(e){this.requestAdapter=e.requestAdapter,this.debug=e.debug??!1,this.now=e.now??Date.now,this.onFailure=e.onFailure}async send(e,t){if(this.requestAdapter&&0!==t.length)try{const o=await this.requestAdapter.request({url:this.debug?"https://data-reporting.realtimemesh.com/report":"https://data-reporting.rtnsvc.com/report",method:"POST",headers:{"Content-Type":"application/json",token:"32f24ab2ddb74f508aa9286c356cec84",appid:e,sendts:String(Math.floor(this.now()/1e3)),biz:"im",debug:String(this.debug)},body:JSON.stringify(t),responseType:"text",timeoutMs:15e3});(o.status<200||o.status>=300)&&this.onFailure?.({reason:"non-success-response",status:o.status})}catch(o){this.onFailure?.({reason:"transport-error",message:o instanceof Error?o.message:String(o)})}else this.onFailure?.({reason:"request-adapter-unavailable",eventCount:t.length})}}const Rt={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},mt=()=>{const e=nt(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class ht{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??mt;const t=new _t({requestAdapter:e.requestAdapter,debug:e.debug,now:this.now,onFailure:t=>{e.onDiagnostic?.("DataReport transport failed",t)}}),o=e.send??((e,o)=>t.send(e,o));this.queue=new Ot({send:o,now:this.now,onDrop:t=>{e.onDiagnostic?.("DataReport event dropped",{reason:t})}})}get state(){return this.currentState}get queuedEventCount(){return this.queue.size}get serviceId(){return this.session?.serviceId}startSession(e){this.queue.clear(),this.currentState="unknown";const t=this.randomId();return this.session={...e,sessionId:`session_${t}`,serviceId:`sid_${t}`},this.enqueue(9674,{did:e.did??"",os:e.os??e.platform,sdkVersion:e.sdkVersion,deviceId:e.deviceId??""}),this.session.serviceId}updateSession(e){this.session&&(e.appKey&&e.appKey!==this.session.appKey&&this.queue.updateAppKey(this.session.appKey,e.appKey),this.session={...this.session,...e})}updateNetworkType(e){this.networkType=(e=>"number"==typeof e&&Number.isFinite(e)?e:"string"!=typeof e?-1:Rt[e.trim().toLowerCase()]??-1)(e)}applyDnsSwitch(e){if(this.session){if("true"===e)return this.currentState="enabled",void this.queue.enable();this.currentState="disabled",this.queue.clear()}else this.currentState="disabled"}startOperation(e){const t=this.session?.sessionId;if(!t||"disabled"===this.currentState)return this.createNoopOperation();const o=`opr_${this.randomId()}`,r=this.now();let s=!1,i=!1,a=`req_${this.randomId()}`,n=0,p="";const E=()=>!s&&!i&&this.session?.sessionId===t,c=(t,r,s,i,a)=>{E()&&(n=a.success?0:a.code,p=a.success?"":a.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:r,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(s),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:a.code,codeDesc:a.description??"",isLastApi:0,isSuccess:a.success?1:0,accessChannel:this.session?.accessChannel??lt,msgId:e.msgId,messageType:e.messageType,resultCount:a.resultCount}))},T=(e,t,o,r)=>{const s=this.now();let i=!1;return{retry:()=>(r.next+=1,T(e,t,r.next,r)),finish:r=>{i||(i=!0,c(e,t,o,s,r))}}};return{startRequest:(e={})=>(a=`req_${this.randomId()}`,T(e,a,1,{next:1})),finish:t=>{E()&&(s=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:a,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-r),code:t.success?0:t.code??n,codeDesc:t.success?"":t.description??p,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??lt,msgId:e.msgId,messageType:e.messageType,resultCount:t.resultCount}))},discard:()=>{i=!0}}}reset(){this.currentState="disabled",this.session=void 0,this.queue.clear()}enqueue(e,t){const o=this.session;if(!o||"disabled"===this.currentState)return;const r={lts:this.now(),net:this.networkType,appkey:o.appKey,sdkServiceId:o.serviceId,sdkProduct:0,uikitVersion:o.uikitVersion??"",...t},s={eventId:e,body:Object.fromEntries(Object.entries(r).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:o.appKey,wire:s})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let Nt;const It=e=>(Nt?.reset(),Nt=new ht(e),Nt),At=e=>Nt?.startSession(e),ft=e=>{Nt?.updateSession(e)},St=e=>{Nt?.applyDnsSwitch(e)},yt=e=>{Nt?.updateNetworkType(e)},Ct=e=>{if("disabled"!==Nt?.state)return Nt?.startOperation(e)},Mt=()=>{Nt?.reset(),Nt=void 0},gt=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},Dt=()=>ct({fetchImpl:gt()})??{request:e=>Promise.reject(st("Request capability is missing for current platform.",{code:rt.MISSING_CAPABILITY,stage:ot.REQUEST,retryable:!1,details:{capability:"request"}}))},Ut=e=>e??Dt(),Lt=(e,t)=>{if(!e.matchField)return!1;const o=t[e.matchField];return void 0!==e.matchPattern?"string"==typeof o&&o.includes(e.matchPattern):void 0===e.matchValue?void 0!==o:o===e.matchValue||!("string"!=typeof o&&"number"!=typeof o||"string"!=typeof e.matchValue&&"number"!=typeof e.matchValue)&&String(o)===String(e.matchValue)};function bt(e,t,o){if(!e)return;const r=o&&"object"==typeof o?o:{},s="string"==typeof r.error?r.error:void 0,i=(e=>"string"==typeof e.error_code||"number"==typeof e.error_code?e.error_code:"string"==typeof e.errorCode||"number"==typeof e.errorCode?e.errorCode:"string"==typeof e.error||"number"==typeof e.error?e.error:"string"==typeof e.code||"number"==typeof e.code?e.code:void 0)(r),a="string"==typeof r.error_description?r.error_description:"string"==typeof r.message?r.message:"string"==typeof r.desc?r.desc:void 0,n=(e,t=!1)=>{const o=(e,o,r)=>({reasonKey:e,entry:o,matchedBy:t?"common":r});if(s&&e[s])return o(s,e[s],"key");for(const[s,i]of Object.entries(e))if(Lt(i,r))return o(s,i,"field");if(void 0!==i)for(const[r,s]of Object.entries(e)){if(s.code===i||s.canonicalCode===i)return o(r,s,"code");if(Array.isArray(s.aliases)&&s.aliases.includes(String(i)))return o(r,s,"alias")}if(a)for(const[r,s]of Object.entries(e))if(Array.isArray(s.aliases)&&s.aliases.includes(a))return o(r,s,"alias")},p=t?e.apis[t]:void 0,E=p?n(p.errors):void 0;if(E)return E;for(const c of Object.values(e.common)){const e=n(c.errors,!0);if(e)return e}}function Pt(t){const o=t.entry?.code??e.REST_BUSINESS_UNKNOWN,r=t.message??function(e){const t=e.apiName?`${e.apiName} failed`:"request failed";if(e.entry?.runtimeMessage)return`REST business error: ${e.entry.runtimeMessage}`;if(e.mapped??Boolean(e.entry)){if(e.reasonKey){const t=e.reasonKey.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split("_").join(" ").split("-").join(" ").toLowerCase();return`REST business error: ${t.charAt(0).toUpperCase()}${t.slice(1)}`}return`REST business error: ${t}`}return e.reasonKey?`REST business error: ${t} (${e.reasonKey})`:`REST business error: ${t}`}({apiName:t.apiName,entry:t.entry,mapped:t.mapped,reasonKey:t.reasonKey});return new d(r,{code:o,details:{api:t.apiName,serverCode:t.serverCode,serverMessage:t.serverMessage,httpStatus:t.httpStatus,mapped:t.mapped??Boolean(t.entry),reasonKey:t.reasonKey,matchedBy:t.matchedBy,retryable:t.entry?.retryable,canonicalCode:t.entry?.canonicalCode??t.entry?.code}})}const Gt={getHistoryMessages:{operationName:"REST_GET_HISTORY_MESSAGE",operationType:"REST"},removeHistoryMessages:{operationName:"REST_DELETE_MESSAGES_CONVERSATIONS",operationType:"REST"},searchMessages:{operationName:"REST_SEARCH_MESSAGES",operationType:"REST"},addContact:{operationName:"ROSTER_ADD",operationType:"ROSTER"},deleteContact:{operationName:"ROSTER_REMOVE",operationType:"ROSTER"},acceptContactInvite:{operationName:"ROSTER_ACCEPT",operationType:"ROSTER"},declineContactInvite:{operationName:"ROSTER_DECLINE",operationType:"ROSTER"},addUsersToBlocklist:{operationName:"ROSTER_BAN",operationType:"ROSTER"},removeUserFromBlocklist:{operationName:"ROSTER_ALLOW",operationType:"ROSTER"},getBlocklist:{operationName:"ROSTER_BLACKLIST",operationType:"ROSTER"},getContactList:{operationName:"ROSTER_CONTACTS",operationType:"ROSTER"},setContactRemark:{operationName:"ROSTER_SET_CONTACT_REMARK",operationType:"ROSTER"},updateOwnInfo:{operationName:"USER_UPDATE_USERINFO",operationType:"USER"},getUserInfoByUserId:{operationName:"USER_FETCH_USERINFO",operationType:"USER"},uploadPushToken:{operationName:"USER_UPLOAD_PUSH_TOKEN",operationType:"USER"},createGroup:{operationName:"GROUP_CREATEGROUP",operationType:"GROUP"},destroyGroup:{operationName:"GROUP_DESTOTYGROUP",operationType:"GROUP"},leaveGroup:{operationName:"GROUP_LEAVEGROUP",operationType:"GROUP"},joinGroup:{operationName:"GROUP_JOIN_PUBLICGROUP",operationType:"GROUP"},getGroupMemberList:{operationName:"GROUP_FETCH_MEMEBERS",operationType:"GROUP"},uploadGroupSharedFile:{operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"},downloadGroupSharedFile:{operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"},getChatRoomList:{operationName:"CHATROOM_FETCH_CHATROOMSWITHPAGE",operationType:"CHATROOM"},getChatRoomInfo:{operationName:"CHATROOM_FETCH_SPECIFICATION",operationType:"CHATROOM"},joinChatRoom:{operationName:"CHATROOM_JOINCAHTROOM",operationType:"CHATROOM"},leaveChatRoom:{operationName:"CHATROOM_LEAVECAHTROOM",operationType:"CHATROOM"},getConversationList:{operationName:"REST_GET_SESSION_LIST",operationType:"REST"},deleteConversation:{operationName:"REST_DEL_SESSION",operationType:"REST"},setConversationPinned:{operationName:"REST_PIN_CONVERSATION",operationType:"REST"},getPinnedMessageList:{operationName:"REST_FETCH_PINMESSAGES",operationType:"REST"},clearAllMessagesAndConversations:{operationName:"REST_DELETE_MESSAGES_CONVERSATIONS",operationType:"REST"},setPinned:{operationName:"REST_PIN_MESSAGE",operationType:"REST"},getSelfIdsOnOtherPlatform:{operationName:"USER_LOGGEDIN_OTHER_PLATFORM",operationType:"USER"},getJoinedGroupList:{operationName:"GROUP_FETCH_USERS_GROUP",operationType:"GROUP"},changeGroupOwner:{operationName:"GROUP_CHANGE_OWNER",operationType:"GROUP"},getGroupInfo:{operationName:"GROUP_FETCH_SPECIFICATION",operationType:"GROUP"},getGroupInfoList:{operationName:"GROUP_FETCH_SPECIFICATION",operationType:"GROUP"},updateGroupInfo:{operationName:"GROUP_CHANGE_GROUPATTRIBUTE",operationType:"GROUP"},getGroupAdminList:{operationName:"GROUP_GET_ADMIN",operationType:"GROUP"},addGroupAdmin:{operationName:"GROUP_SET_ADMIN",operationType:"GROUP"},removeGroupAdmin:{operationName:"GROUP_REMOVE_ADMIN",operationType:"GROUP"},inviteUsersToGroup:{operationName:"GROUP_INVITE_TO_GROUP",operationType:"GROUP"},acceptGroupJoinRequest:{operationName:"GROUP_ACCEPT_JOINPUBLICGROUPAPPL",operationType:"GROUP"},rejectGroupJoinRequest:{operationName:"GROUP_DECLINE_JOINPUBLICGROUPAPPL",operationType:"GROUP"},acceptInvitation:{operationName:"GROUP_ACCEPT_INVITATION",operationType:"GROUP"},rejectInvitation:{operationName:"GROUP_DECLINE_INVITATION",operationType:"GROUP"},removeGroupMembers:{operationName:"GROUP_REMOVE_MEMBERS",operationType:"GROUP"},muteGroupMembers:{operationName:"GROUP_MUTE_MEMBERS",operationType:"GROUP"},unmuteGroupMembers:{operationName:"GROUP_UNMUTE_MEMBERS",operationType:"GROUP"},getGroupMuteList:{operationName:"GROUP_FETCH_MUTES",operationType:"GROUP"},blockGroupMembers:{operationName:"GROUP_BLOCK_MEMBERS",operationType:"GROUP"},unblockGroupMembers:{operationName:"GROUP_UNBLOCK_MEMBERS",operationType:"GROUP"},getGroupBlocklist:{operationName:"GROUP_GET_BLOCK_LIST",operationType:"GROUP"},muteAllGroupMembers:{operationName:"GROUP_MUTE_ALLMEMBERS",operationType:"GROUP"},unmuteAllGroupMembers:{operationName:"GROUP_UNMUTE_ALLMEMBERS",operationType:"GROUP"},addUsersToGroupAllowlist:{operationName:"GROUP_ADD_WHITELIST",operationType:"GROUP"},removeUsersFromGroupAllowlist:{operationName:"GROUP_REMOVE_WHITELIST",operationType:"GROUP"},getGroupAllowlist:{operationName:"GROUP_FETCH_WHITELIST",operationType:"GROUP"},checkIfInGroupAllowList:{operationName:"GROUP_IS_IN_WHITELIST",operationType:"GROUP"},getGroupMessageReadUsers:{operationName:"GROUP_GET_READ_USERS",operationType:"GROUP"},getGroupAnnouncement:{operationName:"GROUP_FETCH_ANNOUNCEMENT",operationType:"GROUP"},updateGroupAnnouncement:{operationName:"GROUP_UPDATE_ANNOUNCEMENT",operationType:"GROUP"},deleteGroupSharedFile:{operationName:"GROUP_DELETE_SHAREDFILE",operationType:"GROUP"},getGroupSharedFileList:{operationName:"GROUP_FETCH_SHAREDFILE",operationType:"GROUP"},setGroupMemberAttributes:{operationName:"GROUP_MEMBER_SET_META_DATA",operationType:"GROUP"},getGroupMembersAttributes:{operationName:"GROUP_MEMBER_FETCH_META_DATA",operationType:"GROUP"},destroyChatRoom:{operationName:"CHATROOM_DESTORYCHATROOM",operationType:"CHATROOM"},updateChatRoomInfo:{operationName:"CHATROOM_CHANGE_ATTRIBUTE",operationType:"CHATROOM"},removeChatRoomMembers:{operationName:"CHATROOM_REMOVE_MEMBERS",operationType:"CHATROOM"},addChatRoomMembers:{operationName:"CHATROOM_ADD_MEMBERS",operationType:"CHATROOM"},getChatRoomMemberList:{operationName:"CHATROOM_FETCH_MEMBERS",operationType:"CHATROOM"},getChatRoomAdminList:{operationName:"CHATROOM_GET_ADMIN",operationType:"CHATROOM"},setChatRoomAdmin:{operationName:"CHATROOM_SET_ADMIN",operationType:"CHATROOM"},removeChatRoomAdmin:{operationName:"CHATROOM_REMOVE_ADMIN",operationType:"CHATROOM"},muteChatRoomMembers:{operationName:"CHATROOM_MUTE_USER",operationType:"CHATROOM"},unmuteChatRoomMembers:{operationName:"CHATROOM_UNMUTE_USER",operationType:"CHATROOM"},getChatRoomMuteList:{operationName:"CHATROOM_FETCH_MUTES",operationType:"CHATROOM"},blockChatRoomMembers:{operationName:"CHATROOM_BLOCK_USERS",operationType:"CHATROOM"},unblockChatRoomMembers:{operationName:"CHATROOM_UNBLOCK_USERS",operationType:"CHATROOM"},getChatRoomBlocklist:{operationName:"CHATROOM_FETCH_BANS",operationType:"CHATROOM"},muteAllChatRoomMembers:{operationName:"CHATROOM_MUTE_ALLMEMEBERS",operationType:"CHATROOM"},unmuteAllChatRoomMembers:{operationName:"CHATROOM_UNMUTE_ALLMEMEBERS",operationType:"CHATROOM"},addUsersToChatRoomAllowlist:{operationName:"CHATROOM_ADD_WHITELIST",operationType:"CHATROOM"},removeUsersFromChatRoomAllowlist:{operationName:"CHATROOM_REMOVE_WHITELIST",operationType:"CHATROOM"},getChatRoomAllowlist:{operationName:"CHATROOM_FETCH_WHITELIST",operationType:"CHATROOM"},checkIfInChatRoomAllowList:{operationName:"CHATROOM_FETCH_MEMBERIN_WHITELIST",operationType:"CHATROOM"},getChatRoomAnnouncement:{operationName:"CHATROOM_FETCH_ANNOUNCEMENT",operationType:"CHATROOM"},updateChatRoomAnnouncement:{operationName:"CHATROOM_UPDATE_ANNOUNCEMENT",operationType:"CHATROOM"},deleteChatRoomSharedFile:{operationName:"CHATROOM_REMOVE_SHARE_FILE",operationType:"CHATROOM"},getChatRoomSharedFileList:{operationName:"CHATROOM_GET_SHARE_FILE_LIST",operationType:"CHATROOM"},setChatRoomAttributes:{operationName:"CHATROOM_SET_META_DATA",operationType:"CHATROOM"},removeChatRoomAttributes:{operationName:"CHATROOM_DELETE_META_DATA",operationType:"CHATROOM"},getChatRoomAttributes:{operationName:"CHATROOM_FETCH_META_DATA",operationType:"CHATROOM"}},Ht=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();class wt{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=Ut(t?.requestAdapter),this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),o=t.searchParams;for(const e of o.keys())o.set(e,"***");const r=o.toString(),s=r?`?${r}`:"";return`${t.origin}${t.pathname}${s}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(t,o,r,s){const i={...o.operation?{api:o.operation}:{},url:o.url,method:o.method,httpStatus:t,serverCode:r,serverMessage:s,mapped:!1};if(400===t)return new p("Invalid request parameters",{code:e.VALIDATION_UNKNOWN,details:{...i,canonicalCode:e.VALIDATION_UNKNOWN}});if(401===t){const t=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),o=t?e.AUTH_TOKEN_EXPIRED:e.AUTH_UNAUTHORIZED;return new n(t?"Authentication token expired":"Authentication failed",{code:o,details:{...i,reasonKey:t?"token_expired":"unauthorized",canonicalCode:o}})}return 403===t?new n("Access forbidden",{code:e.AUTH_FORBIDDEN,details:{...i,canonicalCode:e.AUTH_FORBIDDEN}}):429===t?new d("REST rate limit exceeded",{code:e.SERVICE_LIMIT_EXCEEDED,details:{...i,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:e.SERVICE_LIMIT_EXCEEDED}}):t>=500?new d("REST business error: request failed",{code:e.REST_BUSINESS_UNKNOWN,details:{...i,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:e.REST_BUSINESS_UNKNOWN}}):void 0}async request(t,o={}){const r=`${this.baseUrl}${t}`,i=o.method??"GET",a=Date.now(),n=this.sanitizeUrl(r);Ze.debug("REST request",{method:i,url:n,operation:o.operation});const p=o.operation?(e=>{const t=Gt[e];if(t)return t;const o=(e=>{const t=e.toLowerCase();return t.includes("chatroom")||t.includes("chat_room")?"CHATROOM":t.includes("group")?"GROUP":t.includes("contact")||t.includes("blocklist")?"ROSTER":t.includes("userinfo")||t.includes("presence")?"USER":"REST"})(e);return{operationName:`REST_${Ht(e)}`,operationType:o}})(o.operation):void 0,E=p?Ct(p):void 0,c=E?.startRequest({requestName:p?.operationName,method:i,url:r});let T=0;const d={...this.defaultHeaders,...o.headers};if(this.includeRequestId&&(d[ut]=Tt()),o.body&&"GET"!==i){const e=Object.keys(d).some(e=>"content-type"===e.toLowerCase());"string"==typeof o.body?e||(d["Content-Type"]="application/x-www-form-urlencoded"):e||(d["Content-Type"]="application/json")}else if("GET"===i)for(const e of Object.keys(d))"content-type"===e.toLowerCase()&&delete d[e];try{const e=await this.requestAdapter.request({url:r,method:i,headers:d,body:o.body,timeoutMs:o.timeout??this.timeout});T=e.status;const t=((e,t)=>{if("string"!=typeof e)return e;const o=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),r=e.trim();if(!(o?.[1].includes("application/json")||r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]")))return e;try{return JSON.parse(r)}catch{return e}})(e.data,e.headers),s=Date.now()-a;(e.status<200||e.status>=300)&&(Ze.warn("REST response error",{method:i,url:n,status:e.status,duration:s}),this.handleErrorPayload(e.status,e.statusText??"",t,{operation:o.operation,url:r,method:i})),Ze.debug("REST response",{method:i,url:n,status:e.status,duration:s});const p=(e=>{if(Array.isArray(e))return e.length;if(!e||"object"!=typeof e)return;const t=e;for(const o of["entities","data","items","messages","conversations","results"]){const e=t[o];if(Array.isArray(e))return e.length}})(t);return c?.finish({code:e.status,success:!0,resultCount:p}),E?.finish({code:0,success:!0,resultCount:p}),t}catch(l){const t=0!==T?T:l instanceof s?l.code:-1,a=l instanceof Error?l.message:String(l);if(c?.finish({code:t,success:!1,description:a}),E?.finish({code:t,success:!1,description:a}),l instanceof s)throw l;const p=(e=>{if(!e||"object"!=typeof e)return;const t=e.details;if(!t||"object"!=typeof t)return;const o=t.reason;return"abort"===o||"network"===o||"timeout"===o?o:void 0})(l);if(l instanceof Error&&"AbortError"===l.name||"timeout"===p)throw Ze.warn("REST request timeout",{method:i,url:n,timeout:o.timeout??this.timeout}),new u(`Request timeout: ${r}`,{code:e.REST_TIMEOUT,details:{url:r,method:i,timeout:o.timeout??this.timeout}});throw Ze.warn("REST request failed",{method:i,url:n}),new u(`Request failed: ${r}`,{code:e.REST_NETWORK_ERROR,details:{url:r,method:i,...p?{reason:p}:{}}})}}handleErrorPayload(t,o,r,s){const i=r&&"object"==typeof r?r:{},a=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const o=e.error,r=o.code;if("number"!=typeof r&&"string"!=typeof r)return;const s=String(r);return/^\d{7}$/.test(s)&&Number(s.slice(0,3))===t?o:void 0})(i,t),n=a?{...i,code:a.code,message:a.message}:r,p=bt(this.errorMap,s.operation,n),E="string"==typeof i.error?i.error:void 0,c="number"==typeof i.error_code||"string"==typeof i.error_code?i.error_code:"number"==typeof i.errorCode||"string"==typeof i.errorCode?i.errorCode:"number"==typeof i.code||"string"==typeof i.code?i.code:"string"==typeof i.error?i.error:"number"==typeof a?.code||"string"==typeof a?.code?a.code:void 0,T="string"==typeof i.message?i.message:"string"==typeof i.error_description?i.error_description:"string"==typeof i.desc?i.desc:"string"==typeof a?.message?a.message:void 0,d=!!(401!==t&&403!==t||void 0!==E&&"unauthorized"!==E&&"auth_failed"!==E&&"forbidden"!==E)&&(void 0!==E||"string"==typeof i.error_description||"string"==typeof i.message||"string"==typeof i.desc);if(s.operation&&p)throw Pt({apiName:s.operation,entry:p.entry,serverCode:c,serverMessage:T,httpStatus:t,mapped:!0,reasonKey:p.reasonKey,matchedBy:p.matchedBy});const l=this.buildHttpStatusFallbackError(t,s,c,T);if(l)throw l;if(s.operation&&d)throw Pt({apiName:s.operation,serverCode:c,serverMessage:T,httpStatus:t,mapped:!1,reasonKey:E});throw new u(`HTTP ${t}: ${o}`,{code:e.REST_HTTP_ERROR,details:{url:s.url,method:s.method,httpStatus:t}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,o){return this.request(e,{...o,method:"POST",body:t})}put(e,t,o){return this.request(e,{...o,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,o){return this.request(e,{...o,method:"PATCH",body:t})}}const vt=(...e)=>{const t={},o={};for(const r of e)Object.assign(t,r.common),Object.assign(o,r.apis);return{common:t,apis:o}},Ft={common:{validation:{range:"100-110",errors:{MISSING_REQUIRED:{code:110},INVALID_FORMAT:{code:110},UNKNOWN:{code:110}}},auth:{range:"108,200-215",errors:{ALREADY_LOGIN:{code:200},NOT_LOGIN:{code:201},UNAUTHORIZED:{code:202},FORBIDDEN:{code:210},TOKEN_EXPIRED:{code:108},BIND_ANOTHER_DEVICE:{code:213},LOGIN_TOO_MANY_DEVICES:{code:214},USER_MUTED:{code:215}}},connection:{range:"1,100,202,300-304",errors:{TIMEOUT:{code:301},LOGIN_TIMEOUT:{code:301},WEBSOCKET_ERROR:{code:300},NOT_CREATED:{code:1},CLOSED_BEFORE_READY:{code:300},CANCELLED:{code:1},PROVISION_TIMEOUT:{code:301},PROVISION_REJECTED:{code:202},PROVISION_CLOSED:{code:300},DNSLIST_FAILED:{code:304},SERVER_BUSY:{code:302}}},storage:{range:"3",errors:{OPERATION_FAILED:{code:3}}},message:{range:"1,300-511",errors:{NOT_CONNECTED:{code:300},ACK_TIMEOUT:{code:301},SEND_FAILED:{code:303},SENDER_DESTROYED:{code:1},ENCODE_FAILED:{code:500},DECODE_FAILED:{code:500},ACK_MISSING:{code:301}}},transport:{range:"2,301,303",errors:{NETWORK_ERROR:{code:2},TIMEOUT:{code:301},HTTP_ERROR:{code:303},BUSINESS_UNKNOWN:{code:303}}},upload:{range:"1,100,110,301,402,405",errors:{REQUIRED_FIELD_MISSING:{code:110},INVALID_APPKEY:{code:100},SIZE_EXCEEDED:{code:405},REQUEST_FAILED:{code:402},TIMEOUT:{code:301},ABORTED:{code:1}}},unknown:{range:"1,4",errors:{UNKNOWN:{code:1},SERVICE_LIMIT_EXCEEDED:{code:4}}},push:{range:"1500,1501,1502",errors:{TOKEN_UPLOAD_FAILED:{code:1500},SILENT_MODE_OPERATION_FAILED:{code:1501},PUSH_LANGUAGE_OPERATION_FAILED:{code:1502}}},chatroom:{range:"700-707",errors:{CHATROOM_INVALID_ID:{code:700},CHATROOM_NOT_JOINED:{code:702},CHATROOM_PERMISSION_DENIED:{code:703},CHATROOM_MEMBERS_FULL:{code:704},CHATROOM_NOT_EXIST:{code:705},CHATROOM_OWNER_NOT_ALLOW_LEAVE:{code:706},CHATROOM_USER_IN_BLOCKLIST:{code:707}}}},apis:{}};export{Le as $,n as A,A as B,Ft as C,L as D,e as E,U as F,D as G,M as H,le as I,g as J,f as K,Ct as L,E as M,W as N,c as O,rt as P,_ as Q,wt as R,s as S,dt as T,l as U,p as V,Ut as W,pe as X,ce as Y,Ae as Z,ge as _,ot as a,h as a0,Ee as a1,he as a2,Re as a3,_e as a4,be as a5,Se as a6,ye as a7,Ce as a8,F as a9,Mt as aA,Ye as aB,Xe as aC,Je as aD,Qe as aE,R as aF,Z as aG,ze as aH,je as aI,xe as aJ,O as aK,bt as aL,I as aM,N as aN,T as aa,b as ab,v as ac,P as ad,o as ae,H as af,G as ag,w as ah,y as ai,C as aj,m as ak,q as al,K as am,x as an,$ as ao,j as ap,V as aq,k as ar,B as as,S as at,It as au,At as av,yt as aw,We as ax,ft as ay,St as az,z as b,Y as c,J as d,X as e,Q as f,nt as g,Me as h,Pt as i,d as j,fe as k,Ze as l,vt as m,ne as n,ut as o,me as p,Tt as q,a as r,i as s,u as t,et as u,st as v,it as w,ct as x,Ue as y,De as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={MESSAGE:"onMessage",STREAM_MESSAGE:"onStreamMessage",CONVERSATION_LIST_UPDATE:"onConversationListUpdate",MESSAGE_READ_RECEIPTS:"onMessageReadReceipts",MESSAGE_DELIVERED:"onMessageDelivered",MESSAGE_RECALLED:"onMessageRecalled",MESSAGE_UPDATED:"onMessageUpdated",REACTION_CHANGED:"onReactionChanged",PINNED_MESSAGE_CHANGED:"onPinnedMessageChanged",MULTI_DEVICE_CONTACT:"onMultiDeviceContact",MULTI_DEVICE_CONVERSATION:"onMultiDeviceConversation",SYNC_DATA_START:"onSyncDataStart",SYNC_DATA_FINISHED:"onSyncDataFinished"},E={LOG:"onLog"},o={STATUS_CHANGE:"onPresenceStatusChange"},n={INVITED:"onContactInvited",DELETED:"onContactDeleted",ADDED:"onContactAdded",REFUSE:"onContactRefuse",AGREED:"onContactAgreed",CONTACT_INFO_UPDATED:"onContactInfoUpdated"},_={INVITATION_RECEIVED:"onInvitationReceived",REQUEST_TO_JOIN_RECEIVED:"onRequestToJoinReceived",REQUEST_TO_JOIN_ACCEPTED:"onRequestToJoinAccepted",REQUEST_TO_JOIN_DECLINED:"onRequestToJoinDeclined",INVITATION_ACCEPTED:"onInvitationAccepted",INVITATION_DECLINED:"onInvitationDeclined",USER_REMOVED:"onUserRemoved",GROUP_DESTROYED:"onGroupDestroyed",AUTO_ACCEPT_INVITATION:"onAutoAcceptInvitationFromGroup",MUTE_LIST_ADDED:"onMuteListAdded",MUTE_LIST_REMOVED:"onMuteListRemoved",ALLOW_LIST_ADDED:"onAllowListAdded",ALLOW_LIST_REMOVED:"onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"onAllMemberMuteStateChanged",ADMIN_ADDED:"onAdminAdded",ADMIN_REMOVED:"onAdminRemoved",OWNER_CHANGED:"onOwnerChanged",MEMBERS_JOINED:"onMembersJoined",MEMBERS_EXITED:"onMembersExited",ANNOUNCEMENT_CHANGED:"onAnnouncementChanged",SHARED_FILE_ADDED:"onSharedFileAdded",SHARED_FILE_DELETED:"onSharedFileDeleted",GROUP_INFO_CHANGED:"onGroupInfoChanged",GROUP_DISABLED_CHANGED:"onGroupDisabledChanged",GROUP_MEMBER_ATTRIBUTE_CHANGED:"onGroupMemberAttributeChanged",USER_GROUP_NAMECARD_UPDATED:"onUserGroupNamecardUpdated"},A={CHAT_ROOM_DESTROYED:"__chatroom:onChatRoomDestroyed",MEMBERS_JOINED:"__chatroom:onMembersJoined",MEMBERS_EXITED:"__chatroom:onMembersExited",REMOVED_FROM_CHAT_ROOM:"__chatroom:onRemovedFromChatRoom",MUTE_LIST_ADDED:"__chatroom:onMuteListAdded",MUTE_LIST_REMOVED:"__chatroom:onMuteListRemoved",ALLOW_LIST_ADDED:"__chatroom:onAllowListAdded",ALLOW_LIST_REMOVED:"__chatroom:onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"__chatroom:onAllMemberMuteStateChanged",ADMIN_ADDED:"__chatroom:onAdminAdded",ADMIN_REMOVED:"__chatroom:onAdminRemoved",OWNER_CHANGED:"__chatroom:onOwnerChanged",ANNOUNCEMENT_CHANGED:"__chatroom:onAnnouncementChanged",CHAT_ROOM_INFO_CHANGED:"__chatroom:onChatRoomInfoChanged",ATTRIBUTES_UPDATE:"__chatroom:onAttributesUpdate",ATTRIBUTES_REMOVED:"__chatroom:onAttributesRemoved"},D={TOKEN_BOUND:"onPushTokenBound",TOKEN_BIND_FAILED:"onPushTokenBindFailed",TOKEN_REMOVE_FAILED:"onPushTokenRemoveFailed"};export{e as C,_ as G,E as L,
|
|
1
|
+
const e={MESSAGE:"onMessage",STREAM_MESSAGE:"onStreamMessage",CONVERSATION_LIST_UPDATE:"onConversationListUpdate",MESSAGE_READ_RECEIPTS:"onMessageReadReceipts",MESSAGE_DELIVERED:"onMessageDelivered",MESSAGE_RECALLED:"onMessageRecalled",MESSAGE_UPDATED:"onMessageUpdated",REACTION_CHANGED:"onReactionChanged",PINNED_MESSAGE_CHANGED:"onPinnedMessageChanged",MULTI_DEVICE_CONTACT:"onMultiDeviceContact",MULTI_DEVICE_CONVERSATION:"onMultiDeviceConversation",SYNC_DATA_START:"onSyncDataStart",SYNC_DATA_FINISHED:"onSyncDataFinished"},E={LOG:"onLog"},o={STATUS_CHANGE:"onPresenceStatusChange"},n={INVITED:"onContactInvited",DELETED:"onContactDeleted",ADDED:"onContactAdded",REFUSE:"onContactRefuse",AGREED:"onContactAgreed",CONTACT_INFO_UPDATED:"onContactInfoUpdated"},_={INVITATION_RECEIVED:"onInvitationReceived",REQUEST_TO_JOIN_RECEIVED:"onRequestToJoinReceived",REQUEST_TO_JOIN_ACCEPTED:"onRequestToJoinAccepted",REQUEST_TO_JOIN_DECLINED:"onRequestToJoinDeclined",INVITATION_ACCEPTED:"onInvitationAccepted",INVITATION_DECLINED:"onInvitationDeclined",USER_REMOVED:"onUserRemoved",GROUP_DESTROYED:"onGroupDestroyed",AUTO_ACCEPT_INVITATION:"onAutoAcceptInvitationFromGroup",MUTE_LIST_ADDED:"onMuteListAdded",MUTE_LIST_REMOVED:"onMuteListRemoved",ALLOW_LIST_ADDED:"onAllowListAdded",ALLOW_LIST_REMOVED:"onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"onAllMemberMuteStateChanged",ADMIN_ADDED:"onAdminAdded",ADMIN_REMOVED:"onAdminRemoved",OWNER_CHANGED:"onOwnerChanged",MEMBERS_JOINED:"onMembersJoined",MEMBERS_EXITED:"onMembersExited",ANNOUNCEMENT_CHANGED:"onAnnouncementChanged",SHARED_FILE_ADDED:"onSharedFileAdded",SHARED_FILE_DELETED:"onSharedFileDeleted",GROUP_INFO_CHANGED:"onGroupInfoChanged",GROUP_DISABLED_CHANGED:"onGroupDisabledChanged",GROUP_MEMBER_ATTRIBUTE_CHANGED:"onGroupMemberAttributeChanged",USER_GROUP_NAMECARD_UPDATED:"onUserGroupNamecardUpdated"},A={CHAT_ROOM_DESTROYED:"__chatroom:onChatRoomDestroyed",MEMBERS_JOINED:"__chatroom:onMembersJoined",MEMBERS_EXITED:"__chatroom:onMembersExited",REMOVED_FROM_CHAT_ROOM:"__chatroom:onRemovedFromChatRoom",MUTE_LIST_ADDED:"__chatroom:onMuteListAdded",MUTE_LIST_REMOVED:"__chatroom:onMuteListRemoved",ALLOW_LIST_ADDED:"__chatroom:onAllowListAdded",ALLOW_LIST_REMOVED:"__chatroom:onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"__chatroom:onAllMemberMuteStateChanged",ADMIN_ADDED:"__chatroom:onAdminAdded",ADMIN_REMOVED:"__chatroom:onAdminRemoved",OWNER_CHANGED:"__chatroom:onOwnerChanged",ANNOUNCEMENT_CHANGED:"__chatroom:onAnnouncementChanged",CHAT_ROOM_INFO_CHANGED:"__chatroom:onChatRoomInfoChanged",ATTRIBUTES_UPDATE:"__chatroom:onAttributesUpdate",ATTRIBUTES_REMOVED:"__chatroom:onAttributesRemoved"},D={TOKEN_BOUND:"onPushTokenBound",TOKEN_BIND_FAILED:"onPushTokenBindFailed",TOKEN_REMOVE_FAILED:"onPushTokenRemoveFailed"};export{e as C,_ as G,E as L,D as P,n as a,o as b,A as c};
|
package/chunks/{group-user-info-resolver-DMccCqez.js → group-user-info-resolver-D6AQAHEE.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{U as e,P as r,a as s,E as t,l as n}from"./common-
|
|
1
|
+
import{U as e,P as r,a as s,E as t,l as n}from"./common-DHQukb7J.js";const a=n=>{if(n instanceof e)return n;if((e=>"object"==typeof e&&null!==e)(n)){const a=n.details;if(n.code===r.MISSING_CAPABILITY){const r=a?.capability;if(n.stage===s.RUNTIME&&"string"==typeof r&&r.includes("FileSystem")){const r=n instanceof Error?n.message:"Upload failed";return new e(r,{code:t.UPLOAD_REQUEST_FAILED,details:a})}return new e("Upload capability is missing for current platform",{code:t.UPLOAD_REQUIRED_FIELD_MISSING,details:a})}if(n.stage===s.UPLOAD)return(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("abort"))})(a)?new e("Upload canceled",{code:t.UPLOAD_ABORTED,details:a}):(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("timeout"))})(a)?new e("Upload timeout",{code:t.UPLOAD_TIMEOUT,details:a}):new e("Upload failed",{code:t.UPLOAD_REQUEST_FAILED,details:a})}const a=n instanceof Error?n.message:"Upload failed";return new e(a,{code:t.UPLOAD_REQUEST_FAILED,details:{cause:n}})},o=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],u=(e,r)=>`${e}\0${r}`,c=(e,r,s)=>{const t={userId:e};for(const n of o){const e=s?.[n]??r?.[n];void 0!==e&&(t[n]=e)}return t},d=e=>c(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),i=(e,r,s)=>{const t=/* @__PURE__ */new Map;if(!e?.getGroupNamecard||!s)return t;for(const n of r){const r=e.getGroupNamecard(n.groupId,n.user.userId,!1);r&&t.set(u(n.groupId,n.user.userId),r.namecard)}return t},f=async(e,r)=>{if(0===e.length||!r)return[];try{return await r({userIds:e})}catch(s){return n.warn("Group user info hydration failed",{userIds:e,error:s}),[]}},I=async(e,r)=>{r&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,s])=>{try{await r(e,s)}catch(t){n.warn("Group namecard hydration failed",{groupId:e,userIds:s,error:t})}}))},l=async e=>{const r=(e=>{const r=[],s=/* @__PURE__ */new Set;for(const t of e){const e=t.groupId.trim(),n=t.user.userId.trim();if(!e||!n)continue;const a=u(e,n);s.has(a)||(s.add(a),r.push({groupId:e,user:{...t.user,userId:n}}))}return r})(e.contexts),s=(e=>{const r=[],s=/* @__PURE__ */new Set;for(const t of e)s.has(t.user.userId)||(s.add(t.user.userId),r.push(t.user.userId));return r})(r),t=((e,r)=>{const s=/* @__PURE__ */new Map;if(!e)return s;for(const n of r){const r=e.getRuntimeUserInfo?.(n,!1)??null;r&&s.set(n,r)}const t=r.filter(e=>!s.has(e));for(const n of e.getUserInfoSummaries?.(t,!1)??[])s.set(n.userId,d(n));return s})(e.cacheManager,s),n=s.filter(e=>!t.has(e)),a=new Set(n),o=i(e.cacheManager,r,e.includeNameCard),l=e.includeNameCard?((e,r,s)=>{const t=/* @__PURE__ */new Map;for(const n of e){const e=n.user.userId,a=u(n.groupId,e);if(!r.has(e)||s.has(a))continue;const o=t.get(n.groupId)??[];o.includes(e)||o.push(e),t.set(n.groupId,o)}return t})(r,a,o):/* @__PURE__ */new Map,[p]=await Promise.all([f(n,e.fetchUserInfos),I(l,e.hydrateGroupNamecards)]),g=new Map(p.map(e=>[e.userId,e])),m=i(e.cacheManager,r,e.includeNameCard),U=/* @__PURE__ */new Map;for(const d of r){const e=d.user.userId,r=u(d.groupId,e),s=c(e,d.user,g.get(e)??t.get(e)),n=m.get(r)??o.get(r);U.set(r,void 0!==n?{...s,nameCard:n}:s)}return{usersByContextKey:U,fetchedUserInfos:p,missingUserIds:n.filter(e=>!g.has(e))}},p=async e=>{const r=await l({...e,contexts:e.users.map(r=>({groupId:e.groupId,user:r}))}),s=/* @__PURE__ */new Map;for(const t of e.users){const n=t.userId.trim();if(!n||s.has(n))continue;const a=r.usersByContextKey.get(u(e.groupId.trim(),n));a&&s.set(n,a)}return{usersById:s,fetchedUserInfos:r.fetchedUserInfos,missingUserIds:r.missingUserIds}};export{l as a,u as g,a as m,p as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{V as e,E as t,p as s,aF as r,c as a,S as n,A as o,l as i,h as c,m as d,j as l}from"./common-BvlDAw4a.js";import{i as u}from"./cache-utils-B99glc0H.js";import{b as p,a as h,n as m}from"./user-info-AlshAvdy.js";import{a as g,b as y,L as I}from"./reflection-proto-codec-7r8Sei3y.js";import{l as f}from"./light-DImBnNes.js";const C=e=>({userId:e}),S=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),R=e=>e,v=async(e,t)=>{const s=(e=>{const t=[],s=/* @__PURE__ */new Set;for(const r of e){const e=r.trim();e&&!s.has(e)&&(s.add(e),t.push(e))}return t})(e),r=/* @__PURE__ */new Map;if(0===s.length)return r;const a=t.cacheManager?.getUserInfoSummaries(s,!1)??[];for(const o of a)r.set(o.userId,S(o));const n=s.filter(e=>!r.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)r.set(t.userId,R(t))}for(const o of s)r.has(o)||r.set(o,C(o));return r},E=async(e,t)=>((e,t,s)=>({userId:s,nickname:t?.nickname??e?.nickname,avatarUrl:t?.avatarUrl??e?.avatarUrl,mail:t?.mail??e?.mail,phone:t?.phone??e?.phone,gender:t?.gender??e?.gender,sign:t?.sign??e?.sign,birth:t?.birth??e?.birth,ext:t?.ext??e?.ext}))(void 0,(await v([e],t)).get(e),e),_={UNSPECIFIED:0,PING:1,PONG:2,REQUEST:3,RESPONSE:4,ERROR:5},T=0,U=0,w=1,N=1001,b=1002,A=1003,k=1004,O=1005,M=1101,D={common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1},cannot_add_self:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,221",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_ON_ROSTER:{code:221,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}},q="User ID is invalid: cannot add yourself as a contact",$=(e,t,s)=>{if(!u(e)||!u(e.data))return;const r=e.data[t];if(Array.isArray(r))for(const a of r)if(u(a)&&"string"==typeof a.failReason&&a.failReason.toLowerCase().includes(s))return a.failReason},P=e=>{const{orgName:t,appName:r}=s(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},F=e=>u(e)&&Array.isArray(e.data)?e.data.filter(e=>"string"==typeof e&&e.length>0):Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[],B=(s,r)=>{if(!Array.isArray(s.userIds)||0===s.userIds.length)throw new e(`${r} is required`,{code:t.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});const a=s.userIds.map((s,a)=>{if("string"!=typeof s)throw new e(`${r}[${a}] must be a string`,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${r}[${a}]`,message:"userId must be a string",rule:"invalid_format"}]}});return s.trim()}),n=(e=>{const t=[],s=/* @__PURE__ */new Set;for(const r of e)r&&!s.has(r)&&(s.add(r),t.push(r));return t})(a);if(0===n.length)throw new e(`${r} is required`,{code:t.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});return n.length!==a.length&&u(s),n},x=async(s,n,o)=>{const i=P(n),c=`/${i.orgName}/${i.appName}/users/${i.encodedUserId}/contacts/apply?resource=${i.encodedResource}`;(s=>{const n=$(s,"applyYourselfUsers","user cannot apply to become a new friend");if(n)throw new e(q,{code:t.VALIDATION_INVALID_FORMAT,details:{api:"addContact",mapped:!0,reasonKey:"cannot_add_self",serverMessage:n,retryable:!1,canonicalCode:t.VALIDATION_INVALID_FORMAT,fields:[{path:"params.userId",message:q,rule:"invalid_format"}]}});const o=$(s,"notExistUsers","the users not exist");if(!o)return;const i=r(D,"addContact",{error:"USER_NOT_FOUND"});if(!i)throw a({apiName:"addContact",serverMessage:o,mapped:!1,reasonKey:"USER_NOT_FOUND"});throw a({apiName:"addContact",entry:i.entry,serverMessage:o,mapped:!0,reasonKey:i.reasonKey,matchedBy:i.matchedBy})})(await s.post(c,{usernames:[o.userId],reason:o.message??""},{operation:"addContact"}))},L=async(e,t)=>{const s=P(t),r=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/blocks/users`,a=await e.get(r,{operation:"getBlocklist"});return F(a).map(e=>({userId:e}))},V=async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`,n=await e.post(a,{usernames:s},{operation:"addUsersToBlocklist"});return{succeeded:F(n).map(e=>({userId:e})),failed:[]}},G={nested:{easemob:{nested:{imfusion:{nested:{gateway:{nested:{v1:{nested:{MessageType:{values:{MESSAGE_TYPE_UNSPECIFIED:0,MESSAGE_TYPE_PING:1,MESSAGE_TYPE_PONG:2,MESSAGE_TYPE_ROSTER_REQUEST:3,MESSAGE_TYPE_ROSTER_RESPONSE:4,MESSAGE_TYPE_ERROR:5}},ServerStatus:{values:{SERVER_STATUS_OK:0,SERVER_STATUS_BUSY:1}},RosterResponseType:{values:{ROSTER_RESPONSE_TYPE_UNSPECIFIED:0,ROSTER_RESPONSE_TYPE_INCREMENTAL:1,ROSTER_RESPONSE_TYPE_FULL:2}},BaseMessage:{fields:{type:{type:"MessageType",id:1}}},GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},requestId:{type:"string",id:3},protocolVersion:{type:"int32",id:4}}},PingRequest:{fields:{type:{type:"MessageType",id:1}}},PongResponse:{fields:{type:{type:"MessageType",id:1},status:{type:"ServerStatus",id:2}}},ErrorDetail:{fields:{type:{type:"MessageType",id:1},code:{type:"string",id:2},message:{type:"string",id:3},header:{type:"GatewayHeader",id:4}}},GetRosterRequest:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},version:{type:"string",id:6},cursor:{type:"uint64",id:7}}},RosterItem:{fields:{contact:{type:"string",id:1},remark:{type:"string",id:2},metadata:{type:"string",id:3},createdAt:{type:"int64",id:4},updatedAt:{type:"int64",id:5},metadataUpdatedAt:{type:"int64",id:6}}},GetRosterResponse:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},data:{rule:"repeated",type:"RosterItem",id:3},cursor:{type:"uint64",id:4},version:{type:"string",id:5},responseType:{type:"RosterResponseType",id:6}}}}}}}}}}}}};let Y=!1,K=null;const H=()=>K||(Y||(f.util.Long=I,f.configure(),Y=!0),g(),K=f.Root.fromJSON(G),y(K),K),W=e=>"number"==typeof e?e:I.isLong(e)?e.toNumber():0,j=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:W(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:W(t.protocolVersion)}};class Q{encodeRequest(e){const t=H().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=T){const t=H().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:_.PONG,status:e})).finish()}decode(e){const t=H(),s=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(s.type){case _.PING:return{type:_.PING};case _.PONG:{const s=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:_.PONG,status:W(s.status)}}case _.RESPONSE:{const s=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:_.RESPONSE,header:j(s.header),data:Array.isArray(s.data)?s.data.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{contact:"string"==typeof t.contact?t.contact:"",remark:"string"==typeof t.remark?t.remark:"",metadata:"string"==typeof t.metadata?t.metadata:"",createdAt:W(t.createdAt),updatedAt:W(t.updatedAt),metadataUpdatedAt:W(t.metadataUpdatedAt)}})(e)):[],cursor:W(s.cursor),version:"string"==typeof s.version?s.version:"",responseType:W(s.responseType)||U}}case _.ERROR:{const s=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:_.ERROR,header:j(s.header),code:"string"==typeof s.code?s.code:"",message:"string"==typeof s.message?s.message:"Unknown roster error"}}default:return{type:"number"==typeof s.type?s.type:_.UNSPECIFIED}}}}class z{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(e){const s=e.header?.requestId;if(s&&s!==this.requestId)throw new n("Roster response requestId mismatched",t.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:s}});if(this.completed)throw new n("Roster response received after completion",t.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new n("Roster response type changed in same session",t.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:e.responseType}});if(this.pages.length>0&&0!==e.cursor&&e.cursor===this.pages[this.pages.length-1]?.cursor)throw new n("Roster cursor duplicated",t.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});return this.responseType=e.responseType,this.version=e.version||this.version,this.pages.push(e),this.nextCursor=e.cursor,this.pageCount+=1,this.completed=0===e.cursor,{done:this.completed,nextCursor:this.nextCursor,pageCount:this.pageCount}}getNextCursor(){return this.nextCursor}getPageCount(){return this.pageCount}hasPages(){return this.pages.length>0}isCompleted(){return this.completed}buildResult(){return{mode:this.responseType===w?"incremental":"full",version:this.version,pages:this.pages}}}const J=e=>e.type===_.RESPONSE,X=e=>"message"in e&&"code"in e;class Z{constructor(e){this.codec=new Q,this.sharedSession=e}async sync(e){const t=new z(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(e,s){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:e.header.requestId,encode:()=>{const t=this.buildAttemptRequest(e,s.getNextCursor());return this.codec.encodeRequest(t)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:J(t)||X(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===_.PING)return void(await r.send(this.codec.encodePong()));if(J(e)){if(!s.push(e).done)return;return{done:!0,result:s.buildResult()}}if(X(e))throw(e=>{const s=e.header?.requestId,r=t=>({stage:"sync_page",serverCode:e.code,requestId:s,retryable:t});switch(Number.parseInt(e.code,10)){case b:return new o(e.message,{code:t.AUTH_UNAUTHORIZED,details:r(!1)});case A:return new n(e.message,t.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case N:return new n(e.message,t.VALIDATION_REQUIRED,{details:r(!1)});case k:return new n(e.message,t.VALIDATION_INVALID_FORMAT,{details:r(!1)});case O:return new n(e.message,t.REST_BUSINESS_UNKNOWN,{details:r(!0)});case M:return new n(e.message,t.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new n(e.message,t.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(e);return}catch(a){throw a instanceof n?a:new n("Roster frame decode failed",t.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:a instanceof Error?a.message:String(a)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const ee=e=>e.versionState.version?"incremental":"full",te=e=>{const{metadata:t,metadataFailed:s,state:r}=e,a=r.versionState.version;return s||!t?{decision:"complete"===r.cacheMeta.cacheIntegrity?ee(r):"full",version:a}:t.requiresSync||"complete"!==r.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===r.cacheMeta.cacheIntegrity&&a?{decision:"incremental",version:t.version||a}:{decision:"full",version:t.version||a}:{decision:"skip",version:t.version||a}},se=e=>{if(!e)return{};try{const t=JSON.parse(e);return{nickname:"string"==typeof t.nickname?t.nickname:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:"string"==typeof t.avatarurl?t.avatarurl:void 0,sign:"string"==typeof t.sign?t.sign:void 0,ext:"string"==typeof t.ext?t.ext:void 0}}catch{return{}}},re=e=>{const t=(e=>{if(!(e instanceof n&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},ae=(e,t,s,r)=>({code:t,stage:e,message:`${e}: ${s}`,retryable:r}),ne=e=>{i.warn("Contact sync duration",e)};class oe{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("contact-sync-cancelled")}async runSync(){const e=this.dependencies.getContextState(),s=Date.now();let r;this.dependencies.onStart();try{const t=await this.dependencies.queryMetadata(e.versionState.version);if(r=te({metadata:t,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void ne({outcome:"skip",decision:r.decision,durationMs:Date.now()-s,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(a){if(re(a)){const r=te({metadataFailed:!0,state:e}),o=a instanceof n?a:new n("Contact metadata request failed",t.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:ae("metadata",o.code,o.message,!1)}),void ne({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:e.versionState.version,stage:"metadata",hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}if(r=te({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:ae("metadata",t.CONTACT_SYNC_METADATA_FAILED,a instanceof Error?a.message:String(a),!0)}),void ne({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const t=await this.dependencies.getSyncUrls(),a=this.dependencies.buildRosterRequest({decision:r.decision,version:e.versionState.version}),n=await new Z(this.dependencies.getSharedSyncSession()).sync({urls:t,request:a}),o=(e=>{const t=[];for(const s of e)for(const e of s.data){const s=se(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:s.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:s.nickname,avatarUrl:s.avatarUrl,sign:s.sign,ext:s.ext}})}return t})(n.pages),i=this.dependencies.applySyncResult({mode:n.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:n.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),ne({outcome:"finish",decision:r.decision,durationMs:Date.now()-s,version:n.version,source:"sync",changed:i.changed,hasUsableSnapshot:i.snapshot.complete})}catch(a){const o=a instanceof n?a:new n("Contact sync failed",t.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:a instanceof Error?a.message:String(a)}}),i=o.details??{},c="string"==typeof i.stage?i.stage:"sync_page";this.dependencies.onFinish({error:ae(c,o.code,o.message,!0)}),ne({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:c,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const ie={items:[],loaded:!1,source:"server"},ce=d(l,D),de=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=ie,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=ie,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(e){return this.runOperation("addContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.validateOptionalString(e.message,"params.message"),r=this.getRestContextOrThrow();if(t===r.userId)throw this.buildValidationError(q,[{path:"params.userId",message:q,rule:"invalid_format"}]);const a=this.getRestClient(r);i.debug("ContactManager addContact",{userId:t,hasMessage:"string"==typeof s&&s.length>0}),await x(a,r,{userId:t,message:s})})}async deleteContact(e){return this.runOperation("deleteContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);i.debug("ContactManager deleteContact",{userId:t}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.delete(a,{operation:"deleteContact"})})(r,s,{userId:t});const a=this.client?.getCacheManager()?.removeContact(t);i.debug("ContactManager deleteContact patched cache",{userId:t,changed:a?.changed??!1})})}async acceptContactInvite(e){return this.runOperation("acceptContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);i.debug("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/accept/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"acceptContactInvite"})})(r,s,{userId:t}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(e){return this.runOperation("declineContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);i.debug("ContactManager declineContactInvite",{userId:t}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/decline/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"declineContactInvite"})})(r,s,{userId:t})})}async setContactRemark(e){return this.runOperation("setContactRemark",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.validateRemark(e.remark,"params.remark"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);i.debug("ContactManager setContactRemark",{userId:t,remarkLength:s.length}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.put(a,{remark:s.remark},{operation:"setContactRemark"})})(a,r,{userId:t,remark:s});const n=this.client?.getCacheManager()?.updateContactRemark(t,s);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),i.debug("ContactManager setContactRemark patched cache",{userId:t,changed:n?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const e=this.getRestContextOrThrow();this.ensureBlocklistSession(e);const t=this.getRestClient(e);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const s=await this.enrichBlocklistUsers(await L(t,e));return this.blocklistSnapshot={items:s,loaded:!0,source:"server"},i.debug("ContactManager getBlocklist",{count:s.length}),s})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=B(e,"params.userIds"),r=this.getRestClient(t);i.debug("ContactManager addUsersToBlocklist",{userIds:s,inputCount:e.userIds.length,normalizedCount:s.length});const a=await V(r,t,s),n=await this.enrichBlocklistUsers(a.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(n),{succeeded:n,failed:await this.enrichBlocklistUsers(a.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=B(e,"params.userIds"),r=this.getRestClient(t);i.debug("ContactManager removeUserFromBlocklist",{userIds:s,inputCount:e.userIds.length,normalizedCount:s.length}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`;await e.request(a,{method:"DELETE",body:{usernames:s},operation:"removeUserFromBlocklist"})})(r,t,s),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(s)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(e,t){try{return await t()}catch(s){const t=this.normalizeSdkError(e,s);throw i.warn(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,s){return s instanceof n?s:s instanceof Error?new n(`ContactManager ${e} failed: ${s.message}`,t.UNKNOWN):new n(`ContactManager ${e} failed`,t.UNKNOWN)}requireClient(){if(!this.client)throw this.buildValidationError("ContactManager is not bound to client",[{path:"contactManager.client",message:"ContactManager is not bound to client",rule:"required"}]);return this.client}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new c(e.restBaseUrl,{errorMap:ce,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}ensureBlocklistSession(e){const t=`${e.restBaseUrl}:${e.userId}:${e.token}`;this.blocklistSessionKey!==t&&(this.blocklistSessionKey=t,this.blocklistSnapshot=ie)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.set(s.userId,s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}patchBlocklistSnapshotWithRemovals(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.delete(s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}validateUserId(e,t){if("string"!=typeof e)throw this.buildValidationError("userId must be a string",[{path:t,message:"userId must be a string",rule:"invalid_format"}]);const s=e.trim();if(!s)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return s}validateOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw this.buildValidationError(`${t} must be a string`,[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]);return e}}validateRemark(e,t){if("string"!=typeof e)throw this.buildValidationError("remark must be a string",[{path:t,message:"remark must be a string",rule:"invalid_format"}]);return e}buildValidationError(s,r){const a=r.some(e=>"invalid_format"===e.rule)?t.VALIDATION_INVALID_FORMAT:t.VALIDATION_REQUIRED;return new e(s,{code:a,details:{fields:r}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await v(e.map(e=>e.userId),{cacheManager:this.requireClient().getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchUserInfos(e)});return e.map(e=>t.get(e.userId)??e)}async fetchUserInfos(e){if(0===e.length)return[];try{const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}catch(t){return i.warn("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),s=p(e),r=await this.getRestClient(t).request(h(t),{method:"POST",body:s,operation:"getUserInfoByUserId"});return m(r,s.targets)}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}createSyncController(e){return new oe(e)}};de.key="contactManager";let le=de;export{le as C,_ as R,E as r};
|
|
1
|
+
import{V as e,E as t,p as s,aL as r,i as a,S as n,A as o,l as i,R as c,m as d,C as l}from"./common-DHQukb7J.js";import{i as u}from"./cache-utils-B99glc0H.js";import{b as p,a as h,n as m}from"./user-info-7QzMa7bR.js";import{a as g,b as y,L as I}from"./reflection-proto-codec-7r8Sei3y.js";import{l as f}from"./light-DImBnNes.js";const C=e=>({userId:e}),S=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),R=e=>e,v=async(e,t)=>{const s=(e=>{const t=[],s=/* @__PURE__ */new Set;for(const r of e){const e=r.trim();e&&!s.has(e)&&(s.add(e),t.push(e))}return t})(e),r=/* @__PURE__ */new Map;if(0===s.length)return r;const a=t.cacheManager?.getUserInfoSummaries(s,!1)??[];for(const o of a)r.set(o.userId,S(o));const n=s.filter(e=>!r.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)r.set(t.userId,R(t))}for(const o of s)r.has(o)||r.set(o,C(o));return r},E=async(e,t)=>((e,t,s)=>({userId:s,nickname:t?.nickname??e?.nickname,avatarUrl:t?.avatarUrl??e?.avatarUrl,mail:t?.mail??e?.mail,phone:t?.phone??e?.phone,gender:t?.gender??e?.gender,sign:t?.sign??e?.sign,birth:t?.birth??e?.birth,ext:t?.ext??e?.ext}))(void 0,(await v([e],t)).get(e),e),_={UNSPECIFIED:0,PING:1,PONG:2,REQUEST:3,RESPONSE:4,ERROR:5},T=0,U=0,w=1,N=1001,b=1002,A=1003,k=1004,O=1005,M=1101,D={common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1},cannot_add_self:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,221",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_ON_ROSTER:{code:221,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}},q="User ID is invalid: cannot add yourself as a contact",$=(e,t,s)=>{if(!u(e)||!u(e.data))return;const r=e.data[t];if(Array.isArray(r))for(const a of r)if(u(a)&&"string"==typeof a.failReason&&a.failReason.toLowerCase().includes(s))return a.failReason},P=e=>{const{orgName:t,appName:r}=s(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},B=e=>u(e)&&Array.isArray(e.data)?e.data.filter(e=>"string"==typeof e&&e.length>0):Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[],F=(s,r)=>{if(!Array.isArray(s.userIds)||0===s.userIds.length)throw new e(`${r} is required`,{code:t.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});const a=s.userIds.map((s,a)=>{if("string"!=typeof s)throw new e(`${r}[${a}] must be a string`,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${r}[${a}]`,message:"userId must be a string",rule:"invalid_format"}]}});return s.trim()}),n=(e=>{const t=[],s=/* @__PURE__ */new Set;for(const r of e)r&&!s.has(r)&&(s.add(r),t.push(r));return t})(a);if(0===n.length)throw new e(`${r} is required`,{code:t.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});return n.length!==a.length&&u(s),n},x=async(s,n,o)=>{const i=P(n),c=`/${i.orgName}/${i.appName}/users/${i.encodedUserId}/contacts/apply?resource=${i.encodedResource}`;(s=>{const n=$(s,"applyYourselfUsers","user cannot apply to become a new friend");if(n)throw new e(q,{code:t.VALIDATION_INVALID_FORMAT,details:{api:"addContact",mapped:!0,reasonKey:"cannot_add_self",serverMessage:n,retryable:!1,canonicalCode:t.VALIDATION_INVALID_FORMAT,fields:[{path:"params.userId",message:q,rule:"invalid_format"}]}});const o=$(s,"notExistUsers","the users not exist");if(!o)return;const i=r(D,"addContact",{error:"USER_NOT_FOUND"});if(!i)throw a({apiName:"addContact",serverMessage:o,mapped:!1,reasonKey:"USER_NOT_FOUND"});throw a({apiName:"addContact",entry:i.entry,serverMessage:o,mapped:!0,reasonKey:i.reasonKey,matchedBy:i.matchedBy})})(await s.post(c,{usernames:[o.userId],reason:o.message??""},{operation:"addContact"}))},L=async(e,t)=>{const s=P(t),r=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/blocks/users`,a=await e.get(r,{operation:"getBlocklist"});return B(a).map(e=>({userId:e}))},V=async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`,n=await e.post(a,{usernames:s},{operation:"addUsersToBlocklist"});return{succeeded:B(n).map(e=>({userId:e})),failed:[]}},G={nested:{easemob:{nested:{imfusion:{nested:{gateway:{nested:{v1:{nested:{MessageType:{values:{MESSAGE_TYPE_UNSPECIFIED:0,MESSAGE_TYPE_PING:1,MESSAGE_TYPE_PONG:2,MESSAGE_TYPE_ROSTER_REQUEST:3,MESSAGE_TYPE_ROSTER_RESPONSE:4,MESSAGE_TYPE_ERROR:5}},ServerStatus:{values:{SERVER_STATUS_OK:0,SERVER_STATUS_BUSY:1}},RosterResponseType:{values:{ROSTER_RESPONSE_TYPE_UNSPECIFIED:0,ROSTER_RESPONSE_TYPE_INCREMENTAL:1,ROSTER_RESPONSE_TYPE_FULL:2}},BaseMessage:{fields:{type:{type:"MessageType",id:1}}},GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},requestId:{type:"string",id:3},protocolVersion:{type:"int32",id:4}}},PingRequest:{fields:{type:{type:"MessageType",id:1}}},PongResponse:{fields:{type:{type:"MessageType",id:1},status:{type:"ServerStatus",id:2}}},ErrorDetail:{fields:{type:{type:"MessageType",id:1},code:{type:"string",id:2},message:{type:"string",id:3},header:{type:"GatewayHeader",id:4}}},GetRosterRequest:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},version:{type:"string",id:6},cursor:{type:"uint64",id:7}}},RosterItem:{fields:{contact:{type:"string",id:1},remark:{type:"string",id:2},metadata:{type:"string",id:3},createdAt:{type:"int64",id:4},updatedAt:{type:"int64",id:5},metadataUpdatedAt:{type:"int64",id:6}}},GetRosterResponse:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},data:{rule:"repeated",type:"RosterItem",id:3},cursor:{type:"uint64",id:4},version:{type:"string",id:5},responseType:{type:"RosterResponseType",id:6}}}}}}}}}}}}};let Y=!1,K=null;const H=()=>K||(Y||(f.util.Long=I,f.configure(),Y=!0),g(),K=f.Root.fromJSON(G),y(K),K),W=e=>"number"==typeof e?e:I.isLong(e)?e.toNumber():0,j=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:W(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:W(t.protocolVersion)}};class Q{encodeRequest(e){const t=H().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=T){const t=H().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:_.PONG,status:e})).finish()}decode(e){const t=H(),s=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(s.type){case _.PING:return{type:_.PING};case _.PONG:{const s=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:_.PONG,status:W(s.status)}}case _.RESPONSE:{const s=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:_.RESPONSE,header:j(s.header),data:Array.isArray(s.data)?s.data.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{contact:"string"==typeof t.contact?t.contact:"",remark:"string"==typeof t.remark?t.remark:"",metadata:"string"==typeof t.metadata?t.metadata:"",createdAt:W(t.createdAt),updatedAt:W(t.updatedAt),metadataUpdatedAt:W(t.metadataUpdatedAt)}})(e)):[],cursor:W(s.cursor),version:"string"==typeof s.version?s.version:"",responseType:W(s.responseType)||U}}case _.ERROR:{const s=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:_.ERROR,header:j(s.header),code:"string"==typeof s.code?s.code:"",message:"string"==typeof s.message?s.message:"Unknown roster error"}}default:return{type:"number"==typeof s.type?s.type:_.UNSPECIFIED}}}}class z{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(e){const s=e.header?.requestId;if(s&&s!==this.requestId)throw new n("Roster response requestId mismatched",t.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:s}});if(this.completed)throw new n("Roster response received after completion",t.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new n("Roster response type changed in same session",t.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:e.responseType}});if(this.pages.length>0&&0!==e.cursor&&e.cursor===this.pages[this.pages.length-1]?.cursor)throw new n("Roster cursor duplicated",t.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});return this.responseType=e.responseType,this.version=e.version||this.version,this.pages.push(e),this.nextCursor=e.cursor,this.pageCount+=1,this.completed=0===e.cursor,{done:this.completed,nextCursor:this.nextCursor,pageCount:this.pageCount}}getNextCursor(){return this.nextCursor}getPageCount(){return this.pageCount}hasPages(){return this.pages.length>0}isCompleted(){return this.completed}buildResult(){return{mode:this.responseType===w?"incremental":"full",version:this.version,pages:this.pages}}}const J=e=>e.type===_.RESPONSE,X=e=>"message"in e&&"code"in e;class Z{constructor(e){this.codec=new Q,this.sharedSession=e}async sync(e){const t=new z(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(e,s){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:e.header.requestId,encode:()=>{const t=this.buildAttemptRequest(e,s.getNextCursor());return this.codec.encodeRequest(t)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:J(t)||X(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===_.PING)return void(await r.send(this.codec.encodePong()));if(J(e)){if(!s.push(e).done)return;return{done:!0,result:s.buildResult()}}if(X(e))throw(e=>{const s=e.header?.requestId,r=t=>({stage:"sync_page",serverCode:e.code,requestId:s,retryable:t});switch(Number.parseInt(e.code,10)){case b:return new o(e.message,{code:t.AUTH_UNAUTHORIZED,details:r(!1)});case A:return new n(e.message,t.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case N:return new n(e.message,t.VALIDATION_REQUIRED,{details:r(!1)});case k:return new n(e.message,t.VALIDATION_INVALID_FORMAT,{details:r(!1)});case O:return new n(e.message,t.REST_BUSINESS_UNKNOWN,{details:r(!0)});case M:return new n(e.message,t.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new n(e.message,t.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(e);return}catch(a){throw a instanceof n?a:new n("Roster frame decode failed",t.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:a instanceof Error?a.message:String(a)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const ee=e=>e.versionState.version?"incremental":"full",te=e=>{const{metadata:t,metadataFailed:s,state:r}=e,a=r.versionState.version;return s||!t?{decision:"complete"===r.cacheMeta.cacheIntegrity?ee(r):"full",version:a}:t.requiresSync||"complete"!==r.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===r.cacheMeta.cacheIntegrity&&a?{decision:"incremental",version:t.version||a}:{decision:"full",version:t.version||a}:{decision:"skip",version:t.version||a}},se=e=>{if(!e)return{};try{const t=JSON.parse(e);return{nickname:"string"==typeof t.nickname?t.nickname:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:"string"==typeof t.avatarurl?t.avatarurl:void 0,sign:"string"==typeof t.sign?t.sign:void 0,ext:"string"==typeof t.ext?t.ext:void 0}}catch{return{}}},re=e=>{const t=(e=>{if(!(e instanceof n&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},ae=(e,t,s,r)=>({code:t,stage:e,message:`${e}: ${s}`,retryable:r}),ne=e=>{i.warn("Contact sync duration",e)};class oe{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("contact-sync-cancelled")}async runSync(){const e=this.dependencies.getContextState(),s=Date.now();let r;this.dependencies.onStart();try{const t=await this.dependencies.queryMetadata(e.versionState.version);if(r=te({metadata:t,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void ne({outcome:"skip",decision:r.decision,durationMs:Date.now()-s,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(a){if(re(a)){const r=te({metadataFailed:!0,state:e}),o=a instanceof n?a:new n("Contact metadata request failed",t.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:ae("metadata",o.code,o.message,!1)}),void ne({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:e.versionState.version,stage:"metadata",hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}if(r=te({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:ae("metadata",t.CONTACT_SYNC_METADATA_FAILED,a instanceof Error?a.message:String(a),!0)}),void ne({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const t=await this.dependencies.getSyncUrls(),a=this.dependencies.buildRosterRequest({decision:r.decision,version:e.versionState.version}),n=await new Z(this.dependencies.getSharedSyncSession()).sync({urls:t,request:a}),o=(e=>{const t=[];for(const s of e)for(const e of s.data){const s=se(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:s.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:s.nickname,avatarUrl:s.avatarUrl,sign:s.sign,ext:s.ext}})}return t})(n.pages),i=this.dependencies.applySyncResult({mode:n.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:n.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),ne({outcome:"finish",decision:r.decision,durationMs:Date.now()-s,version:n.version,source:"sync",changed:i.changed,hasUsableSnapshot:i.snapshot.complete})}catch(a){const o=a instanceof n?a:new n("Contact sync failed",t.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:a instanceof Error?a.message:String(a)}}),i=o.details??{},c="string"==typeof i.stage?i.stage:"sync_page";this.dependencies.onFinish({error:ae(c,o.code,o.message,!0)}),ne({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:c,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const ie={items:[],loaded:!1,source:"server"},ce=d(l,D),de=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=ie,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=ie,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(e){return this.runOperation("addContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.validateOptionalString(e.message,"params.message"),r=this.getRestContextOrThrow();if(t===r.userId)throw this.buildValidationError(q,[{path:"params.userId",message:q,rule:"invalid_format"}]);const a=this.getRestClient(r);i.debug("ContactManager addContact",{userId:t,hasMessage:"string"==typeof s&&s.length>0}),await x(a,r,{userId:t,message:s})})}async deleteContact(e){return this.runOperation("deleteContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);i.debug("ContactManager deleteContact",{userId:t}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.delete(a,{operation:"deleteContact"})})(r,s,{userId:t});const a=this.client?.getCacheManager()?.removeContact(t);i.debug("ContactManager deleteContact patched cache",{userId:t,changed:a?.changed??!1})})}async acceptContactInvite(e){return this.runOperation("acceptContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);i.debug("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/accept/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"acceptContactInvite"})})(r,s,{userId:t}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(e){return this.runOperation("declineContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);i.debug("ContactManager declineContactInvite",{userId:t}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/decline/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"declineContactInvite"})})(r,s,{userId:t})})}async setContactRemark(e){return this.runOperation("setContactRemark",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.validateRemark(e.remark,"params.remark"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);i.debug("ContactManager setContactRemark",{userId:t,remarkLength:s.length}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.put(a,{remark:s.remark},{operation:"setContactRemark"})})(a,r,{userId:t,remark:s});const n=this.client?.getCacheManager()?.updateContactRemark(t,s);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),i.debug("ContactManager setContactRemark patched cache",{userId:t,changed:n?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const e=this.getRestContextOrThrow();this.ensureBlocklistSession(e);const t=this.getRestClient(e);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const s=await this.enrichBlocklistUsers(await L(t,e));return this.blocklistSnapshot={items:s,loaded:!0,source:"server"},i.debug("ContactManager getBlocklist",{count:s.length}),s})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=F(e,"params.userIds"),r=this.getRestClient(t);i.debug("ContactManager addUsersToBlocklist",{userIds:s,inputCount:e.userIds.length,normalizedCount:s.length});const a=await V(r,t,s),n=await this.enrichBlocklistUsers(a.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(n),{succeeded:n,failed:await this.enrichBlocklistUsers(a.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=F(e,"params.userIds"),r=this.getRestClient(t);i.debug("ContactManager removeUserFromBlocklist",{userIds:s,inputCount:e.userIds.length,normalizedCount:s.length}),await(async(e,t,s)=>{const r=P(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`;await e.request(a,{method:"DELETE",body:{usernames:s},operation:"removeUserFromBlocklist"})})(r,t,s),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(s)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(e,t){try{return await t()}catch(s){const t=this.normalizeSdkError(e,s);throw i.warn(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,s){return s instanceof n?s:s instanceof Error?new n(`ContactManager ${e} failed: ${s.message}`,t.UNKNOWN):new n(`ContactManager ${e} failed`,t.UNKNOWN)}requireClient(){if(!this.client)throw this.buildValidationError("ContactManager is not bound to client",[{path:"contactManager.client",message:"ContactManager is not bound to client",rule:"required"}]);return this.client}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new c(e.restBaseUrl,{errorMap:ce,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}ensureBlocklistSession(e){const t=`${e.restBaseUrl}:${e.userId}:${e.token}`;this.blocklistSessionKey!==t&&(this.blocklistSessionKey=t,this.blocklistSnapshot=ie)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.set(s.userId,s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}patchBlocklistSnapshotWithRemovals(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.delete(s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}validateUserId(e,t){if("string"!=typeof e)throw this.buildValidationError("userId must be a string",[{path:t,message:"userId must be a string",rule:"invalid_format"}]);const s=e.trim();if(!s)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return s}validateOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw this.buildValidationError(`${t} must be a string`,[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]);return e}}validateRemark(e,t){if("string"!=typeof e)throw this.buildValidationError("remark must be a string",[{path:t,message:"remark must be a string",rule:"invalid_format"}]);return e}buildValidationError(s,r){const a=r.some(e=>"invalid_format"===e.rule)?t.VALIDATION_INVALID_FORMAT:t.VALIDATION_REQUIRED;return new e(s,{code:a,details:{fields:r}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await v(e.map(e=>e.userId),{cacheManager:this.requireClient().getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchUserInfos(e)});return e.map(e=>t.get(e.userId)??e)}async fetchUserInfos(e){if(0===e.length)return[];try{const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}catch(t){return i.warn("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),s=p(e),r=await this.getRestClient(t).request(h(t),{method:"POST",body:s,operation:"getUserInfoByUserId"});return m(r,s.targets)}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}createSyncController(e){return new oe(e)}};de.key="contactManager";let le=de;export{le as C,_ as R,E as r};
|