easemob-websdk 5.1.3 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-types.d.ts +2 -2
- package/chat-client.d.ts +17 -2
- package/chunks/chat-manager-BB7wYWYG.js +2 -0
- package/chunks/chat-manager-auF_3s3R.cjs +1 -0
- package/chunks/common-Cg-lTASK.cjs +1 -0
- package/chunks/common-gbNWJrBc.js +1 -0
- package/chunks/{group-user-info-resolver-B-dyr__b.cjs → group-user-info-resolver-BNwtC7dY.cjs} +1 -1
- package/chunks/{group-user-info-resolver-D6AQAHEE.js → group-user-info-resolver-rs5Fnr0l.js} +1 -1
- package/chunks/index-BUNbI8gf.cjs +1 -0
- package/chunks/index-BxMCMoWN.js +1 -0
- package/chunks/index-C7fO2X0x.cjs +1 -0
- package/chunks/index-C_EMU0-3.js +1 -0
- package/chunks/index-CsqE2tfH.js +1 -0
- package/chunks/index-DeJuR3uW.cjs +1 -0
- package/chunks/index-Dknccp9Q.js +1 -0
- package/chunks/index-P1vnLSK2.cjs +1 -0
- package/chunks/multibody-content-BHb-Au8Q.js +1 -0
- package/chunks/multibody-content-BmdQukoX.cjs +1 -0
- package/chunks/{push-manager-CSIKhoPe.js → push-manager-BO3xq-7O.js} +1 -1
- package/chunks/{push-manager-D7RDsKuv.cjs → push-manager-DMI0G9v9.cjs} +1 -1
- package/chunks/reflection-proto-codec-B1apL0ws.js +1 -0
- package/chunks/reflection-proto-codec-CYglS_mx.cjs +1 -0
- package/chunks/session-list-query-DMe2GZ4v.cjs +1 -0
- package/chunks/session-list-query-Inseic9m.js +1 -0
- package/chunks/{user-info-DH3aE1gm.cjs → user-info-B5St7axd.cjs} +1 -1
- package/chunks/{user-info-7QzMa7bR.js → user-info-BkqJHgja.js} +1 -1
- package/core/index.d.ts +1 -1
- package/core/message/attachment-downloader.d.ts +4 -1
- package/core/message/message-sender.d.ts +19 -4
- package/core/message/prepare-text-translation.d.ts +7 -0
- package/index.cjs +1 -1
- package/index.d.ts +3 -2
- package/index.js +2 -2
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-manager.d.ts +128 -7
- package/managers/chat-thread/index.cjs +1 -1
- package/managers/chat-thread/index.js +1 -1
- package/managers/chatroom/index.cjs +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.cjs +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.cjs +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.cjs +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.js +1 -1
- package/managers/user-info/index.cjs +1 -1
- package/managers/user-info/index.js +1 -1
- package/message/combine-payload-codec.d.ts +2 -2
- package/message/combine-payload-file.d.ts +11 -0
- package/message/create-message.d.ts +16 -4
- package/message/create-multibody-message.d.ts +31 -0
- package/message/message-snapshot.d.ts +2 -1
- package/message/multibody-content.d.ts +35 -0
- package/message/translations.d.ts +7 -0
- package/package.json +1 -1
- package/platform/image/miniapp-image-processor.d.ts +10 -6
- package/protocol/msync/codec.d.ts +3 -0
- package/protocol/msync/message-payload-decoder.d.ts +5 -1
- package/protocol/session-list/payload-decoder.d.ts +2 -2
- package/types/chat-manager.d.ts +2 -2
- package/types/conversation.d.ts +2 -2
- package/types/index.d.ts +33 -9
- package/types/message-create.d.ts +130 -2
- package/upload/attachment-uploader.d.ts +8 -0
- package/validators/message-create.d.ts +25 -2
- package/chunks/chat-manager-BI-6bEor.cjs +0 -1
- package/chunks/chat-manager-nXOTpJ01.js +0 -2
- package/chunks/common-DHQukb7J.js +0 -1
- package/chunks/common-tHGz9VBk.cjs +0 -1
- package/chunks/index-CneY58NJ.js +0 -1
- package/chunks/index-DJPAjXAp.cjs +0 -1
- package/chunks/index-DtWkVcfb.cjs +0 -1
- package/chunks/index-DxjmfFL7.js +0 -1
- package/chunks/reflection-proto-codec-7r8Sei3y.js +0 -1
- package/chunks/reflection-proto-codec-CwrIKT1L.cjs +0 -1
- package/chunks/session-list-query-C3iQvQxK.cjs +0 -1
- package/chunks/session-list-query-Cdpiw_IZ.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";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.AUTH_UNAUTHORIZED,o),this.name="AuthenticationError"}}class n extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class a extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="RestTransportError"}}class E extends s{constructor(t,o){super(t,o?.code??e.REST_BUSINESS_UNKNOWN,o),this.name="RestBusinessError"}}class p extends s{constructor(t,o){super(t,o?.code??e.UPLOAD_REQUEST_FAILED,o),this.name="UploadError"}}const T={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"},c=e=>"undefined"!=typeof Blob&&e instanceof Blob,_=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),o=t.length>0?t[t.length-1]:void 0;if(o)return o},O=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const o=e.slice(t+1).toLowerCase();return T[o]},u=(e,t)=>{for(const o of t){const t=e[o];if("string"==typeof t&&t.length>0)return t}},d=e=>{const t=e.file,o=e.sourceMeta,r=t.name||(o?u(o,["name","fileName","filename"]):void 0),s=e.file.type||(o?u(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),n=l({fileName:r,fileType:s,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:n.fileName,mimeType:n.fileType,size:n.fileSize},fileName:n.fileName,fileType:n.fileType,fileSize:n.fileSize,webFile:e.file}},l=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),R=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(c(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(c(e))return e}})(t);if(i)return d({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=_(t.path),i=l({fileName:t.name??e,fileType:t.type??O(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=_(t.uri),i=l({fileName:t.name??e,fileType:t.type??O(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 n=l({fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"web-file",name:n.fileName,mimeType:n.fileType,size:n.fileSize},fileName:n.fileName,fileType:n.fileType,fileSize:n.fileSize}},I="CHAT",A="GROUP",N="ROOM",m="original",S="large",h=e=>/^https?:\/\//i.test(e),f=t=>{const o=t.split("#");if(2!==o.length||!o[0]||!o[1])throw new p("Invalid appKey for upload",{code:e.UPLOAD_INVALID_APPKEY,details:{appKey:t}});return{orgName:o[0],appName:o[1]}},C=(e,t)=>M(e,{size:t}),y=e=>{try{return decodeURIComponent(e)}catch{return e}},M=(e,t)=>{const[o="",r]=e.split("#",2),[s,i=""]=o.split("?",2),n=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const o=encodeURIComponent(e),r=n.filter(t=>{const[r=""]=t.split("=",2);return r!==o&&y(r)!==e});n.length=0,n.push(...r),void 0!==t&&n.push(`${o}=${encodeURIComponent(String(t))}`)}),`${s}${n.length>0?`?${n.join("&")}`:""}${r?`#${r}`:""}`},D=(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=y(t),s=y(o);return"size"!==r||!["big","large","thumbnail","small"].includes(s)}).join("&");return`${r}${i?`?${i}`:""}${o?`#${o}`:""}`})(e);return{originalImageUrl:o,bigImageUrl:C(o,"large"),thumbnailUrl:C(o,"small")}},U=e=>new Promise(t=>{setTimeout(t,e)});const L=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 U(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:n}=this.context;if(!(t&&o&&r&&s&&n))return!1;let a="",E="";try{const e=f(o);a=e.orgName,E=e.appName}catch{return!1}const p=`${t}/${a}/${E}/sdk/users/${r}/client/logs`,T={resource:i??"webim",logContent:e};try{const e=await n.request({url:p,method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body:T,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}}},g="[MASKED]",P=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),b=e=>!!e&&P.has((e=>e.toLowerCase())(e)),G=(e,t,o)=>{const r=o??new WeakSet;if("string"==typeof e)return((e,t)=>b(t)?g: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=>G(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))b(o)?t[o]=g:t[o]=G(s,o,r);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},H="undefined"!=typeof document;let w=null,x=!1;const B={DEBUG:0,WARN:1,ERROR:2};class F{constructor(e="WARN"){this.consoleEnabled=!0,this.level=e}setLevel(e){this.level=e}setConsoleEnabled(e){this.consoleEnabled=e}shouldLog(e){return B[e]>=B[this.level]}emit(e,t,o){const r=(e=>{const t=new WeakSet;return e.map(e=>G(e,void 0,t))})(o),s=((e,t,o)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:o}))(e,t,r);if(L.append(s),this.consoleEnabled){const o=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")}`}]`;H?console.log(`%c${s}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(s,t,...r)}const i=w;i&&!x&&Promise.resolve().then(()=>{if(i===w){x=!0;try{i(s)}catch{}finally{x=!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 v=new F;const k={debug:(e,...t)=>v.debug(e,...t),warn:(e,...t)=>v.warn(e,...t),error:(e,...t)=>v.error(e,...t)},K={INIT:"init",REQUEST:"request",UPLOAD:"upload",SOCKET:"socket",PROTO:"proto",RUNTIME:"runtime",STORAGE:"storage"},V={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"},q=(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},W=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],$=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 W)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}:{}})},Y=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},j=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}},z=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(o){const r=o.method??"GET",s={...o.headers??{}},i=new AbortController,n=o.timeoutMs??e?.timeoutMs??15e3;let a=!1;const E=()=>i.abort(o.signal?.reason);o.signal?.aborted?E():o.signal?.addEventListener("abort",E,{once:!0});const p=setTimeout(()=>{a=!0,i.abort()},n),T=((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:T,signal:i.signal});let n;if("arraybuffer"===o.responseType)n=await e.arrayBuffer();else if("text"===o.responseType)n=await e.text();else if("json"===o.responseType)n=await j(e,!0);else{const t=e.headers.get("content-type")??"";n=await j(e,t.includes("application/json"))}return{status:e.status,statusText:e.statusText,headers:Y(e.headers),data:n}}catch(c){const e=((e,t,o)=>t?"timeout":o?.aborted||e instanceof Error&&"AbortError"===e.name?"abort":"network")(c,a,o.signal);throw q("Request adapter execution failed.",{code:V.REQUEST_FAILED,stage:K.REQUEST,retryable:"abort"!==e,details:{url:o.url,method:r,reason:e,cause:c instanceof Error?c.message:String(c)}})}finally{clearTimeout(p),o.signal?.removeEventListener("abort",E)}}}},X=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,Q="X-Request-Id",J="direct";class Z{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 ee{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 te={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},oe=()=>{const e=$(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class re{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??oe;const t=new ee({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 Z({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:te[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,n=`req_${this.randomId()}`,a=0,E="";const p=()=>!s&&!i&&this.session?.sessionId===t,T=(t,r,s,i,n)=>{p()&&(a=n.success?0:n.code,E=n.success?"":n.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:n.code,codeDesc:n.description??"",isLastApi:0,isSuccess:n.success?1:0,accessChannel:this.session?.accessChannel??J,msgId:e.msgId,messageType:e.messageType,resultCount:n.resultCount}))},c=(e,t,o,r)=>{const s=this.now();let i=!1;return{retry:()=>(r.next+=1,c(e,t,r.next,r)),finish:r=>{i||(i=!0,T(e,t,o,s,r))}}};return{startRequest:(e={})=>(n=`req_${this.randomId()}`,c(e,n,1,{next:1})),finish:t=>{p()&&(s=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:n,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-r),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??E,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??J,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 se;const ie=e=>{if("disabled"!==se?.state)return se?.startOperation(e)},ne=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},ae=()=>z({fetchImpl:ne()})??{request:e=>Promise.reject(q("Request capability is missing for current platform.",{code:V.MISSING_CAPABILITY,stage:K.REQUEST,retryable:!1,details:{capability:"request"}}))},Ee=e=>e??ae(),pe=(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 Te(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),n="string"==typeof r.error_description?r.error_description:"string"==typeof r.message?r.message:"string"==typeof r.desc?r.desc:void 0,a=(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(pe(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(n)for(const[r,s]of Object.entries(e))if(Array.isArray(s.aliases)&&s.aliases.includes(n))return o(r,s,"alias")},E=t?e.apis[t]:void 0,p=E?a(E.errors):void 0;if(p)return p;for(const T of Object.values(e.common)){const e=a(T.errors,!0);if(e)return e}}function ce(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 E(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 _e={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"}},Oe=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();exports.AuthenticationError=i,exports.COMMON_ERROR_MAP={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:{}},exports.CONNECT_TIMEOUT=1e4,exports.ConnectionError=class extends s{constructor(t,o){super(t,o?.code??e.CONNECTION_WEBSOCKET_ERROR,o),this.name="ConnectionError"}},exports.DATA_REPORT_CORRELATION_LIMIT=1e3,exports.DEFAULT_PART_SIZE=5242880,exports.ERROR_CODES=e,exports.GROUP_NAMECARD_HYDRATION_BATCH_SIZE=50,exports.GROUP_NAMECARD_HYDRATION_MAX_CONCURRENCY=5,exports.GROUP_NAMECARD_HYDRATION_MIN_WINDOW_MS=1e3,exports.GROUP_NAMECARD_HYDRATION_WINDOW_MS=7e3,exports.GROUP_SHARED_FILE_DOWNLOAD_TIMEOUT=6e4,exports.GROUP_SHARED_FILE_UPLOAD_TIMEOUT=3e5,exports.HEARTBEAT_INTERVAL=3e4,exports.HEARTBEAT_TIMEOUT=6e4,exports.IMAGE_TYPE_ORIGINAL=m,exports.LOGIN_TIMEOUT_DEFAULT=3e4,exports.LOGIN_TIMEOUT_MAX=12e4,exports.LOGIN_TIMEOUT_MIN=5e3,exports.MANAGER_SESSION_ENDING_TIMEOUT=6e3,exports.MAX_POOL=4,exports.MESSAGE_TIMEOUT=15e3,exports.MULTIPART_THRESHOLD=5242880,exports.MessageReceiveError=class extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_DECODE_FAILED,o),this.name="MessageReceiveError"}},exports.MessageSendError=class extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_SEND_FAILED,o),this.name="MessageSendError"}},exports.NATIVE_PUSH_BIND_MAX_RETRIES=2,exports.NATIVE_PUSH_BIND_REQUEST_TIMEOUT=5e3,exports.NATIVE_PUSH_BIND_RETRY_DELAYS=[1e3,2e3],exports.NATIVE_PUSH_REMOVE_MAX_RETRIES=1,exports.NATIVE_PUSH_REMOVE_REQUEST_TIMEOUT=2500,exports.NATIVE_PUSH_REMOVE_RETRY_DELAY=500,exports.NetworkError=class extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="NetworkError"}},exports.PLATFORM_ERROR_CODE=V,exports.PLATFORM_ERROR_STAGE=K,exports.PROVISION_TIMEOUT=1e4,exports.RECONNECT_BACKOFF_MULTIPLIER=2,exports.RECONNECT_INITIAL_DELAY=1e3,exports.RECONNECT_MAX_DELAY=6e4,exports.REQUEST_ID_HEADER=Q,exports.REQUEST_TIMEOUT=15e3,exports.RUNTIME_PLATFORMS={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"},exports.RestBusinessError=E,exports.RestClient=class{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=Ee(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 a={...o.operation?{api:o.operation}:{},url:o.url,method:o.method,httpStatus:t,serverCode:r,serverMessage:s,mapped:!1};if(400===t)return new n("Invalid request parameters",{code:e.VALIDATION_UNKNOWN,details:{...a,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 i(t?"Authentication token expired":"Authentication failed",{code:o,details:{...a,reasonKey:t?"token_expired":"unauthorized",canonicalCode:o}})}return 403===t?new i("Access forbidden",{code:e.AUTH_FORBIDDEN,details:{...a,canonicalCode:e.AUTH_FORBIDDEN}}):429===t?new E("REST rate limit exceeded",{code:e.SERVICE_LIMIT_EXCEEDED,details:{...a,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:e.SERVICE_LIMIT_EXCEEDED}}):t>=500?new E("REST business error: request failed",{code:e.REST_BUSINESS_UNKNOWN,details:{...a,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",n=Date.now(),E=this.sanitizeUrl(r);k.debug("REST request",{method:i,url:E,operation:o.operation});const p=o.operation?(e=>{const t=_e[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_${Oe(e)}`,operationType:o}})(o.operation):void 0,T=p?ie(p):void 0,c=T?.startRequest({requestName:p?.operationName,method:i,url:r});let _=0;const O={...this.defaultHeaders,...o.headers};if(this.includeRequestId&&(O[Q]=X()),o.body&&"GET"!==i){const e=Object.keys(O).some(e=>"content-type"===e.toLowerCase());"string"==typeof o.body?e||(O["Content-Type"]="application/x-www-form-urlencoded"):e||(O["Content-Type"]="application/json")}else if("GET"===i)for(const e of Object.keys(O))"content-type"===e.toLowerCase()&&delete O[e];try{const e=await this.requestAdapter.request({url:r,method:i,headers:O,body:o.body,timeoutMs:o.timeout??this.timeout});_=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()-n;(e.status<200||e.status>=300)&&(k.warn("REST response error",{method:i,url:E,status:e.status,duration:s}),this.handleErrorPayload(e.status,e.statusText??"",t,{operation:o.operation,url:r,method:i})),k.debug("REST response",{method:i,url:E,status:e.status,duration:s});const a=(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:a}),T?.finish({code:0,success:!0,resultCount:a}),t}catch(u){const t=0!==_?_:u instanceof s?u.code:-1,n=u instanceof Error?u.message:String(u);if(c?.finish({code:t,success:!1,description:n}),T?.finish({code:t,success:!1,description:n}),u instanceof s)throw u;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})(u);if(u instanceof Error&&"AbortError"===u.name||"timeout"===p)throw k.warn("REST request timeout",{method:i,url:E,timeout:o.timeout??this.timeout}),new a(`Request timeout: ${r}`,{code:e.REST_TIMEOUT,details:{url:r,method:i,timeout:o.timeout??this.timeout}});throw k.warn("REST request failed",{method:i,url:E}),new a(`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:{},n=((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),E=n?{...i,code:n.code,message:n.message}:r,p=Te(this.errorMap,s.operation,E),T="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 n?.code||"string"==typeof n?.code?n.code:void 0,_="string"==typeof i.message?i.message:"string"==typeof i.error_description?i.error_description:"string"==typeof i.desc?i.desc:"string"==typeof n?.message?n.message:void 0,O=!!(401!==t&&403!==t||void 0!==T&&"unauthorized"!==T&&"auth_failed"!==T&&"forbidden"!==T)&&(void 0!==T||"string"==typeof i.error_description||"string"==typeof i.message||"string"==typeof i.desc);if(s.operation&&p)throw ce({apiName:s.operation,entry:p.entry,serverCode:c,serverMessage:_,httpStatus:t,mapped:!0,reasonKey:p.reasonKey,matchedBy:p.matchedBy});const u=this.buildHttpStatusFallbackError(t,s,c,_);if(u)throw u;if(s.operation&&O)throw ce({apiName:s.operation,serverCode:c,serverMessage:_,httpStatus:t,mapped:!1,reasonKey:T});throw new a(`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})}},exports.RestTransportError=a,exports.SDKError=s,exports.SEND_CONNECTION_RECOVERY_TIMEOUT=1e4,exports.SESSION_LIST_SYNC_OVERLAP_MS=2e4,exports.SOCKET_READY_STATE={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},exports.SYNC_WEBSOCKET_COMPLETE_CLOSE_DELAY=0,exports.SYNC_WEBSOCKET_CONNECT_TIMEOUT=5e3,exports.SYNC_WEBSOCKET_IDLE_TIMEOUT=1e4,exports.SYNC_WEBSOCKET_RETRY_BACKOFF_MULTIPLIER=2,exports.SYNC_WEBSOCKET_RETRY_INITIAL_DELAY=1e3,exports.SYNC_WEBSOCKET_RETRY_MAX_DELAY=5e3,exports.StorageError=class extends s{constructor(t,o){super(t,o?.code??e.STORAGE_OPERATION_FAILED,o),this.name="StorageError"}},exports.UPLOAD_TIMEOUT=3e5,exports.USER_INFO_HYDRATION_BATCH_SIZE=20,exports.USER_INFO_HYDRATION_MAX_CONCURRENCY=3,exports.USER_INFO_HYDRATION_MAX_RETRIES=1,exports.USER_INFO_HYDRATION_WINDOW_MS=7e3,exports.UploadError=p,exports.ValidationError=n,exports.appendAttachUrlParams=(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:M(e,o)},exports.appendUrlQueryParams=M,exports.applyDataReportDnsSwitch=e=>{se?.applyDnsSwitch(e)},exports.buildAttachmentPrecheckDecision=e=>{const t=(o=e.messageType,r=e.imageType,"image"!==o?"attachment":r===m?"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"}},exports.buildUploadResult=t=>{const o=t.response.entities?.[0];if(!o?.uuid)throw new p("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,n="string"==typeof s["content-type"]?s["content-type"]:t.fileType,a=`${t.restBaseUrl}/${t.orgName}/${t.appName}/chatfiles/${o.uuid}`;if("image"===t.messageType){const e=(t.imageType??S)===m;return{...D(a,{deriveVariants:!t.useCustomAttachmentUpload}),isOriginalImage:e,secret:r,fileLength:i,filetype:n,filename:t.fileName,width:t.width,height:t.height}}const E="video"===t.messageType?`${a}?vframe=true`:void 0;return{url:a,secret:r,fileLength:i,filetype:n,filename:t.fileName,thumbnailUrl:E}},exports.createPlatformError=q,exports.createRestBusinessError=ce,exports.createTraceId=X,exports.createWebRequestAdapter=z,exports.deriveImageUrls=D,exports.fromProtocolImageType=e=>2===e?S:m,exports.getRuntimeGlobal=$,exports.installDataReporter=e=>(se?.reset(),se=new re(e),se),exports.isRemoteUrl=h,exports.isSDKError=function(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},exports.logger=k,exports.mergeRuntimeErrorMaps=(...e)=>{const t={},o={};for(const r of e)Object.assign(t,r.common),Object.assign(o,r.apis);return{common:t,apis:o}},exports.normalizeAttachmentFile=(t,o)=>{if(!t)throw new p("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=R({file:t,fallbackName:o.filename,fallbackMimeType:o.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new p("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s},exports.normalizeUploadSource=R,exports.parseAppKey=f,exports.parseAttachmentPrecheckResult=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,n=i?.["exists-type"]??i?.existsType,a="origin"===n?m:n===S||n===m?n:void 0,E="string"==typeof o?.["share-secret"]?o["share-secret"]:void 0;if(r&&!s)throw new p("Upload precheck response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{uuid:s,exists:r,existsType:a,shareSecret:E,hit:(T={exists:r,uuid:s},T.exists&&"string"==typeof T.uuid&&T.uuid.length>0)};var T},exports.reportLogsNow=async function(){await L.reportNow()},exports.resetDataReporter=()=>{se?.reset(),se=void 0},exports.resolveApiBusinessError=Te,exports.resolveImageSendPolicy=e=>e.isGif?{resolvedImageType:m,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:m,reason:"explicit-original"}:{resolvedImageType:S,reason:"default-large"},exports.resolveRequestAdapter=Ee,exports.sanitizeErrorUrl=o,exports.setConsoleLogEnabled=function(e){v instanceof F&&v.setConsoleEnabled(e)},exports.setLogEntrySink=function(e){w=e},exports.setLogLevel=function(e){v instanceof F&&v.setLevel(e)},exports.setLogReportInterval=function(e){L.updateReportInterval(e)},exports.setLogReportState=function(e){L.setState(e)},exports.shouldUploadByUrl=(e,t)=>!!t||(!e||!h(e)),exports.startDataReportOperation=ie,exports.startDataReportSession=e=>se?.startSession(e),exports.stopLogReporter=function(){L.stop()},exports.toProtocolImageType=e=>e===m?1:2,exports.toUploadChatType=e=>"singleChat"===e?I:"groupChat"===e?A:N,exports.toUploadImageType=e=>e===m?"origin":"large",exports.updateDataReportNetworkType=e=>{se?.updateNetworkType(e)},exports.updateDataReportSession=e=>{se?.updateSession(e)},exports.updateLogReportContext=function(e){L.updateContext(e)};
|
package/chunks/index-CneY58NJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const e=require("./cache-utils-gowrxNr8.cjs"),t=require("./common-tHGz9VBk.cjs"),r=require("./profile-version-njNs7R5-.cjs"),o=require("./group-user-info-resolver-B-dyr__b.cjs"),s=require("./event-system-TYhmgy4K.cjs"),n=require("./query-params-BHyPuD2k.cjs"),a=require("./user-info-DH3aE1gm.cjs"),i=require("./light-BcQg8h2W.cjs"),u=require("./reflection-proto-codec-CwrIKT1L.cjs"),p=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],d=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),c=e=>({userId:e}),m=(e,t,r)=>{const o={userId:r};for(const s of p){const r=t?.[s]??e?.[s];void 0!==r&&(o[s]=r)}return o},l=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),o=new Map;if(0===r.length)return o;const s=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const a of s)o.set(a.userId,d(a));const n=r.filter(e=>!o.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)o.set(t.userId,t)}for(const a of r)o.has(a)||o.set(a,c(a));return o},h=t=>e.isRecord(t)?t:null,g=e=>{if("string"==typeof e)return e},I=e=>{const t=g(e)?.trim();return t||void 0},y=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},f=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},R=e=>{const t=h(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},_=e=>{const t=h(e);return t?h(t.data)?t.data:t:null},G=(e,t)=>{const r=h(e),o=r&&h(r.params),s=o?.[t];if(Array.isArray(s)&&0!==s.length)return y(s[0])},v=(e,t)=>{const r=(e=>{const t=h(e);return t?y(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},w=e=>I(e.groupId)??I(e.groupid)??I(e.id)??"",S=e=>g(e.name)??g(e.groupname)??g(e.groupName)??"",E=e=>{const t=R(e),r=h(t[0])??_(e)??{},o=(e=>{const t=h(e);if(!t)return null;const r=w(t);return r?{groupId:r,name:S(t),description:g(t.description),memberCount:y(t.memberCount)??y(t.affiliations_count),public:f(t.public),joinApprovalRequired:f(t.joinApprovalRequired)??f(t.approval)??f(t.membersonly)??f(t.members_only),allowInvites:f(t.allowInvites)??f(t.allowinvites)??f(t.allow_user_invites),maxMembers:y(t.maxMembers)??y(t.maxusers),role:I(t.role)??I(t.permission),disabled:f(t.disabled)}:null})(r)??{groupId:w(r),name:S(r)},s=I(r.owner)??I(r.admin)??I(r.member),n=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>h(e)).filter(e=>null!==e).map(e=>y(e.joined_time)).find(e=>void 0!==e);return{...o,owner:s?c(s):void 0,inviteNeedConfirm:f(r.inviteNeedConfirm)??f(r.invite_need_confirm),muteAllMembers:f(r.mute),ext:g(r.ext)??g(r.custom),createdAt:y(r.createdAt)??y(r.created),joinedAt:n,avatarUrl:g(r.avatar),messageBlocked:f(r.messageBlocked)??f(r.isMessageBlocked)??f(r.shieldgroup)}},b=e=>c(e),C=e=>R(e).map(e=>I(e)).filter(e=>Boolean(e)).map(e=>b(e)),A=e=>{const t=h(e);if(!t)return null;const r=I(t.fileId)??I(t.file_id);if(!r)return null;const o=g(t.fileName)??g(t.file_name)??r,s=I(t.fileOwner)??I(t.file_owner);return{fileId:r,fileName:o,fileOwner:s?b(s):void 0,fileSize:y(t.fileSize)??y(t.file_size),createdAt:y(t.createdAt)??y(t.created)}},U=100,O=3e3,D=e=>({...e}),N=e=>"object"==typeof e&&null!==e,T=e=>"DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e?e:"mentionOnly"===e?"AT":"mute"===e?"NONE":"default"===e?"DEFAULT":2===e?"AT":3===e?"NONE":0===e?"DEFAULT":1===e?"ALL":void 0;class M{constructor(e,t){this.groupId=e,this.manager=t}getSummary(){return this.manager.getGroupSummaryForHandle(this.groupId)}getDetail(){return this.manager.getGroupDetailForHandle(this.groupId)}refresh(){return this.manager.refreshGroupDetailForHandle(this.groupId)}updateInfo(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}updateConfigs(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}changeOwner(e){return this.manager.changeGroupOwner({groupId:this.groupId,newOwner:e.newOwner})}destroy(){return this.manager.destroyGroup(this.toTarget())}leave(){return this.manager.leaveGroup(this.toTarget())}getMembers(e={}){return this.manager.getGroupMemberList({groupId:this.groupId,...e})}removeMembers(e){return this.manager.removeGroupMembers(this.toUserBatchParams(e))}getAdmins(){return this.manager.getGroupAdminList(this.toTarget())}addAdmin(e){return this.manager.addGroupAdmin({groupId:this.groupId,userId:e.userId})}removeAdmin(e){return this.manager.removeGroupAdmin({groupId:this.groupId,userId:e.userId})}getMuteList(e){return this.manager.getGroupMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteGroupMembers({groupId:this.groupId,userIds:e.userIds,muteDuration:e.muteDuration})}unmuteMembers(e){return this.manager.unmuteGroupMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllGroupMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllGroupMembers(this.toTarget())}getBlocklist(e){return this.manager.getGroupBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockGroupMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockGroupMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getGroupAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToGroupAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromGroupAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInGroupAllowList({groupId:this.groupId})}checkIfInMuteList(){return this.manager.checkIfInGroupMuteList(this.toTarget())}getAnnouncement(){return this.manager.getGroupAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateGroupAnnouncement({groupId:this.groupId,announcement:e.announcement})}getSharedFileList(e={}){return this.manager.getGroupSharedFileList({groupId:this.groupId,...e})}uploadSharedFile(e){return this.manager.uploadGroupSharedFile({groupId:this.groupId,...e})}deleteSharedFile(e){return this.manager.deleteGroupSharedFile({groupId:this.groupId,fileId:e.fileId})}downloadSharedFile(e){return this.manager.downloadGroupSharedFile({groupId:this.groupId,...e})}setMemberAttributes(e){return this.manager.setGroupMemberAttributes({groupId:this.groupId,userId:e.userId,memberAttributes:e.memberAttributes})}getMembersAttributes(e){return this.manager.getGroupMembersAttributes({groupId:this.groupId,userIds:e.userIds,keys:e.keys})}toTarget(){return{groupId:this.groupId}}toUserBatchParams(e){return{groupId:this.groupId,userIds:e.userIds}}}const L=e=>{const{orgName:r,appName:o}=t.parseAppKey(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},F=e=>new t.ValidationError(`${e} is required`,{code:t.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),P=(e,r)=>new t.ValidationError(r,{code:t.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:r,rule:"invalid_format"}]}}),x=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw F(t);const r=[],o=new Set;if(e.forEach((e,s)=>{if("string"!=typeof e)throw P(`${t}[${s}]`,`${t}[${s}] must be a string`);const n=e.trim();n&&!o.has(n)&&(o.add(n),r.push(n))}),0===r.length)throw F(t);return r},$=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw F(t);return e.trim()},j=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw P(t,`${t} must be a string`);return e}},k=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw P(t,`${t} must be a boolean`);return e}},q=(e,t)=>`/${e.orgName}/${e.appName}${t}`,J=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),B=e=>{const t=n.createQueryParams();"number"==typeof e?.pageNum&&t.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize));const r=t.toString();return r?`?${r}`:""},K=async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups?resource=${o.encodedResource}`);return(e=>{const t=R(e),r=h(t[0]),o=_(e)??r;return{groupId:o&&w(o)||r&&w(r)||""}})(await e.post(s,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?x(r.memberIds,"params.memberIds"):[],public:r.public,approval:r.joinApprovalRequired,allowinvites:r.allowInvites,invite_need_confirm:r.inviteNeedConfirm,maxusers:r.maxMembers,custom:r.ext,avatar:r.avatar},{operation:"createGroup"}))},V=async(e,t,r)=>{const o=L(t),s=$(r.groupId,"params.groupId"),n=q(o,`/chatgroups/${encodeURIComponent(s)}?joined_time=true&version=v3`),a=await e.get(n,{operation:"getGroupInfo"});return E(a)},H=async(e,t,r)=>{const o=L(t),s=$(r.groupId,"params.groupId"),n={},a=j(r.name,"params.name"),i=j(r.description,"params.description"),u=j(r.avatar,"params.avatar"),p=j(r.ext,"params.ext"),d=k(r.public,"params.public"),c=k(r.joinApprovalRequired,"params.joinApprovalRequired"),m=k(r.allowInvites,"params.allowInvites"),l=k(r.inviteNeedConfirm,"params.inviteNeedConfirm"),h=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw P(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==a&&(n.groupname=a),void 0!==i&&(n.description=i),void 0!==u&&(n.avatar=u),void 0!==p&&(n.custom=p),void 0!==d&&(n.public=d),void 0!==c&&(n.membersonly=c),void 0!==m&&(n.allowinvites=m),void 0!==l&&(n.invite_need_confirm=l),void 0!==h&&(n.maxusers=h),0===Object.keys(n).length)throw F("params");const g=q(o,`/chatgroups/${encodeURIComponent(s)}?resource=${o.encodedResource}&version=v3`);await e.put(g,n,{operation:"updateGroupInfo"})},z=async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/users${(e=>{const t=n.createQueryParams();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const n of R(e)){const e=h(n);if(!e)continue;const r=I(e.owner),o=I(e.admin),s=I(e.member),a=r??o??s;if(!a)continue;const i=y(e.joinedAt)??y(e.joined_time);t.push({user:b(a),role:r?"owner":o?"admin":"member",...void 0===i?{}:{joinedAt:i}})}const r=G(e,"pagenum"),o=G(e,"pagesize"),s=v(e,o);return{items:t,pageNum:r,pageSize:o,...void 0===s?{}:{hasMore:s}}})(await e.get(s,{operation:"getGroupMemberList"}))},W=async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/admin`),n=await e.get(s,{operation:"getGroupAdminList"});return C(n)},Q=async(e,t,r)=>{const o=L(t),s=$(r.groupId,"params.groupId"),n=B(r),a=n?"&":"",i=q(o,`/chatgroups/${encodeURIComponent(s)}/mute?version=v3${a}${n.replace("?","")}`);return(e=>{const t=[];for(const r of R(e)){const e=I(r);if(e){t.push({user:b(e)});continue}const o=h(r);if(!o)continue;const s=I(o.user);if(!s)continue;const n=y(o.expire);t.push({user:b(s),...void 0===n?{}:{muteExpire:n}})}return t})(await e.get(i,{operation:"getGroupMuteList"}))},Y=async(e,t,r)=>{const o=L(t),s=$(r.groupId,"params.groupId"),n=B(r),a=n?"&":"",i=q(o,`/chatgroups/${encodeURIComponent(s)}/blocks/users?version=v3${a}${n.replace("?","")}`),u=await e.get(i,{operation:"getGroupBlocklist"});return C(u).map(e=>({user:e}))},X=async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/white/users`),n=await e.get(s,{operation:"getGroupAllowlist"});return C(n).map(e=>({user:e}))},Z=async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=_(e)??{};return{announcement:g(t.announcement)??""}})(await e.get(s,{operation:"getGroupAnnouncement"}))},ee=async(e,t,r)=>{const o=L(t),s=n.createQueryParams();s.set("pagenum",String(r.pageNum??1)),s.set("pagesize",String(r.pageSize??20));const a=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/share_files?${s.toString()}`);return(e=>{const t=G(e,"pagenum"),r=G(e,"pagesize"),o=v(e,r);return{items:R(e).map(e=>A(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===o?{}:{hasMore:o}}})(await e.get(a,{operation:"getGroupSharedFileList"}))},te=(e,t)=>{const r=L(e);return q(r,`/chatgroups/${encodeURIComponent($(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent($(t.fileId,"params.fileId"))}`)},re=async(e,t,r)=>{const o=L(t),s=$(r.groupId,"params.groupId"),n=$(r.userId,"params.userId"),a=((e,t,r)=>{if(t!==e.userId)return null;const o=Object.entries(r);if(0===o.length)return null;let s;for(const[n,a]of o){if(!J.has(n)||"string"!=typeof a)return null;if(void 0!==s){if(s!==a)return null}else s=a}return void 0===s?null:{nameCard:s}})(t,n,r.memberAttributes);if(a){const t=q(o,`/sdk/chatgroups/${encodeURIComponent(s)}/nameCard`);return await e.put(t,a,{operation:"setGroupMemberAttributes"})}const i=q(o,`/sdk/metadata/chatgroup/${encodeURIComponent(s)}/user/${encodeURIComponent(n)}?resource=${o.encodedResource}`);return await e.put(i,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},oe=async(e,t,r)=>{const o=L(t),s=q(o,`/sdk/metadata/chatgroup/${encodeURIComponent($(r.groupId,"params.groupId"))}/get`);return(e=>{const t=_(e)??{},r=h(t.data)??t,o={};for(const[s,n]of Object.entries(r)){const e=h(n);e&&(o[s]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:o}})(await e.post(s,{targets:x(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},se=t=>{const r=e.isRecord(t)?t:{},o=r.data,s=e.isRecord(o)?o.data:void 0,n=Array.isArray(o)?o:Array.isArray(s)?s:null;if(Array.isArray(n))return ne(n);const a=e.isRecord(o)?o:r,i=e.isRecord(a.namecards)?a.namecards:a,u={};for(const[p,d]of Object.entries(i)){if("string"==typeof d){u[p]={namecard:d};continue}if(!e.isRecord(d))continue;const t=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof t&&(u[p]={namecard:t,namecardUpdateTime:ae(d)})}return u},ne=t=>{const r={};return t.forEach(t=>{if(!e.isRecord(t))return;const o=t.username??t.userId??t.userid??t.user_id,s=t.name_card??t.namecard??t.nameCard??t.groupNamecard??t.group_namecard??t.group_name_card;"string"==typeof o&&o.trim()&&"string"==typeof s&&(r[o.trim()]={namecard:s,namecardUpdateTime:ae(t)})}),r},ae=e=>r.normalizeProfileVersionFromTimestamp("number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.timestamp?e.timestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0),ie=t=>{if(e.isRecord(t))return r.normalizeProfileVersionFromTimestamp("number"==typeof t.timestamp?t.timestamp:"number"==typeof t.update_timestamp?t.update_timestamp:"number"==typeof t.updateTimestamp?t.updateTimestamp:"number"==typeof t.lastModified?t.lastModified:"number"==typeof t.last_modified?t.last_modified:void 0)};class ue{constructor(e){this.repository=e}applyPatch(e){e.shouldMarkStale&&this.repository.markStale(e.groupId);const t=this.repository.getDetailSnapshot(e.groupId);if(!e.groupPatch)return t;const r=t??{groupId:e.groupId,name:e.groupPatch.name??e.groupName??""};return this.repository.mergeDetail({...r,...e.groupPatch,groupId:e.groupId})}}const pe=e=>({...e}),de=e=>({...e,owner:e.owner?{...e.owner}:void 0});class ce{constructor(e){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null,this.groupId=e}mergeSummary(e){e.groupId===this.groupId&&(this.summarySnapshot=pe({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=de({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=pe(this.toSummaryFromDetail(this.detailSnapshot)),this.loadedSummary=!0,this.loadedDetail=!0,this.stale=!1,this.lastPatchedAt=Date.now(),this.lastHydratedAt=Date.now())}markStale(){this.stale=!0,this.lastPatchedAt=Date.now()}clear(){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null}getSummarySnapshot(){return this.summarySnapshot?pe(this.summarySnapshot):this.detailSnapshot?pe(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?de(this.detailSnapshot):null}isStale(){return this.stale}hasLoadedSummary(){return this.loadedSummary}hasLoadedDetail(){return this.loadedDetail}getLastPatchedAt(){return this.lastPatchedAt}getLastHydratedAt(){return this.lastHydratedAt}toSummaryFromDetail(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,public:e.public,joinApprovalRequired:e.joinApprovalRequired,allowInvites:e.allowInvites,maxMembers:e.maxMembers,role:e.role,disabled:e.disabled}}}class me{toSummary(e){const t=e.getSummarySnapshot();return t?(e=>({...e}))(t):null}toDetail(e){const t=e.getDetailSnapshot();return t?(e=>({...e,owner:e.owner?{...e.owner}:void 0}))(t):null}}class le{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new me,this.joinedGroupSnapshot=null,this.sessionKey=null}ensureSession(e){return this.sessionKey!==e&&(this.sessionKey=e,this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null,!0)}getSessionKey(){return this.sessionKey}getOrCreate(e){const t=this.groups.get(e);if(t)return t;const r=new ce(e);return this.groups.set(e,r),r}mergeSummary(e){return this.getOrCreate(e.groupId).mergeSummary(e),this.getSummarySnapshot(e.groupId)??{...e}}mergeSummaries(e){return e.map(e=>this.mergeSummary(e))}applyJoinedGroupSnapshot(e){const t=e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId));this.joinedGroupSnapshot={items:t.map(e=>({...e})),meta:{...e.meta}},this.joinedGroupById.clear();for(const r of t){const e={...r};this.joinedGroupById.set(e.groupId,e),this.mergeSummary(this.toGroupSummary(e))}}getJoinedGroupSnapshot(e){return this.joinedGroupSnapshot?{items:this.joinedGroupSnapshot.items.map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}}:e?{items:e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId)).map(e=>({...e})),meta:{...e.meta}}:{items:[],meta:{integrity:"unknown",limited:!1,storageLimit:100,serverLimit:3e3,source:"sync"}}}getJoinedGroupSummarySnapshot(e,t){const r=this.joinedGroupById.get(e);if(r)return{...r};if(this.removedJoinedGroupIds.has(e))return null;const o=t?.items.find(t=>t.groupId===e);return o?{...o}:null}addJoinedGroupIfAbsent(e,t){const r=this.getJoinedGroupSnapshot(t);return r.items.some(t=>t.groupId===e.groupId)?null:(this.removedJoinedGroupIds.delete(e.groupId),this.applyJoinedGroupSnapshot({items:[{...e},...r.items],meta:{...r.meta}}),this.getJoinedGroupSnapshot())}mergeJoinedGroupSummary(e,t){const r=this.joinedGroupById.get(e);if(!r||!this.joinedGroupSnapshot)return null;const o={...r,...t,groupId:e};return this.joinedGroupById.set(e,o),this.mergeSummary(this.toGroupSummary(o)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...o}:{...t}),meta:{...this.joinedGroupSnapshot.meta}},this.getJoinedGroupSnapshot()}mergeDetail(e){const t=this.mergeJoinedGroupFieldsIntoDetail(e);return this.getOrCreate(t.groupId).mergeDetail(t),this.getDetailSnapshot(t.groupId)??{...t}}mergeDetails(e){return e.map(e=>this.mergeDetail(e))}getSummarySnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toSummary(t):null}getDetailSnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toDetail(t):null}hasFreshDetail(e){const t=this.groups.get(e);return Boolean(t&&t.hasLoadedDetail()&&!t.isStale())}markStale(e){this.getOrCreate(e).markStale()}delete(e){this.groups.delete(e),this.joinedGroupById.delete(e),this.joinedGroupSnapshot&&(this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.filter(t=>t.groupId!==e).map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}})}markJoinedGroupRemoved(e){this.removedJoinedGroupIds.add(e),this.delete(e)}clear(){this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null}mergeJoinedGroupFieldsIntoDetail(e){const t=this.joinedGroupById.get(e.groupId);return t&&void 0===e.joinedAt&&void 0!==t.joinedAt?{...e,joinedAt:t.joinedAt}:e}toGroupSummary(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,role:e.role,disabled:e.disabled}}}const he=0,ge=5,Ie=12,ye=13,fe=0,Re=1,_e=2,Ge=0,ve=1,we=2,Se=3,Ee=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(o=e.role,o===fe?"owner":o===Re?"admin":o===_e?"member":void 0),disabled:e.disabled,ownerId:e.group_owner,avatarUrl:e.group_avatar,muteAllMembers:e.mute_all,muteExpiration:e.mute_expiration,remindType:(r=e.remind_type,r===Ge?"DEFAULT":r===ve?"ALL":r===we?"AT":r===Se?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,o},be=e=>e.updatedAt??0,Ce=(e,t)=>{if(!e)return!0;return be(t)>=be(e)},Ae={nested:{easemob:{nested:{joinedgroups:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},GetJoinedGroupsRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},cursor:{type:"string",id:7}}},GroupItem:{fields:{group_id:{type:"string",id:1},group_name:{type:"string",id:2},group_owner:{type:"string",id:3},members_count:{type:"int64",id:4},mute_all:{type:"bool",id:5},disabled:{type:"bool",id:6},description:{type:"string",id:7},group_avatar:{type:"string",id:8},role:{type:"uint32",id:9},mute_expiration:{type:"int64",id:10},remind_type:{type:"int32",id:11},create_at:{type:"uint64",id:12},update_at:{type:"uint64",id:13},joined_timestamp:{type:"int64",id:14}}},GetJoinedGroupsResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},groups:{rule:"repeated",type:"GroupItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5},cursor:{type:"string",id:6}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let Ue=null,Oe=!1;const De=()=>Ue||(Oe||(i.lightExports.util.Long=u.Long,i.lightExports.configure(),Oe=!0),u.installReflectionRuntime(),Ue=i.lightExports.Root.fromJSON(Ae),u.installReflectionCodecInNamespace(Ue),Ue),Ne=e=>De().lookupType(e),Te=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if(u.Long.isLong(e))return e.toNumber();if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},Me=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Te(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Te(t.protocol_version)??Te(t.protocolVersion)??0}};class Le{constructor(){this.requestType=Ne("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=Ne("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=Ne("easemob.joinedgroups.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,cursor:e.cursor});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const o=this.tryDecodeRequest(e);return o||{type:he}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=Te(t.type);return r!==Ie?null:{type:r,header:Me(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Te(t.last_sync_time)??Te(t.lastSyncTime)??0,cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=Te(t.type);return r!==ye?null:{type:r,header:Me(t.header),groups:Array.isArray(t.groups)?t.groups.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{group_id:"string"==typeof t.group_id?t.group_id:"string"==typeof t.groupId?t.groupId:void 0,group_name:"string"==typeof t.group_name?t.group_name:"string"==typeof t.groupName?t.groupName:void 0,group_owner:"string"==typeof t.group_owner?t.group_owner:"string"==typeof t.groupOwner?t.groupOwner:void 0,members_count:Te(t.members_count)??Te(t.membersCount),mute_all:"boolean"==typeof t.mute_all?t.mute_all:"boolean"==typeof t.muteAll?t.muteAll:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,description:"string"==typeof t.description?t.description:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:"string"==typeof t.groupAvatar?t.groupAvatar:void 0,role:Te(t.role),mute_expiration:Te(t.mute_expiration)??Te(t.muteExpiration),remind_type:Te(t.remind_type)??Te(t.remindType),create_at:Te(t.create_at)??Te(t.createAt),update_at:Te(t.update_at)??Te(t.updateAt),joined_timestamp:Te(t.joined_timestamp)??Te(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:Te(t.last_sync_finished_ts)??Te(t.lastSyncFinishedTs),cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=Te(t.type);return r!==ge?null:{type:r,header:Me(t.header),code:Te(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class Fe{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==ye)return{done:!1};const r=e.header?.requestId;if(r!==this.requestId)return{done:!1};if(this.done)throw new t.SDKError("Joined groups response received after completion",t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{stage:"response_decode",requestId:this.requestId}});if(this.batches.push(e),e.cursor&&(this.latestCursor=e.cursor),e.isLastBatch){if("number"!=typeof e.lastSyncFinishedTs)throw new t.SDKError("Joined groups final batch missing lastSyncFinishedTs",t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{stage:"completion_meta",requestId:this.requestId}});this.done=!0,this.lastSyncFinishedTs=e.lastSyncFinishedTs}return{done:this.done}}buildResult(){return{batches:this.batches.map(e=>({...e,groups:e.groups.map(e=>({...e}))})),lastSyncFinishedTs:this.lastSyncFinishedTs}}}const Pe=e=>e.type===ye,xe=e=>e.type===ge;class $e{constructor(e){this.codec=new Le,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new Fe(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,r,o){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:r,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,r,o.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:Pe(t)||xe(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(Pe(e)){if(!o.push(e).done)return;return{done:!0,result:o.buildResult()}}if(xe(e))throw(e=>{const r=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new t.SDKError(e.message,t.ERROR_CODES.VALIDATION_REQUIRED,{details:r("request_send",!1)});case 1602:return new t.SDKError(e.message,t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:r("batch_merge",!0)});case 1002:return new t.AuthenticationError(e.message,{code:t.ERROR_CODES.AUTH_UNAUTHORIZED,details:r("auth",!1)});case 1003:return new t.SDKError(e.message,t.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,{details:r("server_limit",!0)});default:return new t.SDKError(e.message,t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:r("response_decode",!0)})}})(e);return}catch(r){throw r instanceof t.SDKError?r:new t.SDKError("Joined groups frame decode failed",t.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:r instanceof Error?r.message:String(r)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class je{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const o=await this.dependencies.getSyncUrls();if(0===o.length)throw new t.SDKError("Group sync websocket urls are unavailable",t.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const s=this.buildRequest(),n=await new $e(this.dependencies.getSharedSyncSession()).sync({urls:o,request:s}),a=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=Ee(r);e&&t.push(e)}return t})(e.groups)),i=this.dependencies.getRuntimeSnapshot(),u=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=new Map;for(const s of e.incomingItems){const e=r.get(s.groupId)??t.get(s.groupId);Ce(e,s)?r.set(s.groupId,{...e??{},...s,groupId:s.groupId}):e&&r.set(s.groupId,{...e})}const o=r.size>=O;return{items:Array.from(o?e.existingItems.map(e=>({...e})):r.values()).sort((e,t)=>{const r=(t.joinedAt??0)-(e.joinedAt??0);return 0!==r?r:e.groupId.localeCompare(t.groupId)}),meta:{integrity:o?"limited":"synced",limited:o,storageLimit:U,serverLimit:O,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:i?.items??[],incomingItems:a,lastSyncFinishedTs:n.lastSyncFinishedTs}),p=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(u);const d=this.dependencies.getRuntimeSnapshot()??u;try{await p.commitJoinedGroupPreviewSnapshot(d);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(d,e)&&await p.commitJoinedGroupPreviewSnapshot(e)}catch(r){throw i&&this.dependencies.applyRuntimeSnapshot(i),new t.StorageError("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:r instanceof Error?r.message:String(r)}})}t.logger.warn("Group sync finished",{durationMs:Date.now()-e,itemCount:u.items.length,limited:u.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(r){const o=(e=>{const r=e instanceof t.SDKError?e:new t.SDKError("Group sync failed",t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),o=r.details??{},s=o.serverCode;return{dataType:"group",code:r.code,stage:(n=o.stage,"config"===n||"socket_connect"===n||"request_send"===n||"response_decode"===n||"batch_merge"===n||"preview_persist"===n||"completion_meta"===n||"auth"===n||"server_limit"===n||"cancelled"===n?n:"socket_connect"),message:r.message,retryable:!0===o.retryable,serverCode:"number"==typeof s||"string"==typeof s?s:void 0};var n})(r);t.logger.warn("Group sync failed",{durationMs:Date.now()-e,stage:o.stage,code:o.code,serverCode:o.serverCode}),this.dependencies.onFinish({status:"failed",error:o})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:r,appName:o}=t.parseAppKey(e.appKey);return{type:Ie,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:r,app:o,username:e.userId,lastSyncTime:0}}}const ke=t.mergeRuntimeErrorMaps(t.COMMON_ERROR_MAP,{common:{},apis:{createGroup:{range:"4,110,204,608",errors:{invalid_parameter:{code:110,httpStatus:400,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:4,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1,aliases:["INVALID_GROUP_NAME"]},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]}}},getJoinedGroupList:{range:"",errors:{}},getGroupInfo:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupInfoList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupInfo:{range:"110,603,606,607,608",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},forbidden_op:{code:603,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:110,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},changeGroupOwner:{range:"603,606",errors:{forbidden_op:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},destroyGroup:{range:"603,606,607",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},leaveGroup:{range:"602,603,606",errors:{not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},owner_cannot_leave:{code:603,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"owner can not quit group"},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},joinGroup:{range:"600-607,613",errors:{group_invalid_id:{code:600,retryable:!1,aliases:["GROUP_INVALID_ID"]},already_joined:{code:601,retryable:!1,aliases:["ALREADY_JOINED","GROUP_ALREADY_JOINED","group_already_joined"]},not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},group_authorization:{code:603,httpStatus:403,retryable:!1,aliases:["NEED_APPROVAL","GROUP_PERMISSION_DENIED"]},group_full:{code:604,httpStatus:403,retryable:!1,aliases:["GROUP_FULL","GROUP_MEMBERS_FULL"],matchField:"error_description",matchPattern:"member list is full"},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["GROUP_NOT_FOUND","service_resource_not_found"]},group_disabled:{code:607,retryable:!1,aliases:["GROUP_DISABLED"]},group_user_in_blocklist:{code:613,httpStatus:403,retryable:!1,aliases:["GROUP_USER_IN_BLOCKLIST"],matchField:"error_description",matchPattern:"is in the blacklist"}}},inviteUsersToGroup:{range:"204,603,606,607",errors:{group_authorization:{code:603,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]},group_not_found:{code:606,retryable:!1,aliases:["GROUP_NOT_FOUND"]},group_disabled:{code:607,retryable:!1}}},acceptGroupJoinRequest:{range:"",errors:{}},rejectGroupJoinRequest:{range:"",errors:{}},acceptInvitation:{range:"",errors:{}},rejectInvitation:{range:"",errors:{}},removeGroupMembers:{range:"",errors:{}},addGroupAdmin:{range:"",errors:{}},removeGroupAdmin:{range:"",errors:{}},muteGroupMembers:{range:"",errors:{}},unmuteGroupMembers:{range:"",errors:{}},muteAllGroupMembers:{range:"",errors:{}},unmuteAllGroupMembers:{range:"",errors:{}},blockGroupMembers:{range:"",errors:{}},unblockGroupMembers:{range:"",errors:{}},addUsersToGroupAllowlist:{range:"",errors:{}},removeUsersFromGroupAllowlist:{range:"",errors:{}},checkIfInGroupAllowList:{range:"",errors:{}},getGroupMemberList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},getGroupAdminList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},checkIfInGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupBlocklist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAllowlist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAnnouncement:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupAnnouncement:{range:"110",errors:{announcement_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce into length exceeds limit"},announcement_info_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce info length exceeds limit"}}},getGroupSharedFileList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["RestGroupFeignException"]}}},deleteGroupSharedFile:{range:"603,605,606",errors:{group_authorization:{code:603,retryable:!1},file_not_found:{code:605,retryable:!1,aliases:["GROUP_SHARED_FILE_INVALID_ID"]},resource_not_found:{code:606,retryable:!1}}},setGroupMemberAttributes:{range:"4,210,302,305,602,609-612",errors:{attributes_reach_limit:{code:609,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT"],matchField:"error_code",matchValue:60006},attributes_update_failed:{code:610,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED"],matchField:"error_code",matchValue:60005},attributes_key_reach_limit:{code:611,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT"],matchField:"error_code",matchValue:60009},attributes_value_reach_limit:{code:612,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT"],matchField:"error_code",matchValue:600010},not_joined:{code:602,httpStatus:404,retryable:!1,matchField:"error_code",matchValue:60003},permission_denied:{code:210,httpStatus:401,retryable:!1,matchField:"error_code",matchValue:60001},permission_denied_403:{code:210,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60002},exceed_service_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60007},service_disabled:{code:305,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60004}}},getGroupMembersAttributes:{range:"606",errors:{resource_not_found:{code:606,retryable:!1}}},getGroupNamecards:{range:"",errors:{}}}}),qe=class{constructor(){this.capabilities=["rawNotify:group","group:namecard"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.groupRegistry=new Map,this.groupRepository=null,this.groupEventSync=null}bind(e,t){this.client=e,this.eventContext=t??null,this.groupRegistry.clear(),this.groupRepository=new le,this.groupEventSync=new ue(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,o=await this.buildIncomingEventPayload(r,t);if(!o)return;if(this.eventContext?.dispatch?.(r,o),r!==s.GroupEventName.GROUP_MEMBER_ATTRIBUTE_CHANGED)return;if(!("attribute"in o)||!("user"in o))return;const n=this.extractGroupNamecard(o.attribute);if(void 0===n||!o.user?.userId)return;const a=this.client?.getCurrentUserId();o.user.userId!==a&&(this.getCacheManager()?.setGroupNamecards([{groupId:o.groupId,userId:o.user.userId,namecard:n,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(s.GroupEventName.USER_GROUP_NAMECARD_UPDATED,{groupId:o.groupId,userId:o.user.userId,namecard:n}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await K(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const r=e.trim();if(0===r.length)throw new t.ValidationError("groupId is required",{code:t.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const o=this.groupRegistry.get(r);if(o)return o;this.getGroupSummaryForHandle(r),this.getGroupRepository().getOrCreate(r);const s=new M(r,this);return this.groupRegistry.set(r,s),s}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await V(this.getRestClient(t),t,e),o=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(o)})}async getGroupInfoList(t){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const r=this.getRestContextOrThrow(),o=await(async(t,r,o)=>{const s=L(r),n=x(o.groupIds,"params.groupIds"),a=q(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),i=await t.get(a,{operation:"getGroupInfoList"});return(e.isRecord(i)&&Array.isArray(i.data)?i.data:[]).map(e=>E({data:[e]}))})(this.getRestClient(r),r,t),s=await this.hydrateGroupDetailsUsers(o);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,o=e===s.GroupEventName.GROUP_DESTROYED?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case s.GroupEventName.INVITATION_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case s.GroupEventName.REQUEST_TO_JOIN_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case s.GroupEventName.REQUEST_TO_JOIN_ACCEPTED:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case s.GroupEventName.REQUEST_TO_JOIN_DECLINED:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case s.GroupEventName.INVITATION_ACCEPTED:case s.GroupEventName.INVITATION_DECLINED:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case s.GroupEventName.USER_REMOVED:return{groupId:r.groupId,groupName:r.groupName};case s.GroupEventName.GROUP_DESTROYED:return{groupId:r.groupId,groupName:r.groupName??o};case s.GroupEventName.AUTO_ACCEPT_INVITATION:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case s.GroupEventName.MUTE_LIST_ADDED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case s.GroupEventName.MUTE_LIST_REMOVED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case s.GroupEventName.ALLOW_LIST_ADDED:case s.GroupEventName.ALLOW_LIST_REMOVED:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case s.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case s.GroupEventName.ADMIN_ADDED:case s.GroupEventName.ADMIN_REMOVED:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case s.GroupEventName.OWNER_CHANGED:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case s.GroupEventName.MEMBERS_JOINED:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,n)};case s.GroupEventName.MEMBERS_EXITED:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,n)};case s.GroupEventName.ANNOUNCEMENT_CHANGED:return{groupId:r.groupId,announcement:r.announcement??""};case s.GroupEventName.SHARED_FILE_ADDED:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case s.GroupEventName.SHARED_FILE_DELETED:return{groupId:r.groupId,fileId:r.fileId??""};case s.GroupEventName.GROUP_INFO_CHANGED:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case s.GroupEventName.GROUP_DISABLED_CHANGED:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case s.GroupEventName.GROUP_MEMBER_ATTRIBUTE_CHANGED:return{groupId:r.groupId,user:this.pickEventUser(r.userId,n),attribute:r.attribute??{},from:r.from,source:r.source};default:return null}}async resolveGroupDetailForEvent(e){this.ensureRepositorySession();const r=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},o=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:r,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(n){t.logger.warn("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:n})}if(o)return o;const s=this.getGroupRepository().getDetailSnapshot(e.groupId);return s||{groupId:e.groupId,name:r?.name??e.groupName??"",...r??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await H(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}?resource=${o.encodedResource}`);await e.put(s,{newowner:$(r.newOwner,"params.newOwner")},{operation:"changeGroupOwner"})})(this.getRestClient(t),t,e)})}async destroyGroup(e){return this.runOperation("destroyGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}?version=v3&resource=${o.encodedResource}`);await e.delete(s,{operation:"destroyGroup"})})(this.getRestClient(t),t,e),await this.requireClient().handleGroupDestroyedConversation(e.groupId),await this.removeJoinedGroupLocal(e.groupId)})}async leaveGroup(e){return this.runOperation("leaveGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/quit?resource=${o.encodedResource}`);await e.delete(s,{operation:"leaveGroup"})})(this.getRestClient(t),t,e),await this.removeJoinedGroupLocal(e.groupId)})}async joinGroup(e){return this.runOperation("joinGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/apply?resource=${o.encodedResource}`);await e.post(s,{message:r.message??""},{operation:"joinGroup"})})(this.getRestClient(t),t,e)})}async inviteUsersToGroup(e){return this.runOperation("inviteUsersToGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/invite?resource=${o.encodedResource}`);await e.post(s,{usernames:x(r.userIds,"params.userIds")},{operation:"inviteUsersToGroup"})})(this.getRestClient(t),t,e)})}async acceptGroupJoinRequest(e){return this.runOperation("acceptGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:$(r.userId,"params.userId"),verifyResult:!0},{operation:"acceptGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async rejectGroupJoinRequest(e){return this.runOperation("rejectGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:$(r.userId,"params.userId"),verifyResult:!1,reason:r.reason},{operation:"rejectGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async acceptInvitation(e){return this.runOperation("acceptInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!0},{operation:"acceptInvitation"})})(this.getRestClient(t),t,e)})}async rejectInvitation(e){return this.runOperation("rejectInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await z(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=x(r.userIds,"params.userIds"),n=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await W(this.getRestClient(t),t,e);return this.hydrateUserInfos(e.groupId,r)})}async addGroupAdmin(e){return this.runOperation("addGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/admin?resource=${o.encodedResource}`);await e.post(s,{newadmin:r.userId},{operation:"addGroupAdmin"})})(this.getRestClient(t),t,e)})}async removeGroupAdmin(e){return this.runOperation("removeGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${o.encodedResource}`);await e.delete(s,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await Q(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async muteGroupMembers(e){return this.runOperation("muteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/mute?resource=${o.encodedResource}`);await e.post(s,{usernames:x(r.userIds,"params.userIds"),mute_duration:r.muteDuration},{operation:"muteGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteGroupMembers(e){return this.runOperation("unmuteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=x(r.userIds,"params.userIds"),n=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllGroupMembers(e){return this.runOperation("unmuteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await Y(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async blockGroupMembers(e){return this.runOperation("blockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/blocks/users?resource=${o.encodedResource}`);await e.post(s,{usernames:x(r.userIds,"params.userIds")},{operation:"blockGroupMembers"})})(this.getRestClient(t),t,e)})}async unblockGroupMembers(e){return this.runOperation("unblockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=x(r.userIds,"params.userIds"),n=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await X(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async addUsersToGroupAllowlist(e){return this.runOperation("addUsersToGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/white/users?resource=${o.encodedResource}`);await e.post(s,{usernames:x(r.userIds,"params.userIds")},{operation:"addUsersToGroupAllowlist"})})(this.getRestClient(t),t,e)})}async removeUsersFromGroupAllowlist(e){return this.runOperation("removeUsersFromGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=x(r.userIds,"params.userIds"),n=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(t){return this.runOperation("checkIfInGroupAllowList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=L(r),n=q(s,`/chatgroups/${encodeURIComponent($(o.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof a?a:e.isRecord(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async checkIfInGroupMuteList(t){return this.runOperation("checkIfInGroupMuteList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=L(r),n=q(s,`/sdk/chatgroups/${encodeURIComponent($(o.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof a?a:e.isRecord(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return Z(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/announcement?resource=${o.encodedResource}`);await e.post(s,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await ee(this.getRestClient(t),t,e),o=await this.resolveGroupContextUserInfoMap(e.groupId,r.items.map(e=>e.fileOwner).filter(e=>void 0!==e));return{...r,items:r.items.map(e=>({...e,fileOwner:e.fileOwner?.userId?o.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const r=this.getRestContextOrThrow(),s=te(r,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),n=t.normalizeUploadSource({file:e.file}),a=t.startDataReportOperation({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=a?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${r.restBaseUrl}${s}`});try{const o=await(this.requireClient().getUploadAdapter()?.upload({url:`${r.restBaseUrl}${s}?resource=${encodeURIComponent(r.clientResource)}`,headers:{Authorization:`Bearer ${r.token}`,[t.REQUEST_ID_HEADER]:t.createTraceId()},source:n.source,timeoutMs:t.GROUP_SHARED_FILE_UPLOAD_TIMEOUT,onProgress:e.onFileUploadProgress}));if(!o)throw new Error("platform upload adapter is unavailable");if(o.status<200||o.status>=300)throw new t.SDKError("uploadGroupSharedFile failed",t.ERROR_CODES.REST_HTTP_ERROR,{details:{status:o.status}});i?.finish({code:o.status,success:!0}),a?.finish({code:0,success:!0}),e.onFileUploadComplete?.(o.body)}catch(u){const r=o.mapUploadAdapterError(u);throw i?.finish({code:r.code,success:!1,description:r.message}),a?.finish({code:r.code,success:!1,description:r.message}),r.code===t.ERROR_CODES.UPLOAD_ABORTED&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(r),r}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=L(t),s=q(o,`/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent($(r.fileId,"params.fileId"))}?resource=${o.encodedResource}`);await e.delete(s,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let r,o;try{const s=this.getRestContextOrThrow(),n=`${s.restBaseUrl}${te(s,e)}`;r=t.startDataReportOperation({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),o=r?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:n});const a=this.requireClient().getRequestAdapter();if(!a)throw new t.SDKError("downloadGroupSharedFile request adapter is unavailable",t.ERROR_CODES.REST_NETWORK_ERROR);const i=await a.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[t.REQUEST_ID_HEADER]:t.createTraceId()},responseType:"arraybuffer",timeoutMs:t.GROUP_SHARED_FILE_DOWNLOAD_TIMEOUT});if(i.status<200||i.status>=300)throw o?.finish({code:i.status,success:!1,description:"downloadGroupSharedFile failed"}),r?.finish({code:i.status,success:!1,description:"downloadGroupSharedFile failed"}),new t.SDKError("downloadGroupSharedFile failed",t.ERROR_CODES.REST_HTTP_ERROR);o?.finish({code:i.status,success:!0}),r?.finish({code:0,success:!0});const u="undefined"!=typeof Blob?new Blob([i.data]):i.data;e.onFileDownloadComplete?.(u)}catch(s){const n=s instanceof t.SDKError?s.code:t.ERROR_CODES.REST_NETWORK_ERROR,a=s instanceof Error?s.message:String(s);throw o?.finish({code:n,success:!1,description:a}),r?.finish({code:n,success:!1,description:a}),e.onFileDownloadError?.(s),s}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await re(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return oe(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,r){0!==r.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const o=this.getRestContextOrThrow(),n=r.map(e=>e.userId),a=await(async(e,t,r)=>{const o=L(t),s=q(o,`/sdk/chatgroups/${encodeURIComponent($(r.groupId,"params.groupId"))}/nameCard/batch/get`),n=await e.post(s,{members:x(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:se(n),responseTimestamp:ie(n)}})(this.getRestClient(o),o,{groupId:e,userIds:n}),i=new Map(r.map(e=>[e.userId,e.namecardUpdateTime])),u=[],p=new Set;for(const[t,r]of Object.entries(a.items))p.add(t),u.push({groupId:e,userId:t,namecard:r.namecard,namecardUpdateTime:i.get(t)??r.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const d=n.filter(e=>!p.has(e));d.length>0&&"number"==typeof a.responseTimestamp&&u.push(...d.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:a.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(u);for(const e of u)e.userId!==o.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(s.GroupEventName.USER_GROUP_NAMECARD_UPDATED,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});d.length>0&&"number"!=typeof a.responseTimestamp&&t.logger.warn("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:n,missingUserIds:d})})}async runOperation(e,r){try{return await r()}catch(o){const r=this.normalizeSdkError(e,o);throw t.logger.warn(`GroupManager ${e} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(e,r){return r instanceof t.SDKError?r:r instanceof Error?new t.SDKError(`GroupManager ${e} failed: ${r.message}`,t.ERROR_CODES.UNKNOWN):new t.SDKError(`GroupManager ${e} failed`,t.ERROR_CODES.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new t.RestClient(e.restBaseUrl,{errorMap:ke,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new t.SDKError("GroupManager is not bound to client",t.ERROR_CODES.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new le),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new ue(this.getGroupRepository())),this.groupEventSync}ensureRepositorySession(){this.getGroupRepository().ensureSession(this.resolveRepositorySessionKey())&&this.groupRegistry.clear()}resolveRepositorySessionKey(){if(!this.client)return null;const e=this.client.getCurrentUserId();if(!e)return null;try{const e=this.client.getRestContext();return`${e.restBaseUrl}:${e.userId}:${e.token}:${e.clientResource}`}catch{return`pending:${e}`}}getCacheManager(){return this.client?.getCacheManager()??null}loadJoinedGroupPreviewSnapshot(){const e=this.getCacheManager();if(e&&"function"==typeof e.loadJoinedGroupPreviewSnapshot)return e.loadJoinedGroupPreviewSnapshot()}resolveLocalGroupName(e){const t=this.getGroupRepository(),r=t.getSummarySnapshot(e)?.name;if(r)return r;const o=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return o||void 0}async resolveMembersJoinedGroupName(e){const r=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(r)return r;const o=this.resolveUsableGroupName(e.groupName,e.groupId);if(o)return o;const s=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await V(this.getRestClient(t),t,{groupId:e.groupId}),o=this.getGroupRepository();if(o.getSessionKey()!==s)return;return o.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(n){return void t.logger.warn("Members joined group detail enrichment failed",{groupId:e.groupId,error:n})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,r,o){if(r.userId!==e)return;const s=this.extractGroupNamecard(r.memberAttributes);if("string"!=typeof s)return;const n=this.resolveGroupMemberAttributesUpdateTime(o,r.userId);"number"!=typeof n&&t.logger.warn("Group member attributes update response missing server update time",{groupId:r.groupId,userId:r.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:r.groupId,userId:r.userId,namecard:s,namecardUpdateTime:n,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const o=[];this.collectUpdateTimeCandidates(e,t,o);for(const s of o){const e=r.normalizeProfileVersionFromTimestamp("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(t,r,o){if(!e.isRecord(t))return;o.push(t.lastModified,t.last_modified,t.timestamp,t.updateTime,t.update_time,t.updatedAt,t.updated_at);const s=t.data;if(e.isRecord(s)){this.collectUpdateTimeCandidates(s,r,o);const t=s[r];e.isRecord(t)&&this.collectUpdateTimeCandidates(t,r,o)}const n=t.lastModified??t.last_modified;e.isRecord(n)&&o.push(n[r])}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return l(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const r=this.getUserInfoManager();if(0===e.length)return[];if(!r)return await this.fetchUserInfosFromRest(e);try{return await r.getUserInfoByUserId({userIds:e})}catch(o){return t.logger.warn("GroupManager user info fetch failed",{userIds:e,error:o}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],o=[],s=new Set;for(const n of r){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return m(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>m(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:m(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case s.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case s.GroupEventName.OWNER_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case s.GroupEventName.REQUEST_TO_JOIN_ACCEPTED:case s.GroupEventName.AUTO_ACCEPT_INVITATION:return void this.addCurrentUserJoinedGroupFromEvent(t);case s.GroupEventName.MEMBERS_JOINED:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case s.GroupEventName.MEMBERS_EXITED:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case s.GroupEventName.USER_REMOVED:case s.GroupEventName.GROUP_DESTROYED:return void(await this.removeJoinedGroupLocal(t.groupId));case s.GroupEventName.MUTE_LIST_ADDED:case s.GroupEventName.MUTE_LIST_REMOVED:case s.GroupEventName.ALLOW_LIST_ADDED:case s.GroupEventName.ALLOW_LIST_REMOVED:case s.GroupEventName.ADMIN_ADDED:case s.GroupEventName.ADMIN_REMOVED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case s.GroupEventName.MEMBERS_JOINED:case s.GroupEventName.MEMBERS_EXITED:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const o=this.getGroupRepository().getDetailSnapshot(e);return!(!o||"number"!=typeof o.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,o.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const r=this.getGroupRepository().getSessionKey();let o;try{o=this.getRestContextOrThrow()}catch(s){return t.logger.warn("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,r,o)}catch(s){return t.logger.warn("Joined group detail enrichment failed",{groupId:e.groupId,error:s}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const o=await V(this.getRestClient(r),r,{groupId:e}),s=this.getGroupRepository();if(s.getSessionKey()!==t)return!1;s.mergeDetail(o);const n=s.getJoinedGroupSummarySnapshot(e);if(!n)return!1;const a=s.mergeJoinedGroupSummary(e,{...n.name||!o.name?{}:{name:o.name},...void 0!==n.description||void 0===o.description?{}:{description:o.description},...void 0!==n.memberCount||void 0===o.memberCount?{}:{memberCount:o.memberCount},...void 0!==n.role||void 0===o.role?{}:{role:o.role},...void 0!==n.disabled||void 0===o.disabled?{}:{disabled:o.disabled},...n.ownerId||!o.owner?.userId?{}:{ownerId:o.owner.userId},...void 0!==n.avatarUrl||void 0===o.avatarUrl?{}:{avatarUrl:o.avatarUrl},...void 0!==n.muteAllMembers||void 0===o.muteAllMembers?{}:{muteAllMembers:o.muteAllMembers},...void 0!==n.createdAt||void 0===o.createdAt?{}:{createdAt:o.createdAt},...void 0!==n.joinedAt||void 0===o.joinedAt?{}:{joinedAt:o.joinedAt}});if(a){this.persistJoinedGroupSnapshot(a);const t=s.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:o.name||t.name,avatarUrl:o.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const r=this.getCacheManager();if(r&&"function"==typeof r.applyJoinedGroupPreviewSnapshot){try{r.applyJoinedGroupPreviewSnapshot(e)}catch(o){return void t.logger.warn("Joined group preview persistence failed",{error:o})}"function"==typeof r.flushPending&&r.flushPending().catch(e=>{t.logger.warn("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=a.buildFetchUserInfoByUserIdRequest(e),o=await this.getRestClient(t).request(a.buildUserInfoFetchEndpoint(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return a.normalizeFetchedUserInfos(o,r.targets)}async hydrateEntriesWithUsers(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t.map(e=>e.user));return t.map(e=>({...e,user:r.get(e.user.userId)??e.user}))}extractGroupNamecard(e){return e.groupNamecard??e.group_namecard??e.group_name_card??e.namecard}async hydrateGroupDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveGroupContextUserInfoMap(e.groupId,[e.owner]);return{...e,owner:t.get(e.owner.userId)??e.owner}}async hydrateGroupDetailsUsers(e){const t=e.filter(e=>Boolean(e.owner?.userId)).map(e=>({groupId:e.groupId,user:e.owner}));if(0===t.length)return e;const r=await this.resolveGroupUserInfoContexts(t);return e.map(e=>e.owner?.userId?{...e,owner:r.get(o.getGroupUserInfoContextKey(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await o.resolveGroupUserInfoMap({groupId:e,users:t,includeNameCard:r,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return r&&this.dispatchFetchedUserInfoUpdates(s.fetchedUserInfos),s.usersById}async resolveGroupUserInfoContexts(e){const t=this.isGroupNamecardEnhancementEnabled(),r=await o.resolveGroupUserInfoContexts({contexts:e,includeNameCard:t,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return t&&this.dispatchFetchedUserInfoUpdates(r.fetchedUserInfos),r.usersByContextKey}async fetchGroupUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}isGroupNamecardEnhancementEnabled(){const e=this.requireClient(),t=e.isUserInfoSyncEnabled;return"function"==typeof t&&t.call(e)}dispatchFetchedUserInfoUpdates(e){if(0===e.length)return;const t=this.requireClient(),r=t.getCurrentUserId(),o=e.find(e=>e.userId===r),s=e.filter(e=>e.userId!==r);o&&t.dispatchOwnInfoUpdated?.(o),t.dispatchUserInfoUpdated?.(s),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new je(e)}};qe.key="groupManager";let Je=qe;exports.Group=M,exports.GroupManager=Je,exports.JoinedGroupPreviewCache=class{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:U,serverLimit:O,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:U,serverLimit:O,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return N(t=e)&&"string"==typeof t.groupId&&0!==t.groupId.length?{groupId:t.groupId,name:"string"==typeof t.name?t.name:"",description:"string"==typeof t.description?t.description:void 0,memberCount:"number"==typeof t.memberCount?t.memberCount:void 0,role:"owner"===t.role||"admin"===t.role||"member"===t.role?t.role:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,ownerId:"string"==typeof t.ownerId?t.ownerId:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:void 0,muteAllMembers:"boolean"==typeof t.muteAllMembers?t.muteAllMembers:void 0,muteExpiration:"number"==typeof t.muteExpiration?t.muteExpiration:void 0,remindType:T(t.remindType),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,updatedAt:"number"==typeof t.updatedAt?t.updatedAt:void 0,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null;var t}).filter(e=>null!==e):[];this.items=t.slice(0,U),this.meta=(e=>{const t=N(e)?e:{};return{integrity:"synced"===t.integrity||"limited"===t.integrity||"incomplete"===t.integrity||"unknown"===t.integrity?t.integrity:"preview",limited:!0===t.limited,storageLimit:"number"==typeof t.storageLimit?t.storageLimit:U,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:O,source:"localPreview",lastSyncFinishedTs:"number"==typeof t.lastSyncFinishedTs?t.lastSyncFinishedTs:void 0,lastSuccessfulAt:"number"==typeof t.lastSuccessfulAt?t.lastSuccessfulAt:void 0,reason:"string"==typeof t.reason?t.reason:void 0}})(e.meta)}setSnapshot(e){this.items=e.items.map(e=>D(e)).slice(0,U),this.meta={...e.meta,source:"localPreview",storageLimit:U,serverLimit:O,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>D(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>D(e)),meta:{...this.meta,source:"localPreview"}}}},exports.normalizeGroupSharedFile=A;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const e=require("./common-tHGz9VBk.cjs"),t=require("./cache-utils-gowrxNr8.cjs"),s=require("./user-info-DH3aE1gm.cjs"),r=require("./reflection-proto-codec-CwrIKT1L.cjs"),a=require("./light-BcQg8h2W.cjs"),n=e=>({userId:e}),o=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),i=e=>e,c=async(e,t)=>{const s=(e=>{const t=[],s=new Set;for(const r of e){const e=r.trim();e&&!s.has(e)&&(s.add(e),t.push(e))}return t})(e),r=new Map;if(0===s.length)return r;const a=t.cacheManager?.getUserInfoSummaries(s,!1)??[];for(const n of a)r.set(n.userId,o(n));const c=s.filter(e=>!r.has(e));if(c.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:c});for(const t of e)r.set(t.userId,i(t))}for(const o of s)r.has(o)||r.set(o,n(o));return r},d={UNSPECIFIED:0,PING:1,PONG:2,REQUEST:3,RESPONSE:4,ERROR:5},l=0,u=0,p=1,h=1001,g=1002,m=1003,y=1004,R=1005,I=1101,E={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:{}}}},C="User ID is invalid: cannot add yourself as a contact",S=(e,s,r)=>{if(!t.isRecord(e)||!t.isRecord(e.data))return;const a=e.data[s];if(Array.isArray(a))for(const n of a)if(t.isRecord(n)&&"string"==typeof n.failReason&&n.failReason.toLowerCase().includes(r))return n.failReason},f=t=>{const{orgName:s,appName:r}=e.parseAppKey(t.appKey);return{orgName:s,appName:r,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},_=e=>t.isRecord(e)&&Array.isArray(e.data)?e.data.filter(e=>"string"==typeof e&&e.length>0):Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[],v=(s,r)=>{if(!Array.isArray(s.userIds)||0===s.userIds.length)throw new e.ValidationError(`${r} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});const a=s.userIds.map((t,s)=>{if("string"!=typeof t)throw new e.ValidationError(`${r}[${s}] must be a string`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${r}[${s}]`,message:"userId must be a string",rule:"invalid_format"}]}});return t.trim()}),n=(e=>{const t=[],s=new Set;for(const r of e)r&&!s.has(r)&&(s.add(r),t.push(r));return t})(a);if(0===n.length)throw new e.ValidationError(`${r} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});return n.length!==a.length&&t.isRecord(s),n},O=async(t,s,r)=>{const a=f(s),n=`/${a.orgName}/${a.appName}/users/${a.encodedUserId}/contacts/apply?resource=${a.encodedResource}`;(t=>{const s=S(t,"applyYourselfUsers","user cannot apply to become a new friend");if(s)throw new e.ValidationError(C,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{api:"addContact",mapped:!0,reasonKey:"cannot_add_self",serverMessage:s,retryable:!1,canonicalCode:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,fields:[{path:"params.userId",message:C,rule:"invalid_format"}]}});const r=S(t,"notExistUsers","the users not exist");if(!r)return;const a=e.resolveApiBusinessError(E,"addContact",{error:"USER_NOT_FOUND"});if(!a)throw e.createRestBusinessError({apiName:"addContact",serverMessage:r,mapped:!1,reasonKey:"USER_NOT_FOUND"});throw e.createRestBusinessError({apiName:"addContact",entry:a.entry,serverMessage:r,mapped:!0,reasonKey:a.reasonKey,matchedBy:a.matchedBy})})(await t.post(n,{usernames:[r.userId],reason:r.message??""},{operation:"addContact"}))},T=async(e,t)=>{const s=f(t),r=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/blocks/users`,a=await e.get(r,{operation:"getBlocklist"});return _(a).map(e=>({userId:e}))},U=async(e,t,s)=>{const r=f(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:_(n).map(e=>({userId:e})),failed:[]}},w={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 N=!1,b=null;const A=()=>b||(N||(a.lightExports.util.Long=r.Long,a.lightExports.configure(),N=!0),r.installReflectionRuntime(),b=a.lightExports.Root.fromJSON(w),r.installReflectionCodecInNamespace(b),b),k=e=>"number"==typeof e?e:r.Long.isLong(e)?e.toNumber():0,D=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:k(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:k(t.protocolVersion)}};class M{encodeRequest(e){const t=A().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=l){const t=A().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:d.PONG,status:e})).finish()}decode(e){const t=A(),s=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(s.type){case d.PING:return{type:d.PING};case d.PONG:{const s=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:d.PONG,status:k(s.status)}}case d.RESPONSE:{const s=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:d.RESPONSE,header:D(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:k(t.createdAt),updatedAt:k(t.updatedAt),metadataUpdatedAt:k(t.metadataUpdatedAt)}})(e)):[],cursor:k(s.cursor),version:"string"==typeof s.version?s.version:"",responseType:k(s.responseType)||u}}case d.ERROR:{const s=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:d.ERROR,header:D(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:d.UNSPECIFIED}}}}class q{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(t){const s=t.header?.requestId;if(s&&s!==this.requestId)throw new e.SDKError("Roster response requestId mismatched",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:s}});if(this.completed)throw new e.SDKError("Roster response received after completion",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:t.cursor}});if(null!==this.responseType&&this.responseType!==t.responseType)throw new e.SDKError("Roster response type changed in same session",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:t.responseType}});if(this.pages.length>0&&0!==t.cursor&&t.cursor===this.pages[this.pages.length-1]?.cursor)throw new e.SDKError("Roster cursor duplicated",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:t.cursor}});return this.responseType=t.responseType,this.version=t.version||this.version,this.pages.push(t),this.nextCursor=t.cursor,this.pageCount+=1,this.completed=0===t.cursor,{done:this.completed,nextCursor:this.nextCursor,pageCount:this.pageCount}}getNextCursor(){return this.nextCursor}getPageCount(){return this.pageCount}hasPages(){return this.pages.length>0}isCompleted(){return this.completed}buildResult(){return{mode:this.responseType===p?"incremental":"full",version:this.version,pages:this.pages}}}const P=e=>e.type===d.RESPONSE,$=e=>"message"in e&&"code"in e;class B{constructor(e){this.codec=new M,this.sharedSession=e}async sync(e){const t=new q(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(t,s){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:t.header.requestId,encode:()=>{const e=this.buildAttemptRequest(t,s.getNextCursor());return this.codec.encodeRequest(e)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:P(t)||$(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(t,r)=>{try{if(t.type===d.PING)return void(await r.send(this.codec.encodePong()));if(P(t)){if(!s.push(t).done)return;return{done:!0,result:s.buildResult()}}if($(t))throw(t=>{const s=t.header?.requestId,r=e=>({stage:"sync_page",serverCode:t.code,requestId:s,retryable:e});switch(Number.parseInt(t.code,10)){case g:return new e.AuthenticationError(t.message,{code:e.ERROR_CODES.AUTH_UNAUTHORIZED,details:r(!1)});case m:return new e.SDKError(t.message,e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case h:return new e.SDKError(t.message,e.ERROR_CODES.VALIDATION_REQUIRED,{details:r(!1)});case y:return new e.SDKError(t.message,e.ERROR_CODES.VALIDATION_INVALID_FORMAT,{details:r(!1)});case R:return new e.SDKError(t.message,e.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:r(!0)});case I:return new e.SDKError(t.message,e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new e.SDKError(t.message,e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(t);return}catch(a){throw a instanceof e.SDKError?a:new e.SDKError("Roster frame decode failed",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:a instanceof Error?a.message:String(a)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const F=e=>e.versionState.version?"incremental":"full",x=e=>{const{metadata:t,metadataFailed:s,state:r}=e,a=r.versionState.version;return s||!t?{decision:"complete"===r.cacheMeta.cacheIntegrity?F(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}},L=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{}}},K=t=>{const s=(t=>{if(!(t instanceof e.SDKError&&t.details))return null;const s=t.details.httpStatus;return"number"==typeof s?s:null})(t);return 401===s||403===s||404===s},V=(e,t,s,r)=>({code:t,stage:e,message:`${e}: ${s}`,retryable:r}),G=t=>{e.logger.warn("Contact sync duration",t)};class Y{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("contact-sync-cancelled")}async runSync(){const t=this.dependencies.getContextState(),s=Date.now();let r;this.dependencies.onStart();try{const e=await this.dependencies.queryMetadata(t.versionState.version);if(r=x({metadata:e,state:t}),"skip"===r.decision)return this.dependencies.onFinish(),void G({outcome:"skip",decision:r.decision,durationMs:Date.now()-s,version:r.version,hasUsableSnapshot:t.cachedSnapshot.complete})}catch(a){if(K(a)){const r=x({metadataFailed:!0,state:t}),n=a instanceof e.SDKError?a:new e.SDKError("Contact metadata request failed",e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:V("metadata",n.code,n.message,!1)}),void G({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:t.versionState.version,stage:"metadata",hasUsableSnapshot:t.cachedSnapshot.complete,source:t.cachedSnapshot.complete?t.cachedSnapshot.source:void 0})}if(r=x({metadataFailed:!0,state:t}),t.cachedSnapshot.complete)return this.dependencies.onFinish({error:V("metadata",e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,a instanceof Error?a.message:String(a),!0)}),void G({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:t.cachedSnapshot.source})}try{const e=await this.dependencies.getSyncUrls(),a=this.dependencies.buildRosterRequest({decision:r.decision,version:t.versionState.version}),n=await new B(this.dependencies.getSharedSyncSession()).sync({urls:e,request:a}),o=(e=>{const t=[];for(const s of e)for(const e of s.data){const s=L(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(),G({outcome:"finish",decision:r.decision,durationMs:Date.now()-s,version:n.version,source:"sync",changed:i.changed,hasUsableSnapshot:i.snapshot.complete})}catch(a){const n=a instanceof e.SDKError?a:new e.SDKError("Contact sync failed",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:a instanceof Error?a.message:String(a)}}),o=n.details??{},i="string"==typeof o.stage?o.stage:"sync_page";this.dependencies.onFinish({error:V(i,n.code,n.message,!0)}),G({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:i,hasUsableSnapshot:t.cachedSnapshot.complete,source:t.cachedSnapshot.complete?t.cachedSnapshot.source:void 0})}}}const H={items:[],loaded:!1,source:"server"},W=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,E),j=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=H,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=H,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(t){return this.runOperation("addContact",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.validateOptionalString(t.message,"params.message"),a=this.getRestContextOrThrow();if(s===a.userId)throw this.buildValidationError(C,[{path:"params.userId",message:C,rule:"invalid_format"}]);const n=this.getRestClient(a);e.logger.debug("ContactManager addContact",{userId:s,hasMessage:"string"==typeof r&&r.length>0}),await O(n,a,{userId:s,message:r})})}async deleteContact(t){return this.runOperation("deleteContact",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager deleteContact",{userId:s}),await(async(e,t,s)=>{const r=f(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.delete(a,{operation:"deleteContact"})})(a,r,{userId:s});const n=this.client?.getCacheManager()?.removeContact(s);e.logger.debug("ContactManager deleteContact patched cache",{userId:s,changed:n?.changed??!1})})}async acceptContactInvite(t){return this.runOperation("acceptContactInvite",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager acceptContactInvite",{userId:s}),await(async(e,t,s)=>{const r=f(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/accept/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"acceptContactInvite"})})(a,r,{userId:s}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(t){return this.runOperation("declineContactInvite",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager declineContactInvite",{userId:s}),await(async(e,t,s)=>{const r=f(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/decline/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"declineContactInvite"})})(a,r,{userId:s})})}async setContactRemark(t){return this.runOperation("setContactRemark",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.validateRemark(t.remark,"params.remark"),a=this.getRestContextOrThrow(),n=this.getRestClient(a);e.logger.debug("ContactManager setContactRemark",{userId:s,remarkLength:r.length}),await(async(e,t,s)=>{const r=f(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.put(a,{remark:s.remark},{operation:"setContactRemark"})})(n,a,{userId:s,remark:r});const o=this.client?.getCacheManager()?.updateContactRemark(s,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:s}],"profile"),e.logger.debug("ContactManager setContactRemark patched cache",{userId:s,changed:o?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=this.getRestClient(t);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const r=await this.enrichBlocklistUsers(await T(s,t));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},e.logger.debug("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(t){return this.runOperation("addUsersToBlocklist",async()=>{const s=this.getRestContextOrThrow();this.ensureBlocklistSession(s);const r=v(t,"params.userIds"),a=this.getRestClient(s);e.logger.debug("ContactManager addUsersToBlocklist",{userIds:r,inputCount:t.userIds.length,normalizedCount:r.length});const n=await U(a,s,r),o=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(o),{succeeded:o,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(t){return this.runOperation("removeUserFromBlocklist",async()=>{const s=this.getRestContextOrThrow();this.ensureBlocklistSession(s);const r=v(t,"params.userIds"),a=this.getRestClient(s);e.logger.debug("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:t.userIds.length,normalizedCount:r.length}),await(async(e,t,s)=>{const r=f(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`;await e.request(a,{method:"DELETE",body:{usernames:s},operation:"removeUserFromBlocklist"})})(a,s,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(t,s){try{return await s()}catch(r){const s=this.normalizeSdkError(t,r);throw e.logger.warn(`ContactManager ${t} failed`,{code:s.code,message:s.message,details:s.details}),s}}normalizeSdkError(t,s){return s instanceof e.SDKError?s:s instanceof Error?new e.SDKError(`ContactManager ${t} failed: ${s.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`ContactManager ${t} failed`,e.ERROR_CODES.UNKNOWN)}requireClient(){if(!this.client)throw this.buildValidationError("ContactManager is not bound to client",[{path:"contactManager.client",message:"ContactManager is not bound to client",rule:"required"}]);return this.client}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:W,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}ensureBlocklistSession(e){const t=`${e.restBaseUrl}:${e.userId}:${e.token}`;this.blocklistSessionKey!==t&&(this.blocklistSessionKey=t,this.blocklistSnapshot=H)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.set(s.userId,s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}patchBlocklistSnapshotWithRemovals(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.delete(s);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}validateUserId(e,t){if("string"!=typeof e)throw this.buildValidationError("userId must be a string",[{path:t,message:"userId must be a string",rule:"invalid_format"}]);const s=e.trim();if(!s)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return s}validateOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw this.buildValidationError(`${t} must be a string`,[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]);return e}}validateRemark(e,t){if("string"!=typeof e)throw this.buildValidationError("remark must be a string",[{path:t,message:"remark must be a string",rule:"invalid_format"}]);return e}buildValidationError(t,s){const r=s.some(e=>"invalid_format"===e.rule)?e.ERROR_CODES.VALIDATION_INVALID_FORMAT:e.ERROR_CODES.VALIDATION_REQUIRED;return new e.ValidationError(t,{code:r,details:{fields:s}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await c(e.map(e=>e.userId),{cacheManager:this.requireClient().getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchUserInfos(e)});return e.map(e=>t.get(e.userId)??e)}async fetchUserInfos(t){if(0===t.length)return[];try{const e=this.getUserInfoManager();return e?await e.getUserInfoByUserId({userIds:t}):await this.fetchUserInfosFromRest(t)}catch(s){return e.logger.warn("ContactManager user info fetch failed",{userIds:t,error:s}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=s.buildFetchUserInfoByUserIdRequest(e),a=await this.getRestClient(t).request(s.buildUserInfoFetchEndpoint(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return s.normalizeFetchedUserInfos(a,r.targets)}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}createSyncController(e){return new Y(e)}};j.key="contactManager";let Q=j;exports.ContactManager=Q,exports.RosterMessageType=d,exports.resolveSingleContactUserInfo=async(e,t)=>((e,t,s)=>({userId:s,nickname:t?.nickname??e?.nickname,avatarUrl:t?.avatarUrl??e?.avatarUrl,mail:t?.mail??e?.mail,phone:t?.phone??e?.phone,gender:t?.gender??e?.gender,sign:t?.sign??e?.sign,birth:t?.birth??e?.birth,ext:t?.ext??e?.ext}))(void 0,(await c([e],t)).get(e),e);
|