easemob-websdk 5.0.1 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/chat-client.d.ts +25 -12
  3. package/chunks/chat-manager-QJCNq-in.cjs +1 -0
  4. package/chunks/chat-manager-QxcfwVLg.js +2 -0
  5. package/chunks/{common-BW2KLpvb.js → common-D_DfwSd3.js} +1 -1
  6. package/chunks/{group-user-info-resolver-Diqjmjyj.js → group-user-info-resolver-lEtRdWli.js} +1 -1
  7. package/chunks/index-Baofxzfc.cjs +1 -0
  8. package/chunks/index-CKbroPac.js +1 -0
  9. package/chunks/index-DIV5mZP8.cjs +1 -0
  10. package/chunks/index-DPi6gEFw.js +1 -0
  11. package/chunks/light-BcQg8h2W.cjs +1 -0
  12. package/chunks/light-DImBnNes.js +1 -0
  13. package/chunks/reflection-proto-codec-7r8Sei3y.js +1 -0
  14. package/chunks/reflection-proto-codec-CwrIKT1L.cjs +1 -0
  15. package/chunks/{session-list-query-DtoToipt.js → session-list-query-rynxSxtv.js} +1 -1
  16. package/chunks/{user-info-22jZtcSi.js → user-info-DfbCp80h.js} +1 -1
  17. package/index.cjs +1 -1
  18. package/index.js +2 -2
  19. package/managers/chat/index.cjs +1 -1
  20. package/managers/chat/index.js +1 -1
  21. package/managers/chat-manager.d.ts +3 -2
  22. package/managers/chat-thread/index.js +1 -1
  23. package/managers/chat-thread-manager.d.ts +3 -2
  24. package/managers/chatroom/index.js +1 -1
  25. package/managers/contact/index.cjs +1 -1
  26. package/managers/contact/index.js +1 -1
  27. package/managers/group/index.cjs +1 -1
  28. package/managers/group/index.js +1 -1
  29. package/managers/presence/index.js +1 -1
  30. package/managers/push/index.js +1 -1
  31. package/managers/user-info/index.js +1 -1
  32. package/package.json +1 -1
  33. package/rest/dns-config.d.ts +10 -2
  34. package/types/chat-client.d.ts +28 -3
  35. package/validators/chat-client.d.ts +13 -5
  36. package/chunks/chat-manager-5wHx7UeW.cjs +0 -1
  37. package/chunks/chat-manager-DdAnJpcH.js +0 -2
  38. package/chunks/index-BItCF8E7.cjs +0 -1
  39. package/chunks/index-DKksD5YM.js +0 -1
  40. package/chunks/index-DKmdsV1-.cjs +0 -1
  41. package/chunks/index-VEUtqiDw.js +0 -1
  42. package/chunks/reflection-proto-codec-64ocOTHU.js +0 -1
  43. package/chunks/reflection-proto-codec-BnQFQdZC.cjs +0 -1
@@ -1 +1 @@
1
- var IMSDK=function(e){"use strict";const t="disconnected",r="connecting",s="connected",n="reconnecting",o="reconnectFailed",i="onConnecting",a="onConnected",c="onDisconnected",d="onReconnectFailed",u="onTokenWillExpire",l="onTokenExpired",h="onOfflineMessageSyncStart",p="onOfflineMessageSyncFinish",m="onSendTimeout",f="onGroupNotify",g="onChatRoomNotify",y="onChatThreadNotify",v="onUserInfoNotify",b="__internal:onMessageSent",I="login",w="reconnect",C="online",S="offline-recover",T="heartbeat-failed",_="send-timeout",R="close",A="error",M="limit",E="offline",U="token-expired",k="onMessage",N="onStreamMessage",O="onConversationListUpdate",x="onMessageReadReceipts",L="onMessageDelivered",P="onMessageRecalled",D="onMessageUpdated",$="onReactionChanged",q="onPinnedMessageChanged",G="onMultiDeviceContact",B="onMultiDeviceConversation",F="onSyncDataStart",j="onSyncDataFinished",z="onPresenceStatusChange",K="onContactInvited",H="onContactDeleted",V="onContactAdded",W="onContactRefuse",J="onContactAgreed",Z="onContactInfoUpdated",Q="onInvitationReceived",Y="onRequestToJoinReceived",X="onRequestToJoinAccepted",ee="onRequestToJoinDeclined",te="onInvitationAccepted",re="onInvitationDeclined",se="onUserRemoved",ne="onGroupDestroyed",oe="onAutoAcceptInvitationFromGroup",ie="onMuteListAdded",ae="onMuteListRemoved",ce="onAllowListAdded",de="onAllowListRemoved",ue="onAllMemberMuteStateChanged",le="onAdminAdded",he="onAdminRemoved",pe="onOwnerChanged",me="onMembersJoined",fe="onMembersExited",ge="onAnnouncementChanged",ye="onSharedFileAdded",ve="onSharedFileDeleted",be="onGroupInfoChanged",Ie="onGroupDisabledChanged",we="onGroupMemberAttributeChanged",Ce="onUserGroupNamecardUpdated",Se="__chatroom:onChatRoomDestroyed",Te="__chatroom:onMembersJoined",_e="__chatroom:onMembersExited",Re="__chatroom:onRemovedFromChatRoom",Ae="__chatroom:onMuteListAdded",Me="__chatroom:onMuteListRemoved",Ee="__chatroom:onAllowListAdded",Ue="__chatroom:onAllowListRemoved",ke="__chatroom:onAllMemberMuteStateChanged",Ne="__chatroom:onAdminAdded",Oe="__chatroom:onAdminRemoved",xe="__chatroom:onOwnerChanged",Le="__chatroom:onAnnouncementChanged",Pe="__chatroom:onChatRoomInfoChanged",De="__chatroom:onAttributesUpdate",$e="__chatroom:onAttributesRemoved",qe="onChatRoomDestroyed",Ge="onMembersJoined",Be="onMembersExited",Fe="onRemovedFromChatRoom",je="onMuteListAdded",ze="onMuteListRemoved",Ke="onAllowListAdded",He="onAllowListRemoved",Ve="onAllMemberMuteStateChanged",We="onAdminAdded",Je="onAdminRemoved",Ze="onOwnerChanged",Qe="onAnnouncementChanged",Ye="onChatRoomInfoChanged",Xe="onAttributesUpdate",et="onAttributesRemoved",rt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function st(e){return"object"==typeof e.stream&&null!==e.stream}const nt=110,ot=110,it=110,at=200,ct=201,dt=202,ut=210,lt=108,ht=213,pt=214,mt=215,ft=301,gt=300,yt=1,vt=301,bt=202,It=300,wt=304,Ct=3,St=300,Tt=301,_t=303,Rt=1,At=500,Mt=500,Et=222,Ut=111,kt=302,Nt=400,Ot=401,xt=407,Lt=501,Pt=502,Dt=504,$t=505,qt=506,Gt=507,Bt=508,Ft=509,jt=510,zt=511,Kt=206,Ht=207,Vt=216,Wt=217,Jt=218,Zt=219,Qt=220,Yt=221,Xt=305,er=403,tr=405,rr=406,sr=1200,nr=1299,or=303,ir=110,ar=4,cr=4,dr=500,ur=2,lr=500,hr=2,pr=301,mr=303,fr=303,gr=602,yr=603,vr=606,br=607,Ir=703,wr=1700,Cr=1701,Sr=1702,Tr=1703,_r=1704,Rr=1110,Ar=1111,Mr=1112,Er=1113,Ur=407,kr=408,Nr=409,Or=410,xr=411,Lr=110,Pr=100,Dr=405,$r=402,qr=301,Gr=1,Br=4,Fr=1,jr="[REDACTED]",zr=e=>{if(!e)return"";const t=e.includes("?"),r=e.includes("#");try{return((e,t,r)=>(e.username&&(e.username=jr),e.password&&(e.password=jr),e.search=t?`?${jr}`:"",e.hash=r?`#${jr}`:"",e.toString()))(new URL(e),t,r)}catch{const t=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===t?"[invalid-url]":`${e.slice(0,t)}?${jr}`}},Kr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,zr(t)]:[e,t]));class Hr extends Error{constructor(e,t=Fr,r){super(e),this.name="SDKError",this.code=t,this.details=r?.details?Kr(r.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,Hr)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class Vr extends Hr{constructor(e,t){super(e,t?.code??hr,t),this.name="NetworkError"}}class Wr extends Hr{constructor(e,t){super(e,t?.code??gt,t),this.name="ConnectionError"}}class Jr extends Hr{constructor(e,t){super(e,t?.code??dt,t),this.name="AuthenticationError"}}class Zr extends Hr{constructor(e,t){super(e,t?.code??it,t),this.name="ValidationError"}}class Qr extends Hr{constructor(e,t){super(e,t?.code??_t,t),this.name="MessageSendError"}}class Yr extends Hr{constructor(e,t){super(e,t?.code??Mt,t),this.name="MessageReceiveError"}}class Xr extends Hr{constructor(e,t){super(e,t?.code??Ct,t),this.name="StorageError"}}class es extends Hr{constructor(e,t){super(e,t?.code??hr,t),this.name="RestTransportError"}}class ts extends Hr{constructor(e,t){super(e,t?.code??fr,t),this.name="RestBusinessError"}}class rs extends Hr{constructor(e,t){super(e,t?.code??$r,t),this.name="UploadError"}}const ss=0,ns=1,os=2,is=3,as=4,cs=0,ds=1,us=2,ls=3,hs=4,ps=5,ms=6,fs=7,gs=8,ys=0,vs=1,bs=2,Is=3,ws=4,Cs=5,Ss=6,Ts=7,_s=8,Rs=0,As=1,Ms=2,Es=3,Us=4,Ns=0,Os=1,xs=2,Ls=3,Ps=5,Ds=0,$s=1,qs=2,Gs=0,Bs=0,Fs=2,js=0,zs=1,Ks=2,Hs=3,Vs=4,Ws=5,Js=6,Zs=7,Qs=8,Ys=9,Xs=10,en=11,tn=12,rn=13,sn=14,nn=15,on=16,an=17,cn=18,dn=19,un=20,ln=1,hn=2,pn=3,mn=4,fn=5,gn=6,yn=7,vn=8,bn="Sorry, user register limit",In="Sorry, user register rate limit",wn="Sorry, token expired",Cn="Sorry, token or password does not match login info",Sn="Sorry, user not found",Tn="Sorry, the app month live count limit",_n="Sorry, the app day live count limit",Rn="Sorry, the app online count limit",An={[zs]:dt,[Ks]:dt,[Hs]:nt,[Vs]:ot,[Ws]:gt,[Js]:lt,[Zs]:ut,[dn]:ut,[Qs]:gt,[Ys]:Fr,[Xs]:Fr,[en]:ht,[tn]:ut,[rn]:pt,[sn]:Br,[nn]:mt,[on]:Fr,[an]:Fr,[cn]:Mt,[un]:Qt},Mn=new Set([zs,Ks,Hs,Vs,Js,Zs,dn,Ys,Xs,en,tn,rn,sn,nn,on,an,cn,un]),En={[bn]:Br,[In]:Br,[wn]:lt,[Cn]:dt,[Sn]:dt,blocked:Et,"group not found":vr,"illegal chatroom tag":nt,"not in group or chatroom":gr,"exceed recall time limit":Dt,"message recall disabled":$t,"group ack not open":$t,"group ack msg permission denied":yr,"the message has expired":qt,"limit send group ack msg":Br,"not in group or chatroom white list":Gt,nonroster:Yt,"group is disabled":br,"roaming is not open":$t,"Sorry, message does not exist":nt,"Sorry, edit limit reached":Br,"Sorry, You do not have permission":ut,"Sorry, format is incorrect":nt,"Sorry, edit is not available":Xt,"Sorry, edit fail":zt},Un=[["limit directed users",Br],["no permission to recall message",ut]],kn={[Tn]:Br,[_n]:Br,[Rn]:Br,"sensitive words":Lt,"blocked by mod_antispam":Lt,"user is mute":Zt,"traffic limit":Ft,"Sorry, data is too large":jt},Nn=(e,t)=>{if("number"!=typeof e)return{code:Fr,retryable:!0};const r=((e,t)=>{if(t){if(e===zs){const e=En[t];if(void 0!==e)return e;for(const[r,s]of Un)if(t.includes(r))return s;try{const e=JSON.parse(t);if("moderation"===e.error_type)return sr;if("string"==typeof e.error_type)return nr}catch{}return}return e===Zs?kn[t]:e===dn?Bt:e===nn?mt:void 0}})(e,t);return{code:r??(An[e]??Fr),retryable:!Mn.has(e)}},On={[Br]:"Message operation exceeded a service limit",[lt]:"Message cannot be sent because the authentication token expired",[nt]:"Message cannot be sent because the request is invalid",[dt]:"Message cannot be sent because authentication failed",[ut]:"Message operation is forbidden",[ht]:"Message cannot be sent because the account is bound to another device",[pt]:"Message cannot be sent because the account is logged in on too many devices",[mt]:"Message cannot be sent because the user is muted in the group or chat room",[Et]:"Message cannot be sent because you are blocked by the recipient",[Zt]:"Message cannot be sent because the user is globally muted",[Qt]:"Message cannot be sent because the current device has changed",[Yt]:"Message cannot be sent because the recipient is not in your contact list",[gt]:"Message cannot be sent because the server is unreachable",[Xt]:"Message editing is not available",[Mt]:"Message processing failed",[Lt]:"Message contains prohibited content",[Pt]:"Message sending traffic limit exceeded",[Dt]:"The message recall time limit has been exceeded",[$t]:"The required messaging service is not enabled",[qt]:"The message has expired",[Gt]:"The user is not in the group or chat room allowlist",[Bt]:"The message was blocked by external logic",[Ft]:"Message sending rate limit exceeded",[jt]:"Message size exceeds the limit",[zt]:"Message editing failed",[gr]:"The user is not in the group or chat room",[yr]:"The user does not have permission to perform this group message operation",[vr]:"The group does not exist",[br]:"The group is disabled",[sr]:"The message was rejected by content moderation",[nr]:"The message was rejected by a third-party service"},xn=3e5,Ln={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"},Pn=e=>"undefined"!=typeof Blob&&e instanceof Blob,Dn=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),r=t.length>0?t[t.length-1]:void 0;if(r)return r},$n=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const r=e.slice(t+1).toLowerCase();return Ln[r]},qn=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t&&t.length>0)return t}},Gn=e=>{const t=e.file,r=e.sourceMeta,s=t.name||(r?qn(r,["name","fileName","filename"]):void 0),n=e.file.type||(r?qn(r,["type","mimeType","filetype"]):void 0),o=e.file.size||(r?((e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t}})(r,["size","fileSize","fileLength"]):void 0),i=Bn({fileName:s,fileType:n,fileSize:o,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize,webFile:e.file}},Bn=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),Fn=e=>{const{file:t,fallbackName:r,fallbackMimeType:s,fallbackSize:n}=e,o=(e=>{if(Pn(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const r of["file","originFileObj","raw","blob"]){const e=t[r];if(Pn(e))return e}})(t);if(o)return Gn({file:o,fallbackName:r,fallbackMimeType:s,fallbackSize:n,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=Dn(t.path),o=Bn({fileName:t.name??e,fileType:t.type??$n(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"miniapp-path",path:t.path,name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize}}if((e=>"object"==typeof e&&null!==e&&"uri"in e)(t)){const e=Dn(t.uri),o=Bn({fileName:t.name??e,fileType:t.type??$n(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"rn-uri",uri:t.uri,name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize}}const i=Bn({fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"web-file",name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}},jn=5242880,zn=5242880,Kn="CHAT",Hn="GROUP",Vn="ROOM",Wn="original",Jn="large",Zn=e=>/^https?:\/\//i.test(e),Qn=e=>{const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw new rs("Invalid appKey for upload",{code:Pr,details:{appKey:e}});return{orgName:t[0],appName:t[1]}},Yn=e=>"singleChat"===e?Kn:"groupChat"===e?Hn:Vn,Xn=(e,t)=>to(e,{size:t}),eo=e=>{try{return decodeURIComponent(e)}catch{return e}},to=(e,t)=>{const[r="",s]=e.split("#",2),[n,o=""]=r.split("?",2),i=o.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const r=encodeURIComponent(e),s=i.filter(t=>{const[s=""]=t.split("=",2);return s!==r&&eo(s)!==e});i.length=0,i.push(...s),void 0!==t&&i.push(`${r}=${encodeURIComponent(String(t))}`)}),`${n}${i.length>0?`?${i.join("&")}`:""}${s?`#${s}`:""}`},ro=(e,t)=>{if(!e)return"";const r={};return e.includes("em-redirect")||(r["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(r["share-secret"]=t),0===Object.keys(r).length?e:to(e,r)},so=e=>{const t=(r=e.messageType,s=e.imageType,"image"!==r?"attachment":s===Wn?"image-origin":"image-big");var r,s;const n=(e=>"image-origin"===e?204800:1048576)(t),o=e.fileSize>n;return{shouldPrecheck:o,thresholdType:t,thresholdBytes:n,actualBytes:e.fileSize,reason:o?"threshold-exceeded":"below-threshold"}},no=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const r=(e=>{const[t="",r]=e.split("#",2),[s,n=""]=t.split("?",2),o=n.split("&").filter(Boolean).filter(e=>{const[t="",r=""]=e.split("=",2),s=eo(t),n=eo(r);return"size"!==s||!["big","large","thumbnail","small"].includes(n)}).join("&");return`${s}${o?`?${o}`:""}${r?`#${r}`:""}`})(e);return{originalImageUrl:r,bigImageUrl:Xn(r,"large"),thumbnailUrl:Xn(r,"small")}},oo=e=>e===Wn?"origin":"large",io=e=>2===e?Jn:Wn,ao=e=>{const t=e.response.entities?.[0];if(!t?.uuid)throw new rs("Upload response missing uuid",{code:$r,details:{response:e.response}});const r=t["share-secret"],s=t["file-metadata"]??{},n="number"==typeof s["content-length"]?s["content-length"]:e.fallbackSize,o="string"==typeof s["content-type"]?s["content-type"]:e.fileType,i=`${e.restBaseUrl}/${e.orgName}/${e.appName}/chatfiles/${t.uuid}`;if("image"===e.messageType){const t=(e.imageType??Jn)===Wn;return{...no(i,{deriveVariants:!e.useCustomAttachmentUpload}),isOriginalImage:t,secret:r,fileLength:n,filetype:o,filename:e.fileName,width:e.width,height:e.height}}const a="video"===e.messageType?`${i}?vframe=true`:void 0;return{url:i,secret:r,fileLength:n,filetype:o,filename:e.fileName,thumbnailUrl:a}},co=e=>new Promise(t=>{setTimeout(t,e)});const uo=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(" "):"",r=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${r}`}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 r=e;for(;r.length>this.maxChunkBytes;)t.push(r.slice(0,this.maxChunkBytes)),r=r.slice(this.maxChunkBytes);return r.length>0&&t.push(r),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 co(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:r,userId:s,token:n,resource:o,requestAdapter:i}=this.context;if(!(t&&r&&s&&n&&i))return!1;let a="",c="";try{const e=Qn(r);a=e.orgName,c=e.appName}catch{return!1}const d=`${t}/${a}/${c}/sdk/users/${s}/client/logs`,u={resource:o??"webim",logContent:e};try{const e=await i.request({url:d,method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json"},body:u,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}}},lo="[MASKED]",ho=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),po=e=>!!e&&ho.has((e=>e.toLowerCase())(e)),mo=(e,t,r)=>{const s=r??new WeakSet;if("string"==typeof e)return((e,t)=>po(t)?lo: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:(n=e).name,message:n.message};var n;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>mo(e,void 0,s));if("object"==typeof e){if(s.has(e))return"[Circular]";if(s.add(e),(e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Date||e instanceof Error))(e)){const t={};for(const[r,n]of Object.entries(e))po(r)?t[r]=lo:t[r]=mo(n,r,s);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},fo="undefined"!=typeof document,go={DEBUG:0,WARN:1,ERROR:2};class yo{constructor(e="WARN"){this.level=e}setLevel(e){this.level=e}shouldLog(e){return go[e]>=go[this.level]}emit(e,t,r){const s=(e=>{const t=new WeakSet;return e.map(e=>mo(e,void 0,t))})(r),n=((e,t,r)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:r}))(e,t,s);uo.append(n);const o=new Date,i=`[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")}`}]`;fo?console.log(`%c${i}`,"color: rgb(0, 157, 255); font-weight: bold",t,...s):console.log(i,t,...s)}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 vo=new yo;function bo(e){uo.setState(e)}function Io(e){uo.updateContext(e)}async function wo(){await uo.reportNow()}function Co(){uo.stop()}const So=(e,...t)=>vo.debug(e,...t),To=(e,...t)=>vo.warn(e,...t),_o=(e,...t)=>vo.error(e,...t),Ro=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>=55296&&s<=56319&&r+1<e.length){const t=e.charCodeAt(r+1);t>=56320&&t<=57343&&(s=65536+(s-55296<<10)+(t-56320),r+=1)}s<=127?t.push(s):s<=2047?t.push(192|s>>6,128|63&s):s<=65535?t.push(224|s>>12,128|s>>6&63,128|63&s):t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}return new Uint8Array(t)},Ao=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r+=1){const s=e[r]??0;if(s<128){t+=String.fromCharCode(s);continue}if(s>=192&&s<224){const n=e[r+1]??0;t+=String.fromCharCode((31&s)<<6|63&n),r+=1;continue}if(s>=224&&s<240){const n=e[r+1]??0,o=e[r+2]??0;t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&o),r+=2;continue}const n=((7&s)<<18|(63&(e[r+1]??0))<<12|(63&(e[r+2]??0))<<6|63&(e[r+3]??0))-65536;t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),r+=3}return t};class Mo{constructor(){this.lastEventKey=null}normalize(e,u){const l=(e=>{switch(e){case r:case n:return i;case s:return a;case t:return c;case o:return d;default:return null}})(e);if(!l)return null;const h=((e,t)=>[e,t.state,t.reason,String(t.attempt),String(t.maxAttempts),String(t.isLoginPhase),String(t.isOnline),String(t.errorCode??""),t.errorMessage??""].join("|"))(l,u);return this.lastEventKey===h?null:(this.lastEventKey=h,{eventName:l,payload:u})}reset(){this.lastEventKey=null}}const Eo={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"},Uo="init",ko="request",No="upload",Oo="socket",xo="proto",Lo="runtime",Po="PLATFORM_INIT_FAILED",Do="PLATFORM_MISSING_CAPABILITY",$o="PLATFORM_REQUEST_FAILED",qo="PLATFORM_UPLOAD_FAILED",Go="PLATFORM_SOCKET_FAILED",Bo="PLATFORM_PROTO_FAILED",Fo=(e,t)=>{const r=new Error(e);return r.name="PlatformAdapterError",r.code=t.code,r.stage=t.stage,r.retryable=t.retryable,t.details&&(r.details=Kr(t.details)),r},jo=0,zo=1,Ko=2,Ho=3,Vo=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],Wo=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const r={},s=e;for(const n of Vo)try{const e=s[n];void 0!==e&&(r[n]=e)}catch{}for(const n of Object.keys(t))r[n]=t[n];return r})("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}:{}})},Jo={web:Eo.WEB,"mp-weixin":Eo.WECHAT_MINIAPP,"mp-alipay":Eo.ALIPAY_MINIAPP,"mp-baidu":Eo.BAIDU_MINIAPP,"mp-toutiao":Eo.TOUTIAO_MINIAPP,"mp-lark":Eo.LARK_MINIAPP,"mp-qq":Eo.QQ_MINIAPP,"mp-kuaishou":Eo.KUAISHOU_MINIAPP,"mp-jd":Eo.JD_MINIAPP,"mp-360":Eo.MINIAPP_360,"mp-harmony":Eo.HARMONY_MINIAPP,"quickapp-webview":Eo.QUICKAPP,"quickapp-webview-union":Eo.QUICKAPP,"quickapp-webview-huawei":Eo.QUICKAPP},Zo=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Qo=e=>(e=>Zo(e,"canIUse")&&Zo(e,"getSystemInfo"))(e)||(e=>Zo(e,"request")&&Zo(e,"connectSocket"))(e),Yo=e=>Zo(e,"request")&&Zo(e,"connectSocket")&&Zo(e,"uploadFile"),Xo=(e,t)=>t===Eo.WECHAT_MINIAPP?e.wx:t===Eo.QQ_MINIAPP?e.qq:t===Eo.TOUTIAO_MINIAPP?e.tt:t===Eo.BAIDU_MINIAPP?e.swan:t===Eo.ALIPAY_MINIAPP?e.my:t===Eo.DINGTALK_MINIAPP?e.dd:t===Eo.JD_MINIAPP?e.jd:t===Eo.KUAISHOU_MINIAPP?e.ks:t===Eo.UNIAPP?e.uni:void 0,ei=e=>{const t=e?.miniGlobal;return Qo(t)?t:e},ti=e=>{const t=ei(e);return Yo(t)?t:void 0},ri=e=>void 0!==e.window&&void 0!==e.document,si=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),ni=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(Qo(t))return!0;try{if(!Zo(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},oi=e=>Yo(e.wx)?Eo.WECHAT_MINIAPP:Yo(e.my)?Eo.ALIPAY_MINIAPP:Yo(e.dd)?Eo.DINGTALK_MINIAPP:Yo(e.swan)?Eo.BAIDU_MINIAPP:Yo(e.tt)?Eo.TOUTIAO_MINIAPP:Yo(e.qq)?Eo.QQ_MINIAPP:Yo(e.jd)?Eo.JD_MINIAPP:Yo(e.ks)?Eo.KUAISHOU_MINIAPP:void 0,ii=e=>void 0!==oi(e),ai=e=>{const t=oi(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return Jo[r]??Eo.UNIAPP}catch{return Eo.UNIAPP}return ri(e)?Eo.WEB:Eo.UNIAPP},ci=(e,t)=>{const r=ti(Xo(e,t));if(r)return r;const s=ti(e.uni);return s||(e.uni??e)},di=(e,t)=>{const r=e??Wo();if(t){const e=t===Eo.UNIAPP||ni(r),s=e?ai(r):t;return{platform:t,hostPlatform:s,framework:e?"uniapp":ri(r)?"web":"native",global:e?ci(r,s):ei(Xo(r,t))??r}}if(ni(r)){const e=ai(r);return{platform:Eo.UNIAPP,hostPlatform:e,framework:"uniapp",global:ci(r,e)}}return Qo(r.swan)?{platform:Eo.BAIDU_MINIAPP,hostPlatform:Eo.BAIDU_MINIAPP,framework:"native",global:ei(r.swan)??r.swan}:Qo(r.tt)?{platform:Eo.TOUTIAO_MINIAPP,hostPlatform:Eo.TOUTIAO_MINIAPP,framework:"native",global:ei(r.tt)??r.tt}:Qo(r.dd)?{platform:Eo.DINGTALK_MINIAPP,hostPlatform:Eo.DINGTALK_MINIAPP,framework:"native",global:ei(r.dd)??r.dd}:Qo(r.my)?{platform:Eo.ALIPAY_MINIAPP,hostPlatform:Eo.ALIPAY_MINIAPP,framework:"native",global:ei(r.my)??r.my}:Qo(r.wx)?{platform:Eo.WECHAT_MINIAPP,hostPlatform:Eo.WECHAT_MINIAPP,framework:"native",global:ei(r.wx)??r.wx}:Qo(r.qq)?{platform:Eo.QQ_MINIAPP,hostPlatform:Eo.QQ_MINIAPP,framework:"native",global:ei(r.qq)??r.qq}:Qo(r.jd)?{platform:Eo.JD_MINIAPP,hostPlatform:Eo.JD_MINIAPP,framework:"native",global:ei(r.jd)??r.jd}:Qo(r.ks)?{platform:Eo.KUAISHOU_MINIAPP,hostPlatform:Eo.KUAISHOU_MINIAPP,framework:"native",global:ei(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:Eo.REACT_NATIVE,hostPlatform:Eo.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:ri(r)?Eo.ELECTRON_RENDERER:Eo.ELECTRON_MAIN,hostPlatform:ri(r)?Eo.ELECTRON_RENDERER:Eo.ELECTRON_MAIN,framework:"electron",global:r}:si(r)||ri(r)?{platform:Eo.WEB,hostPlatform:Eo.WEB,framework:si(r)?"worker":"web",global:r}:{platform:Eo.UNKNOWN,hostPlatform:Eo.UNKNOWN,framework:"native",global:r}},ui=e=>e===Eo.WECHAT_MINIAPP||e===Eo.QQ_MINIAPP||e===Eo.TOUTIAO_MINIAPP||e===Eo.BAIDU_MINIAPP||e===Eo.ALIPAY_MINIAPP||e===Eo.DINGTALK_MINIAPP||e===Eo.LARK_MINIAPP||e===Eo.KUAISHOU_MINIAPP||e===Eo.JD_MINIAPP||e===Eo.MINIAPP_360||e===Eo.HARMONY_MINIAPP||e===Eo.QUICKAPP||e===Eo.UNIAPP,li=["request","upload","socket","proto"],hi=(e,t=li)=>{const r=((e,t=li)=>t.filter(t=>!e[t]))(e,t);if(0!==r.length)throw Fo("Platform missing required capabilities.",{code:Do,stage:Uo,retryable:!1,details:{required:[...t],missing:r}})};var pi=null;try{pi=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function mi(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function fi(e){return!0===(e&&e.__isLong__)}function gi(e){var t=Math.clz32(e&-e);return e?31-t:t}mi.prototype.__isLong__,Object.defineProperty(mi.prototype,"__isLong__",{value:!0}),mi.isLong=fi;var yi={},vi={};function bi(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=vi[e])?s:(r=wi(e,0,!0),n&&(vi[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=yi[e])?s:(r=wi(e,e<0?-1:0,!1),n&&(yi[e]=r),r)}function Ii(e,t){if(isNaN(e))return t?Ui:Ei;if(t){if(e<0)return Ui;if(e>=Ri)return Li}else{if(e<=-Ai)return Pi;if(e+1>=Ai)return xi}return e<0?Ii(-e,t).neg():wi(e%_i|0,e/_i|0,t)}function wi(e,t,r){return new mi(e,t,r)}mi.fromInt=bi,mi.fromNumber=Ii,mi.fromBits=wi;var Ci=Math.pow;function Si(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?Ui:Ei;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return Si(e.substring(1),t,r).neg();for(var n=Ii(Ci(r,8)),o=Ei,i=0;i<e.length;i+=8){var a=Math.min(8,e.length-i),c=parseInt(e.substring(i,i+a),r);if(a<8){var d=Ii(Ci(r,a));o=o.mul(d).add(Ii(c))}else o=(o=o.mul(n)).add(Ii(c))}return o.unsigned=t,o}function Ti(e,t){return"number"==typeof e?Ii(e,t):"string"==typeof e?Si(e,t):wi(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}mi.fromString=Si,mi.fromValue=Ti;var _i=4294967296,Ri=_i*_i,Ai=Ri/2,Mi=bi(1<<24),Ei=bi(0);mi.ZERO=Ei;var Ui=bi(0,!0);mi.UZERO=Ui;var ki=bi(1);mi.ONE=ki;var Ni=bi(1,!0);mi.UONE=Ni;var Oi=bi(-1);mi.NEG_ONE=Oi;var xi=wi(-1,2147483647,!1);mi.MAX_VALUE=xi;var Li=wi(-1,-1,!0);mi.MAX_UNSIGNED_VALUE=Li;var Pi=wi(0,-2147483648,!1);mi.MIN_VALUE=Pi;var Di=mi.prototype;Di.toInt=function(){return this.unsigned?this.low>>>0:this.low},Di.toNumber=function(){return this.unsigned?(this.high>>>0)*_i+(this.low>>>0):this.high*_i+(this.low>>>0)},Di.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Pi)){var t=Ii(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=Ii(Ci(e,6),this.unsigned),o=this,i="";;){var a=o.div(n),c=(o.sub(a.mul(n)).toInt()>>>0).toString(e);if((o=a).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},Di.getHighBits=function(){return this.high},Di.getHighBitsUnsigned=function(){return this.high>>>0},Di.getLowBits=function(){return this.low},Di.getLowBitsUnsigned=function(){return this.low>>>0},Di.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Pi)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},Di.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},Di.isZero=function(){return 0===this.high&&0===this.low},Di.eqz=Di.isZero,Di.isNegative=function(){return!this.unsigned&&this.high<0},Di.isPositive=function(){return this.unsigned||this.high>=0},Di.isOdd=function(){return!(1&~this.low)},Di.isEven=function(){return!(1&this.low)},Di.equals=function(e){return fi(e)||(e=Ti(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Di.eq=Di.equals,Di.notEquals=function(e){return!this.eq(e)},Di.neq=Di.notEquals,Di.ne=Di.notEquals,Di.lessThan=function(e){return this.comp(e)<0},Di.lt=Di.lessThan,Di.lessThanOrEqual=function(e){return this.comp(e)<=0},Di.lte=Di.lessThanOrEqual,Di.le=Di.lessThanOrEqual,Di.greaterThan=function(e){return this.comp(e)>0},Di.gt=Di.greaterThan,Di.greaterThanOrEqual=function(e){return this.comp(e)>=0},Di.gte=Di.greaterThanOrEqual,Di.ge=Di.greaterThanOrEqual,Di.compare=function(e){if(fi(e)||(e=Ti(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Di.comp=Di.compare,Di.negate=function(){return!this.unsigned&&this.eq(Pi)?Pi:this.not().add(ki)},Di.neg=Di.negate,Di.add=function(e){fi(e)||(e=Ti(e));var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,o=e.high>>>16,i=65535&e.high,a=e.low>>>16,c=0,d=0,u=0,l=0;return u+=(l+=n+(65535&e.low))>>>16,d+=(u+=s+a)>>>16,c+=(d+=r+i)>>>16,c+=t+o,wi((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},Di.subtract=function(e){return fi(e)||(e=Ti(e)),this.add(e.neg())},Di.sub=Di.subtract,Di.multiply=function(e){if(this.isZero())return this;if(fi(e)||(e=Ti(e)),pi)return wi(pi.mul(this.low,this.high,e.low,e.high),pi.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Ui:Ei;if(this.eq(Pi))return e.isOdd()?Pi:Ei;if(e.eq(Pi))return this.isOdd()?Pi:Ei;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Mi)&&e.lt(Mi))return Ii(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,o=e.high>>>16,i=65535&e.high,a=e.low>>>16,c=65535&e.low,d=0,u=0,l=0,h=0;return l+=(h+=n*c)>>>16,u+=(l+=s*c)>>>16,l&=65535,u+=(l+=n*a)>>>16,d+=(u+=r*c)>>>16,u&=65535,d+=(u+=s*a)>>>16,u&=65535,d+=(u+=n*i)>>>16,d+=t*c+r*a+s*i+n*o,wi((l&=65535)<<16|(h&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},Di.mul=Di.multiply,Di.divide=function(e){if(fi(e)||(e=Ti(e)),e.isZero())throw Error("division by zero");var t,r,s;if(pi)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?wi((this.unsigned?pi.div_u:pi.div_s)(this.low,this.high,e.low,e.high),pi.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Ui:Ei;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Ui;if(e.gt(this.shru(1)))return Ni;s=Ui}else{if(this.eq(Pi))return e.eq(ki)||e.eq(Oi)?Pi:e.eq(Pi)?ki:(t=this.shr(1).div(e).shl(1)).eq(Ei)?e.isNegative()?ki:Oi:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(Pi))return this.unsigned?Ui:Ei;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Ei}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var n=Math.ceil(Math.log(t)/Math.LN2),o=n<=48?1:Ci(2,n-48),i=Ii(t),a=i.mul(e);a.isNegative()||a.gt(r);)a=(i=Ii(t-=o,this.unsigned)).mul(e);i.isZero()&&(i=ki),s=s.add(i),r=r.sub(a)}return s},Di.div=Di.divide,Di.modulo=function(e){return fi(e)||(e=Ti(e)),pi?wi((this.unsigned?pi.rem_u:pi.rem_s)(this.low,this.high,e.low,e.high),pi.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Di.mod=Di.modulo,Di.rem=Di.modulo,Di.not=function(){return wi(~this.low,~this.high,this.unsigned)},Di.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},Di.clz=Di.countLeadingZeros,Di.countTrailingZeros=function(){return this.low?gi(this.low):gi(this.high)+32},Di.ctz=Di.countTrailingZeros,Di.and=function(e){return fi(e)||(e=Ti(e)),wi(this.low&e.low,this.high&e.high,this.unsigned)},Di.or=function(e){return fi(e)||(e=Ti(e)),wi(this.low|e.low,this.high|e.high,this.unsigned)},Di.xor=function(e){return fi(e)||(e=Ti(e)),wi(this.low^e.low,this.high^e.high,this.unsigned)},Di.shiftLeft=function(e){return fi(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wi(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):wi(0,this.low<<e-32,this.unsigned)},Di.shl=Di.shiftLeft,Di.shiftRight=function(e){return fi(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wi(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):wi(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Di.shr=Di.shiftRight,Di.shiftRightUnsigned=function(e){return fi(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wi(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):wi(32===e?this.high:this.high>>>e-32,0,this.unsigned)},Di.shru=Di.shiftRightUnsigned,Di.shr_u=Di.shiftRightUnsigned,Di.rotateLeft=function(e){var t;return fi(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?wi(this.high,this.low,this.unsigned):e<32?(t=32-e,wi(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),wi(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},Di.rotl=Di.rotateLeft,Di.rotateRight=function(e){var t;return fi(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?wi(this.high,this.low,this.unsigned):e<32?(t=32-e,wi(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),wi(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},Di.rotr=Di.rotateRight,Di.toSigned=function(){return this.unsigned?wi(this.low,this.high,!1):this},Di.toUnsigned=function(){return this.unsigned?this:wi(this.low,this.high,!0)},Di.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Di.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},Di.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},mi.fromBytes=function(e,t,r){return r?mi.fromBytesLE(e,t):mi.fromBytesBE(e,t)},mi.fromBytesLE=function(e,t){return new mi(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},mi.fromBytesBE=function(e,t){return new mi(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(mi.fromBigInt=function(e,t){return wi(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},mi.fromValue=function(e,t){return"bigint"==typeof e?mi.fromBigInt(e,t):Ti(e,t)},Di.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var $i,qi,Gi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Bi={exports:{}},Fi={},ji={};function zi(){if(qi)return $i;return qi=1,$i=function(e,t){var r=new Array(arguments.length-1),s=0,n=2,o=!0;for(;n<arguments.length;)r[s++]=arguments[n++];return new Promise(function(n,i){r[s]=function(e){if(o)if(o=!1,e)i(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];n.apply(null,t)}};try{e.apply(t||null,r)}catch(a){o&&(o=!1,i(a))}})},$i}var Ki,Hi,Vi,Wi,Ji,Zi,Qi,Yi={};function Xi(){return Qi?Zi:(Qi=1,Zi=function(){return null})}var ea,ta,ra,sa,na,oa,ia,aa,ca,da,ua,la,ha,pa,ma={};function fa(){return oa||(oa=1,function(e){var t,r=e;function s(e,t,r){for(var s=Object.keys(t),n=0;n<s.length;++n)void 0!==e[s[n]]&&r||(e[s[n]]=t[s[n]]);return e}function n(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),r&&s(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}r.asPromise=zi(),r.base64=(Ki||(Ki=1,function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var r=new Array(64),s=new Array(123),n=0;n<64;)s[r[n]=n<26?n+65:n<52?n+71:n<62?n-4:n-59|43]=n++;t.encode=function(e,t,s){for(var n,o=null,i=[],a=0,c=0;t<s;){var d=e[t++];switch(c){case 0:i[a++]=r[d>>2],n=(3&d)<<4,c=1;break;case 1:i[a++]=r[n|d>>4],n=(15&d)<<2,c=2;break;case 2:i[a++]=r[n|d>>6],i[a++]=r[63&d],c=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),a=0)}return c&&(i[a++]=r[n],i[a++]=61,1===c&&(i[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,i.slice(0,a))),o.join("")):String.fromCharCode.apply(String,i.slice(0,a))};var o="invalid encoding";t.decode=function(e,t,r){for(var n,i=r,a=0,c=0;c<e.length;){var d=e.charCodeAt(c++);if(61===d&&a>1)break;if(void 0===(d=s[d]))throw Error(o);switch(a){case 0:n=d,a=1;break;case 1:t[r++]=n<<2|(48&d)>>4,n=d,a=2;break;case 2:t[r++]=(15&n)<<4|(60&d)>>2,n=d,a=3;break;case 3:t[r++]=(3&n)<<6|d,a=0}}if(1===a)throw Error(o);return r-i},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(Yi)),Yi),r.EventEmitter=function(){if(Vi)return Hi;function e(){this._listeners={}}return Vi=1,Hi=e,e.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},e.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],s=0;s<r.length;)r[s].fn===t?r.splice(s,1):++s;return this},e.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var r=[],s=1;s<arguments.length;)r.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,r)}return this},Hi}(),r.float=function(){if(Ji)return Wi;function e(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),s=128===r[3];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3]}function o(e,s,n){t[0]=e,s[n]=r[3],s[n+1]=r[2],s[n+2]=r[1],s[n+3]=r[0]}function i(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],t[0]}function a(e,s){return r[3]=e[s],r[2]=e[s+1],r[1]=e[s+2],r[0]=e[s+3],t[0]}e.writeFloatLE=s?n:o,e.writeFloatBE=s?o:n,e.readFloatLE=s?i:a,e.readFloatBE=s?a:i}():function(){function o(e,t,r,s){var n=t<0?1:0;if(n&&(t=-t),0===t)e(1/t>0?0:2147483648,r,s);else if(isNaN(t))e(2143289344,r,s);else if(t>34028234663852886e22)e((n<<31|2139095040)>>>0,r,s);else if(t<11754943508222875e-54)e((n<<31|Math.round(t/1401298464324817e-60))>>>0,r,s);else{var o=Math.floor(Math.log(t)/Math.LN2);e((n<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,r,s)}}function i(e,t,r){var s=e(t,r),n=2*(s>>31)+1,o=s>>>23&255,i=8388607&s;return 255===o?i?NaN:n*(1/0):0===o?1401298464324817e-60*n*i:n*Math.pow(2,o-150)*(i+8388608)}e.writeFloatLE=o.bind(null,t),e.writeFloatBE=o.bind(null,r),e.readFloatLE=i.bind(null,s),e.readFloatBE=i.bind(null,n)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),s=128===r[7];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3],s[n+4]=r[4],s[n+5]=r[5],s[n+6]=r[6],s[n+7]=r[7]}function o(e,s,n){t[0]=e,s[n]=r[7],s[n+1]=r[6],s[n+2]=r[5],s[n+3]=r[4],s[n+4]=r[3],s[n+5]=r[2],s[n+6]=r[1],s[n+7]=r[0]}function i(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],r[4]=e[s+4],r[5]=e[s+5],r[6]=e[s+6],r[7]=e[s+7],t[0]}function a(e,s){return r[7]=e[s],r[6]=e[s+1],r[5]=e[s+2],r[4]=e[s+3],r[3]=e[s+4],r[2]=e[s+5],r[1]=e[s+6],r[0]=e[s+7],t[0]}e.writeDoubleLE=s?n:o,e.writeDoubleBE=s?o:n,e.readDoubleLE=s?i:a,e.readDoubleBE=s?a:i}():function(){function o(e,t,r,s,n,o){var i=s<0?1:0;if(i&&(s=-s),0===s)e(0,n,o+t),e(1/s>0?0:2147483648,n,o+r);else if(isNaN(s))e(0,n,o+t),e(2146959360,n,o+r);else if(s>17976931348623157e292)e(0,n,o+t),e((i<<31|2146435072)>>>0,n,o+r);else{var a;if(s<22250738585072014e-324)e((a=s/5e-324)>>>0,n,o+t),e((i<<31|a/4294967296)>>>0,n,o+r);else{var c=Math.floor(Math.log(s)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=s*Math.pow(2,-c))>>>0,n,o+t),e((i<<31|c+1023<<20|1048576*a&1048575)>>>0,n,o+r)}}}function i(e,t,r,s,n){var o=e(s,n+t),i=e(s,n+r),a=2*(i>>31)+1,c=i>>>20&2047,d=4294967296*(1048575&i)+o;return 2047===c?d?NaN:a*(1/0):0===c?5e-324*a*d:a*Math.pow(2,c-1075)*(d+4503599627370496)}e.writeDoubleLE=o.bind(null,t,0,4),e.writeDoubleBE=o.bind(null,r,4,0),e.readDoubleLE=i.bind(null,s,0,4),e.readDoubleBE=i.bind(null,n,4,0)}(),e}function t(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function r(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function n(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return Ji=1,Wi=e(e)}(),r.inquire=Xi(),r.utf8=(ea||(ea=1,(t=ma).length=function(e){for(var t=0,r=0,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(s+1))?(++s,t+=4):t+=3;return t},t.read=function(e,t,r){if(r-t<1)return"";for(var s,n=null,o=[],i=0;t<r;)(s=e[t++])<128?o[i++]=s:s>191&&s<224?o[i++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[i++]=55296+(s>>10),o[i++]=56320+(1023&s)):o[i++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((n||(n=[])).push(String.fromCharCode.apply(String,o)),i=0);return n?(i&&n.push(String.fromCharCode.apply(String,o.slice(0,i))),n.join("")):String.fromCharCode.apply(String,o.slice(0,i))},t.write=function(e,t,r){for(var s,n,o=r,i=0;i<e.length;++i)(s=e.charCodeAt(i))<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(i+1)))?(s=65536+((1023&s)<<10)+(1023&n),++i,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-o}),ma),r.pool=ra?ta:(ra=1,ta=function(e,t,r){var s=r||8192,n=s>>>1,o=null,i=s;return function(r){if(r<1||r>n)return e(r);i+r>s&&(o=e(s),i=0);var a=t.call(o,i,i+=r);return 7&i&&(i=1+(7|i)),a}}),r.LongBits=function(){if(na)return sa;na=1,sa=t;var e=fa();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var s=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return r;var s=e<0;s&&(e=-e);var n=e>>>0,o=(e-n)/4294967296>>>0;return s&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)},t.from=function(s){if("number"==typeof s)return t.fromNumber(s);if(e.isString(s)){if(!e.Long)return t.fromNumber(parseInt(s,10));s=e.Long.fromString(s)}return s.low||s.high?new t(s.low>>>0,s.high>>>0):r},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return t.fromHash=function(e){return e===s?r:new t((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10},sa}(),r.isNode=Boolean(void 0!==Gi&&Gi&&Gi.process&&Gi.process.versions&&Gi.process.versions.node),r.global=r.isNode&&Gi||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||ji,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},r.isString=function(e){return"string"==typeof e||e instanceof String},r.isObject=function(e){return e&&"object"==typeof e},r.isset=r.isSet=function(e,t){var r=e[t];return!(null==r||!e.hasOwnProperty(t))&&("object"!=typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},r.Buffer=function(){try{var e=r.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(e){return"number"==typeof e?r.Buffer?r._Buffer_allocUnsafe(e):new r.Array(e):r.Buffer?r._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(e){return e?r.LongBits.from(e).toHash():r.LongBits.zeroHash},r.longFromHash=function(e,t){var s=r.LongBits.fromHash(e);return r.Long?r.Long.fromBits(s.lo,s.hi,t):s.toNumber(Boolean(t))},r.merge=s,r.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},r.newError=n,r.ProtocolError=n("ProtocolError"),r.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;r>-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},r.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r._configure=function(){var e=r.Buffer;e?(r._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},r._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):r._Buffer_from=r._Buffer_allocUnsafe=null}}(ji)),ji}function ga(){if(aa)return ia;aa=1,ia=c;var e,t=fa(),r=t.LongBits,s=t.base64,n=t.utf8;function o(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function i(){}function a(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function c(){this.len=0,this.head=new o(i,0,0),this.tail=this.head,this.states=null}var d=function(){return t.Buffer?function(){return(c.create=function(){return new e})()}:function(){return new c}};function u(e,t,r){t[r]=255&e}function l(e,t){this.len=e,this.next=void 0,this.val=t}function h(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function p(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}c.create=d(),c.alloc=function(e){return new t.Array(e)},t.Array!==Array&&(c.alloc=t.pool(c.alloc,t.Array.prototype.subarray)),c.prototype._push=function(e,t,r){return this.tail=this.tail.next=new o(e,t,r),this.len+=t,this},l.prototype=Object.create(o.prototype),l.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},c.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new l((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},c.prototype.int32=function(e){return e<0?this._push(h,10,r.fromNumber(e)):this.uint32(e)},c.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},c.prototype.uint64=function(e){var t=r.from(e);return this._push(h,t.length(),t)},c.prototype.int64=c.prototype.uint64,c.prototype.sint64=function(e){var t=r.from(e).zzEncode();return this._push(h,t.length(),t)},c.prototype.bool=function(e){return this._push(u,1,e?1:0)},c.prototype.fixed32=function(e){return this._push(p,4,e>>>0)},c.prototype.sfixed32=c.prototype.fixed32,c.prototype.fixed64=function(e){var t=r.from(e);return this._push(p,4,t.lo)._push(p,4,t.hi)},c.prototype.sfixed64=c.prototype.fixed64,c.prototype.float=function(e){return this._push(t.float.writeFloatLE,4,e)},c.prototype.double=function(e){return this._push(t.float.writeDoubleLE,8,e)};var m=t.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var s=0;s<e.length;++s)t[r+s]=e[s]};return c.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(u,1,0);if(t.isString(e)){var n=c.alloc(r=s.length(e));s.decode(e,n,0),e=n}return this.uint32(r)._push(m,r,e)},c.prototype.string=function(e){var t=n.length(e);return t?this.uint32(t)._push(n.write,t,e):this._push(u,1,0)},c.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new o(i,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new o(i,0,0),this.len=0),this},c.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},c.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},c._configure=function(t){e=t,c.create=d(),e._configure()},ia}function ya(){if(la)return ua;la=1,ua=o;var e,t=fa(),r=t.LongBits,s=t.utf8;function n(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function o(e){this.buf=e,this.pos=0,this.len=e.length}var i="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new o(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new o(e);throw Error("illegal buffer")},a=function(){return t.Buffer?function(r){return(o.create=function(r){return t.Buffer.isBuffer(r)?new e(r):i(r)})(r)}:i};function c(){var e=new r(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw n(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw n(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function u(){if(this.pos+8>this.len)throw n(this,8);return new r(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}return o.create=a(),o.prototype._slice=t.Array.prototype.subarray||t.Array.prototype.slice,o.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,n(this,10);return e}}(),o.prototype.int32=function(){return 0|this.uint32()},o.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},o.prototype.bool=function(){return 0!==this.uint32()},o.prototype.fixed32=function(){if(this.pos+4>this.len)throw n(this,4);return d(this.buf,this.pos+=4)},o.prototype.sfixed32=function(){if(this.pos+4>this.len)throw n(this,4);return 0|d(this.buf,this.pos+=4)},o.prototype.float=function(){if(this.pos+4>this.len)throw n(this,4);var e=t.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},o.prototype.double=function(){if(this.pos+8>this.len)throw n(this,4);var e=t.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},o.prototype.bytes=function(){var e=this.uint32(),r=this.pos,s=this.pos+e;if(s>this.len)throw n(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,s);if(r===s){var o=t.Buffer;return o?o.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,s)},o.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},o.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw n(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw n(this)}while(128&this.buf[this.pos++]);return this},o.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},o._configure=function(r){e=r,o.create=a(),e._configure();var s=t.Long?"toLong":"toNumber";t.merge(o.prototype,{int64:function(){return c.call(this)[s](!1)},uint64:function(){return c.call(this)[s](!0)},sint64:function(){return c.call(this).zzDecode()[s](!1)},fixed64:function(){return u.call(this)[s](!0)},sfixed64:function(){return u.call(this)[s](!1)}})},ua}var va,ba,Ia,wa,Ca,Sa,Ta={};function _a(){return Ia||(Ia=1,Ta.Service=function(){if(ba)return va;ba=1,va=t;var e=fa();function t(t,r,s){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");e.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(r),this.responseDelimited=Boolean(s)}return(t.prototype=Object.create(e.EventEmitter.prototype)).constructor=t,t.prototype.rpcCall=function t(r,s,n,o,i){if(!o)throw TypeError("request must be specified");var a=this;if(!i)return e.asPromise(t,a,r,s,n,o);if(a.rpcImpl)try{return a.rpcImpl(r,s[a.requestDelimited?"encodeDelimited":"encode"](o).finish(),function(e,t){if(e)return a.emit("error",e,r),i(e);if(null!==t){if(!(t instanceof n))try{t=n[a.responseDelimited?"decodeDelimited":"decode"](t)}catch(s){return a.emit("error",s,r),i(s)}return a.emit("data",t,r),i(null,t)}a.end(!0)})}catch(c){return a.emit("error",c,r),void setTimeout(function(){i(c)},0)}else setTimeout(function(){i(Error("already ended"))},0)},t.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},va}()),Ta}function Ra(){return Ca?wa:(Ca=1,wa={})}function Aa(){return Sa||(Sa=1,function(e){var t=e;function r(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=ga(),t.BufferWriter=function(){if(da)return ca;da=1,ca=r;var e=ga();(r.prototype=Object.create(e.prototype)).constructor=r;var t=fa();function r(){e.call(this)}function s(e,r,s){e.length<40?t.utf8.write(e,r,s):r.utf8Write?r.utf8Write(e,s):r.write(e,s)}return r._configure=function(){r.alloc=t._Buffer_allocUnsafe,r.writeBytesBuffer=t.Buffer&&t.Buffer.prototype instanceof Uint8Array&&"set"===t.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var s=0;s<e.length;)t[r++]=e[s++]}},r.prototype.bytes=function(e){t.isString(e)&&(e=t._Buffer_from(e,"base64"));var s=e.length>>>0;return this.uint32(s),s&&this._push(r.writeBytesBuffer,s,e),this},r.prototype.string=function(e){var r=t.Buffer.byteLength(e);return this.uint32(r),r&&this._push(s,r,e),this},r._configure(),ca}(),t.Reader=ya(),t.BufferReader=function(){if(pa)return ha;pa=1,ha=r;var e=ya();(r.prototype=Object.create(e.prototype)).constructor=r;var t=fa();function r(t){e.call(this,t)}return r._configure=function(){t.Buffer&&(r.prototype._slice=t.Buffer.prototype.slice)},r.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},r._configure(),ha}(),t.util=fa(),t.rpc=_a(),t.roots=Ra(),t.configure=r,r()}(Fi)),Fi}var Ma,Ea,Ua,ka,Na={},Oa={exports:{}};var xa,La,Pa,Da,$a,qa,Ga,Ba,Fa,ja,za,Ka,Ha,Va,Wa,Ja={};function Za(){if(Pa)return La;Pa=1,La=c;var e=xc();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=Nc(),o=Uc(),i=Oc();function a(e,t){if(e&&e.length){for(var r={},s=0;s<e.length;++s)r[e[s].name]=e[s].toJSON(t);return r}}function c(t,r){e.call(this,t,r),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function d(e){e._nestedArray=null,e._lookupCache={};for(var t=e;t=t.parent;)t._lookupCache={};return e}return c.fromJSON=function(e,t){return new c(e,t.options).addJSON(t.nested)},c.arrayToJSON=a,c.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},c.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(c.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=o.toArray(this.nested))}}),c.prototype.toJSON=function(e){return o.toObject(["options",this.options,"nested",a(this.nestedArray,e)])},c.prototype.addJSON=function(e){if(e)for(var o,i=Object.keys(e),a=0;a<i.length;++a)o=e[i[a]],this.add((void 0!==o.fields?t.fromJSON:void 0!==o.values?s.fromJSON:void 0!==o.methods?r.fromJSON:void 0!==o.id?n.fromJSON:c.fromJSON)(i[a],o));return this},c.prototype.get=function(e){return this.nested&&this.nested[e]||null},c.prototype.getEnum=function(e){if(this.nested&&this.nested[e]instanceof s)return this.nested[e].values;throw Error("no such enum: "+e)},c.prototype.add=function(e){if(!(e instanceof n&&void 0!==e.extend||e instanceof t||e instanceof i||e instanceof s||e instanceof r||e instanceof c))throw TypeError("object must be a valid nested object");if(this.nested){var o=this.get(e.name);if(o){if(!(o instanceof c&&e instanceof c)||o instanceof t||o instanceof r)throw Error("duplicate name '"+e.name+"' in "+this);for(var a=o.nestedArray,u=0;u<a.length;++u)e.add(a[u]);this.remove(o),this.nested||(this.nested={}),e.setOptions(o.options,!0)}}else this.nested={};this.nested[e.name]=e,this instanceof t||this instanceof r||this instanceof s||this instanceof n||e._edition||(e._edition=e._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var l=this;l=l.parent;)l._needsRecursiveFeatureResolution=!0,l._needsRecursiveResolve=!0;return e.onAdd(this),d(this)},c.prototype.remove=function(t){if(!(t instanceof e))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=void 0),t.onRemove(this),d(this)},c.prototype.define=function(e,t){if(o.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");for(var r=this;e.length>0;){var s=e.shift();if(r.nested&&r.nested[s]){if(!((r=r.nested[s])instanceof c))throw Error("path conflicts with non-namespace objects")}else r.add(r=new c(s))}return t&&r.addJSON(t),r},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var e=this.nestedArray,t=0;for(this.resolve();t<e.length;)e[t]instanceof c?e[t++].resolveAll():e[t++].resolve();return this._needsRecursiveResolve=!1,this},c.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.nestedArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},c.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),o.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;var s=e.join(".");if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+s];if(n&&(!t||t.indexOf(n.constructor)>-1))return n;if((n=this._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;if(r)return null;for(var i=this;i.parent;){if((n=i.parent._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;i=i.parent}return null},c.prototype._lookupImpl=function(e,t){if(Object.prototype.hasOwnProperty.call(this._lookupCache,t))return this._lookupCache[t];var r=this.get(e[0]),s=null;if(r)1===e.length?s=r:r instanceof c&&(e=e.slice(1),s=r._lookupImpl(e,e.join(".")));else for(var n=0;n<this.nestedArray.length;++n)this._nestedArray[n]instanceof c&&(r=this._nestedArray[n]._lookupImpl(e,t))&&(s=r);return this._lookupCache[t]=s,s},c.prototype.lookupType=function(e){var r=this.lookup(e,[t]);if(!r)throw Error("no such type: "+e);return r},c.prototype.lookupEnum=function(e){var t=this.lookup(e,[s]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},c.prototype.lookupTypeOrEnum=function(e){var r=this.lookup(e,[t,s]);if(!r)throw Error("no such Type or Enum '"+e+"' in "+this);return r},c.prototype.lookupService=function(e){var t=this.lookup(e,[r]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},c._configure=function(e,n,o){t=e,r=n,s=o},La}function Qa(){if($a)return Da;$a=1,Da=s;var e=Nc();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=kc(),r=Uc();function s(t,s,n,o,i,a){if(e.call(this,t,s,o,void 0,void 0,i,a),!r.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}return s.fromJSON=function(e,t){return new s(e,t.id,t.keyType,t.type,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},s.prototype.resolve=function(){if(this.resolved)return this;if(void 0===t.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return e.prototype.resolve.call(this)},s.d=function(e,t,n){return"function"==typeof n?n=r.decorateType(n).name:n&&"object"==typeof n&&(n=r.decorateEnum(n).name),function(o,i){r.decorateType(o.constructor).add(new s(i,e,t,n))}},Da}function Ya(){if(Ga)return qa;Ga=1,qa=r;var e=xc();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=Uc();function r(r,s,n,o,i,a,c,d,u){if(t.isObject(i)?(c=i,i=a=void 0):t.isObject(a)&&(c=a,a=void 0),void 0!==s&&!t.isString(s))throw TypeError("type must be a string");if(!t.isString(n))throw TypeError("requestType must be a string");if(!t.isString(o))throw TypeError("responseType must be a string");e.call(this,r,c),this.type=s||"rpc",this.requestType=n,this.requestStream=!!i||void 0,this.responseType=o,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=d,this.parsedOptions=u}return r.fromJSON=function(e,t){return new r(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},r.prototype.toJSON=function(e){var r=!!e&&Boolean(e.keepComments);return t.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",r?this.comment:void 0,"parsedOptions",this.parsedOptions])},r.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),e.prototype.resolve.call(this))},qa}function Xa(){if(Fa)return Ba;Fa=1,Ba=n;var e=Za();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=Ya(),r=Uc(),s=_a();function n(t,r){e.call(this,t,r),this.methods={},this._methodsArray=null}function o(e){return e._methodsArray=null,e}return n.fromJSON=function(e,r){var s=new n(e,r.options);if(r.methods)for(var o=Object.keys(r.methods),i=0;i<o.length;++i)s.add(t.fromJSON(o[i],r.methods[o[i]]));return r.nested&&s.addJSON(r.nested),r.edition&&(s._edition=r.edition),s.comment=r.comment,s._defaultEdition="proto3",s},n.prototype.toJSON=function(t){var s=e.prototype.toJSON.call(this,t),n=!!t&&Boolean(t.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",s&&s.options||void 0,"methods",e.arrayToJSON(this.methodsArray,t)||{},"nested",s&&s.nested||void 0,"comment",n?this.comment:void 0])},Object.defineProperty(n.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=r.toArray(this.methods))}}),n.prototype.get=function(t){return this.methods[t]||e.prototype.get.call(this,t)},n.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolve.call(this);for(var t=this.methodsArray,r=0;r<t.length;++r)t[r].resolve();return this},n.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.methodsArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},n.prototype.add=function(r){if(this.get(r.name))throw Error("duplicate name '"+r.name+"' in "+this);return r instanceof t?(this.methods[r.name]=r,r.parent=this,o(this)):e.prototype.add.call(this,r)},n.prototype.remove=function(r){if(r instanceof t){if(this.methods[r.name]!==r)throw Error(r+" is not a member of "+this);return delete this.methods[r.name],r.parent=null,o(this)}return e.prototype.remove.call(this,r)},n.prototype.create=function(e,t,n){for(var o,i=new s.Service(e,t,n),a=0;a<this.methodsArray.length;++a){var c=r.lcFirst((o=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"");i[c]=r.codegen(["r","c"],r.isReserved(c)?c+"_":c)("return this.rpcCall(m,q,s,r,c)")({m:o,q:o.resolvedRequestType.ctor,s:o.resolvedResponseType.ctor})}return i},Ba}function ec(){if(za)return ja;za=1,ja=t;var e=fa();function t(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r)this[t[r]]=e[t[r]]}return t.create=function(e){return this.$type.create(e)},t.encode=function(e,t){return this.$type.encode(e,t)},t.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},t.decode=function(e){return this.$type.decode(e)},t.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},t.verify=function(e){return this.$type.verify(e)},t.fromObject=function(e){return this.$type.fromObject(e)},t.toObject=function(e,t){return this.$type.toObject(e,t)},t.prototype.toJSON=function(){return this.$type.toObject(this,e.toJSONOptions)},ja}function tc(){if(Ha)return Ka;Ha=1,Ka=function(n){for(var o=r.codegen(["r","l","e"],n.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(n.fieldsArray.filter(function(e){return e.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),i=0;i<n.fieldsArray.length;++i){var a=n._fieldsArray[i].resolve(),c=a.resolvedType instanceof e?"int32":a.type,d="m"+r.safeProp(a.name);o("case %i: {",a.id),a.map?(o("if(%s===util.emptyObject)",d)("%s={}",d)("var c2 = r.uint32()+r.pos"),void 0!==t.defaults[a.keyType]?o("k=%j",t.defaults[a.keyType]):o("k=null"),void 0!==t.defaults[c]?o("value=%j",t.defaults[c]):o("value=null"),o("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===t.basic[c]?o("value=types[%i].decode(r,r.uint32())",i):o("value=r.%s()",c),o("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==t.long[a.keyType]?o('%s[typeof k==="object"?util.longToHash(k):k]=value',d):o("%s[k]=value",d)):a.repeated?(o("if(!(%s&&%s.length))",d,d)("%s=[]",d),void 0!==t.packed[c]&&o("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",d,c)("}else"),void 0===t.basic[c]?o(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",d,i):o("%s.push(r.%s())",d,c)):void 0===t.basic[c]?o(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",d,i):o("%s=r.%s()",d,c),o("break")("}")}for(o("default:")("r.skipType(t&7)")("break")("}")("}"),i=0;i<n._fieldsArray.length;++i){var u=n._fieldsArray[i];u.required&&o("if(!m.hasOwnProperty(%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",s(u))}return o("return m")};var e=Lc(),t=kc(),r=Uc();function s(e){return"missing required '"+e.name+"'"}return Ka}function rc(){if(Wa)return Va;Wa=1,Va=function(e){var o=t.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),i=e.oneofsArray,a={};i.length&&o("var p={}");for(var c=0;c<e.fieldsArray.length;++c){var d=e._fieldsArray[c].resolve(),u="m"+t.safeProp(d.name);if(d.optional&&o("if(%s!=null&&m.hasOwnProperty(%j)){",u,d.name),d.map)o("if(!util.isObject(%s))",u)("return%j",r(d,"object"))("var k=Object.keys(%s)",u)("for(var i=0;i<k.length;++i){"),n(o,d,"k[i]"),s(o,d,c,u+"[k[i]]")("}");else if(d.repeated)o("if(!Array.isArray(%s))",u)("return%j",r(d,"array"))("for(var i=0;i<%s.length;++i){",u),s(o,d,c,u+"[i]")("}");else{if(d.partOf){var l=t.safeProp(d.partOf.name);1===a[d.partOf.name]&&o("if(p%s===1)",l)("return%j",d.partOf.name+": multiple values"),a[d.partOf.name]=1,o("p%s=1",l)}s(o,d,c,u)}d.optional&&o("}")}return o("return null")};var e=Lc(),t=Uc();function r(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function s(t,s,n,o){if(s.resolvedType)if(s.resolvedType instanceof e){t("switch(%s){",o)("default:")("return%j",r(s,"enum value"));for(var i=Object.keys(s.resolvedType.values),a=0;a<i.length;++a)t("case %i:",s.resolvedType.values[i[a]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s);",n,o)("if(e)")("return%j+e",s.name+".")("}");else switch(s.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",o)("return%j",r(s,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",o,o,o,o)("return%j",r(s,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',o)("return%j",r(s,"number"));break;case"bool":t('if(typeof %s!=="boolean")',o)("return%j",r(s,"boolean"));break;case"string":t("if(!util.isString(%s))",o)("return%j",r(s,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',o,o,o)("return%j",r(s,"buffer"))}return t}function n(e,t,s){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",s)("return%j",r(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",s)("return%j",r(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",s)("return%j",r(t,"boolean key"))}return e}return Va}var sc,nc={};function oc(){return sc||(sc=1,function(e){var t=e,r=Lc(),s=Uc();function n(e,t,s,n){var o=!1;if(t.resolvedType)if(t.resolvedType instanceof r){e("switch(d%s){",n);for(var i=t.resolvedType.values,a=Object.keys(i),c=0;c<a.length;++c)i[a[c]]!==t.typeDefault||o||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),o=!0),e("case%j:",a[c])("case %i:",i[a[c]])("m%s=%j",n,i[a[c]])("break");e("}")}else e('if(typeof d%s!=="object")',n)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",n,s,n);else{var d=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",n,n);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":d=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,d)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,d?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function o(e,t,s,n){if(t.resolvedType)t.resolvedType instanceof r?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,s,n,n,s,n,n):e("d%s=types[%i].toObject(m%s,o)",n,s,n);else{var o=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":o=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,o?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}t.fromObject=function(e){var t=e.fieldsArray,o=s.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return o("return new this.ctor");o("var m=new this.ctor");for(var i=0;i<t.length;++i){var a=t[i].resolve(),c=s.safeProp(a.name);a.map?(o("if(d%s){",c)('if(typeof d%s!=="object")',c)("throw TypeError(%j)",a.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),n(o,a,i,c+"[ks[i]]")("}")("}")):a.repeated?(o("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),n(o,a,i,c+"[i]")("}")("}")):(a.resolvedType instanceof r||o("if(d%s!=null){",c),n(o,a,i,c),a.resolvedType instanceof r||o("}"))}return o("return m")},t.toObject=function(e){var t=e.fieldsArray.slice().sort(s.compareFieldsById);if(!t.length)return s.codegen()("return {}");for(var n=s.codegen(["m","o"],e.name+"$toObject")("if(!o)")("o={}")("var d={}"),i=[],a=[],c=[],d=0;d<t.length;++d)t[d].partOf||(t[d].resolve().repeated?i:t[d].map?a:c).push(t[d]);if(i.length){for(n("if(o.arrays||o.defaults){"),d=0;d<i.length;++d)n("d%s=[]",s.safeProp(i[d].name));n("}")}if(a.length){for(n("if(o.objects||o.defaults){"),d=0;d<a.length;++d)n("d%s={}",s.safeProp(a[d].name));n("}")}if(c.length){for(n("if(o.defaults){"),d=0;d<c.length;++d){var u=c[d],l=s.safeProp(u.name);if(u.resolvedType instanceof r)n("d%s=o.enums===String?%j:%j",l,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",l)("}else")("d%s=o.longs===String?%j:%i",l,u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var h="["+Array.prototype.slice.call(u.typeDefault).join(",")+"]";n("if(o.bytes===String)d%s=%j",l,String.fromCharCode.apply(String,u.typeDefault))("else{")("d%s=%s",l,h)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",l,l)("}")}else n("d%s=%j",l,u.typeDefault)}n("}")}var p=!1;for(d=0;d<t.length;++d){u=t[d];var m=e._fieldsArray.indexOf(u);l=s.safeProp(u.name);u.map?(p||(p=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",l,l)("d%s={}",l)("for(var j=0;j<ks2.length;++j){"),o(n,u,m,l+"[ks2[j]]")("}")):u.repeated?(n("if(m%s&&m%s.length){",l,l)("d%s=[]",l)("for(var j=0;j<m%s.length;++j){",l),o(n,u,m,l+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",l,u.name),o(n,u,m,l),u.partOf&&n("if(o.oneofs)")("d%s=%j",s.safeProp(u.partOf.name),u.name)),n("}")}return n("return d")}}(nc)),nc}var ic,ac,cc,dc,uc,lc,hc,pc,mc,fc,gc,yc,vc,bc,Ic,wc,Cc,Sc,Tc,_c,Rc={};function Ac(){return ic||(ic=1,e=Rc,t=ec(),e[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var s="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===s.indexOf("/")&&(s="/"+s),this.create({type_url:s,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,r){var s="",n="";if(r&&r.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),s=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var o=this.lookup(n);o&&(e=o.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof t){var i=e.$type.toObject(e,r);return""===s&&(s="type.googleapis.com/"),n=s+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),i["@type"]=n,i}return this.toObject(e,r)}}),Rc;var e,t}function Mc(){if(cc)return ac;cc=1,ac=f;var e=Za();((f.prototype=Object.create(e.prototype)).constructor=f).className="Type";var t=Lc(),r=Oc(),s=Nc(),n=Qa(),o=Xa(),i=ec(),a=ya(),c=ga(),d=Uc(),u=Pc(),l=tc(),h=rc(),p=oc(),m=Ac();function f(t,r){e.call(this,t,r),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function g(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}return Object.defineProperties(f.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],s=r.id;if(this._fieldsById[s])throw Error("duplicate id "+s+" in "+this);this._fieldsById[s]=r}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=f.generateConstructor(this)())},set:function(e){var t=e.prototype;t instanceof i||((e.prototype=new i).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,i,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var s={};for(r=0;r<this.oneofsArray.length;++r)s[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,s)}}}),f.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),s=0;s<e.fieldsArray.length;++s)(t=e._fieldsArray[s]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},f.fromJSON=function(i,a){var c=new f(i,a.options);c.extensions=a.extensions,c.reserved=a.reserved;for(var d=Object.keys(a.fields),u=0;u<d.length;++u)c.add((void 0!==a.fields[d[u]].keyType?n.fromJSON:s.fromJSON)(d[u],a.fields[d[u]]));if(a.oneofs)for(d=Object.keys(a.oneofs),u=0;u<d.length;++u)c.add(r.fromJSON(d[u],a.oneofs[d[u]]));if(a.nested)for(d=Object.keys(a.nested),u=0;u<d.length;++u){var l=a.nested[d[u]];c.add((void 0!==l.id?s.fromJSON:void 0!==l.fields?f.fromJSON:void 0!==l.values?t.fromJSON:void 0!==l.methods?o.fromJSON:e.fromJSON)(d[u],l))}return a.extensions&&a.extensions.length&&(c.extensions=a.extensions),a.reserved&&a.reserved.length&&(c.reserved=a.reserved),a.group&&(c.group=!0),a.comment&&(c.comment=a.comment),a.edition&&(c._edition=a.edition),c._defaultEdition="proto3",c},f.prototype.toJSON=function(t){var r=e.prototype.toJSON.call(this,t),s=!!t&&Boolean(t.keepComments);return d.toObject(["edition",this._editionToJSON(),"options",r&&r.options||void 0,"oneofs",e.arrayToJSON(this.oneofsArray,t),"fields",e.arrayToJSON(this.fieldsArray.filter(function(e){return!e.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",r&&r.nested||void 0,"comment",s?this.comment:void 0])},f.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolveAll.call(this);var t=this.oneofsArray;for(s=0;s<t.length;)t[s++].resolve();for(var r=this.fieldsArray,s=0;s<r.length;)r[s++].resolve();return this},f.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.oneofsArray.forEach(e=>{e._resolveFeatures(t)}),this.fieldsArray.forEach(e=>{e._resolveFeatures(t)}),this):this},f.prototype.get=function(e){return this.fields[e]||this.oneofs&&this.oneofs[e]||this.nested&&this.nested[e]||null},f.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof s&&void 0===t.extend){if(this._fieldsById?this._fieldsById[t.id]:this.fieldsById[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name))throw Error("name '"+t.name+"' is reserved in "+this);return t.parent&&t.parent.remove(t),this.fields[t.name]=t,t.message=this,t.onAdd(this),g(this)}return t instanceof r?(this.oneofs||(this.oneofs={}),this.oneofs[t.name]=t,t.onAdd(this),g(this)):e.prototype.add.call(this,t)},f.prototype.remove=function(t){if(t instanceof s&&void 0===t.extend){if(!this.fields||this.fields[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.fields[t.name],t.parent=null,t.onRemove(this),g(this)}if(t instanceof r){if(!this.oneofs||this.oneofs[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),g(this)}return e.prototype.remove.call(this,t)},f.prototype.isReservedId=function(t){return e.isReservedId(this.reserved,t)},f.prototype.isReservedName=function(t){return e.isReservedName(this.reserved,t)},f.prototype.create=function(e){return new this.ctor(e)},f.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this._fieldsArray[r].resolve().resolvedType);this.encode=u(this)({Writer:c,types:t,util:d}),this.decode=l(this)({Reader:a,types:t,util:d}),this.verify=h(this)({types:t,util:d}),this.fromObject=p.fromObject(this)({types:t,util:d}),this.toObject=p.toObject(this)({types:t,util:d});var s=m[e];if(s){var n=Object.create(this);n.fromObject=this.fromObject,this.fromObject=s.fromObject.bind(n),n.toObject=this.toObject,this.toObject=s.toObject.bind(n)}return this},f.prototype.encode=function(e,t){return this.setup().encode(e,t)},f.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},f.prototype.decode=function(e,t){return this.setup().decode(e,t)},f.prototype.decodeDelimited=function(e){return e instanceof a||(e=a.create(e)),this.decode(e,e.uint32())},f.prototype.verify=function(e){return this.setup().verify(e)},f.prototype.fromObject=function(e){return this.setup().fromObject(e)},f.prototype.toObject=function(e,t){return this.setup().toObject(e,t)},f.d=function(e){return function(t){d.decorateType(t,e)}},ac}function Ec(){if(uc)return dc;uc=1,dc=c;var e=Za();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=Nc(),o=Lc(),i=Oc(),a=Uc();function c(t){e.call(this,"",t),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}function d(){}c.fromJSON=function(e,t){return t||(t=new c),e.options&&t.setOptions(e.options),t.addJSON(e.nested).resolveAll()},c.prototype.resolvePath=a.path.resolve,c.prototype.fetch=a.fetch,c.prototype.load=function e(t,n,o){"function"==typeof n&&(o=n,n=void 0);var i=this;if(!o)return a.asPromise(e,i,t,n);var c=o===d;function u(e,t){if(o){if(c)throw e;t&&t.resolveAll();var r=o;o=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in s)return r}return null}function h(e,t){try{if(a.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),a.isString(t)){r.filename=e;var s,o=r(t,i,n),d=0;if(o.imports)for(;d<o.imports.length;++d)(s=l(o.imports[d])||i.resolvePath(e,o.imports[d]))&&p(s);if(o.weakImports)for(d=0;d<o.weakImports.length;++d)(s=l(o.weakImports[d])||i.resolvePath(e,o.weakImports[d]))&&p(s,!0)}else i.setOptions(t.options).addJSON(t.nested)}catch(h){u(h)}c||m||u(null,i)}function p(e,t){if(e=l(e)||e,!(i.files.indexOf(e)>-1))if(i.files.push(e),e in s)c?h(e,s[e]):(++m,setTimeout(function(){--m,h(e,s[e])}));else if(c){var r;try{r=a.fs.readFileSync(e).toString("utf8")}catch(n){return void(t||u(n))}h(e,r)}else++m,i.fetch(e,function(r,s){--m,o&&(r?t?m||u(null,i):u(r):h(e,s))})}var m=0;a.isString(t)&&(t=[t]);for(var f,g=0;g<t.length;++g)(f=i.resolvePath("",t[g]))&&p(f);return c?(i.resolveAll(),i):(m||u(null,i),i)},c.prototype.loadSync=function(e,t){if(!a.isNode)throw Error("not supported");return this.load(e,t,d)},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return e.prototype.resolveAll.call(this)};var u=/^[A-Z]/;function l(e,t){var r=t.parent.lookup(t.extend);if(r){var s=new n(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(s.name)||(s.declaringField=t,t.extensionField=s,r.add(s)),!0}return!1}return c.prototype._handleAdd=function(e){if(e instanceof n)void 0===e.extend||e.extensionField||l(0,e)||this.deferred.push(e);else if(e instanceof o)u.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof i)){if(e instanceof t)for(var r=0;r<this.deferred.length;)l(0,this.deferred[r])?this.deferred.splice(r,1):++r;for(var s=0;s<e.nestedArray.length;++s)this._handleAdd(e._nestedArray[s]);u.test(e.name)&&(e.parent[e.name]=e)}(e instanceof t||e instanceof o||e instanceof n)&&(this._fullyQualifiedObjects[e.fullName]=e)},c.prototype._handleRemove=function(t){if(t instanceof n){if(void 0!==t.extend)if(t.extensionField)t.extensionField.parent.remove(t.extensionField),t.extensionField=null;else{var r=this.deferred.indexOf(t);r>-1&&this.deferred.splice(r,1)}}else if(t instanceof o)u.test(t.name)&&delete t.parent[t.name];else if(t instanceof e){for(var s=0;s<t.nestedArray.length;++s)this._handleRemove(t._nestedArray[s]);u.test(t.name)&&delete t.parent[t.name]}delete this._fullyQualifiedObjects[t.fullName]},c._configure=function(e,n,o){t=e,r=n,s=o},dc}function Uc(){if(lc)return Oa.exports;lc=1;var e,t,r,s,n,o=Oa.exports=fa(),i=Ra();o.codegen=function(){if(Ea)return Ma;function e(t,r){"string"==typeof t&&(r=t,t=void 0);var s=[];function n(t){if("string"!=typeof t){var r=o();if(e.verbose&&console.log("codegen: "+r),r="return "+r,t){for(var i=Object.keys(t),a=new Array(i.length+1),c=new Array(i.length),d=0;d<i.length;)a[d]=i[d],c[d]=t[i[d++]];return a[d]=r,Function.apply(null,a).apply(null,c)}return Function(r)()}for(var u=new Array(arguments.length-1),l=0;l<u.length;)u[l]=arguments[++l];if(l=0,t=t.replace(/%([%dfijs])/g,function(e,t){var r=u[l++];switch(t){case"d":case"f":return String(Number(r));case"i":return String(Math.floor(r));case"j":return JSON.stringify(r);case"s":return String(r)}return"%"}),l!==u.length)throw Error("parameter count mismatch");return s.push(t),n}function o(e){return"function "+(e||r||"")+"("+(t&&t.join(",")||"")+"){\n "+s.join("\n ")+"\n}"}return n.toString=o,n}return Ea=1,Ma=e,e.verbose=!1,Ma}(),o.fetch=function(){if(ka)return Ua;ka=1,Ua=r;var e=zi(),t=Xi()("fs");function r(s,n,o){return"function"==typeof n?(o=n,n={}):n||(n={}),o?!n.xhr&&t&&t.readFile?t.readFile(s,function(e,t){return e&&"undefined"!=typeof XMLHttpRequest?r.xhr(s,n,o):e?o(e):o(null,n.binary?t:t.toString("utf8"))}):r.xhr(s,n,o):e(r,this,s,n)}return r.xhr=function(e,t,r){var s=new XMLHttpRequest;s.onreadystatechange=function(){if(4===s.readyState){if(0!==s.status&&200!==s.status)return r(Error("status "+s.status));if(t.binary){var e=s.response;if(!e){e=[];for(var n=0;n<s.responseText.length;++n)e.push(255&s.responseText.charCodeAt(n))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,s.responseText)}},t.binary&&("overrideMimeType"in s&&s.overrideMimeType("text/plain; charset=x-user-defined"),s.responseType="arraybuffer"),s.open("GET",e),s.send()},Ua}(),o.path=(xa||(xa=1,s=(r=Ja).isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},n=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=s(e),n="";r&&(n=t.shift()+"/");for(var o=0;o<t.length;)".."===t[o]?o>0&&".."!==t[o-1]?t.splice(--o,2):r?t.splice(o,1):++o:"."===t[o]?t.splice(o,1):++o;return n+t.join("/")},r.resolve=function(e,t,r){return r||(t=n(t)),s(t)?t:(r||(e=n(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?n(e+"/"+t):t)}),Ja),o.fs=o.inquire("fs"),o.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),s=0;s<t.length;)r[s]=e[t[s++]];return r}return[]},o.toObject=function(e){for(var t={},r=0;r<e.length;){var s=e[r++],n=e[r++];void 0!==n&&(t[s]=n)}return t};var a=/\\/g,c=/"/g;o.isReserved=function(e){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(e)},o.safeProp=function(e){return!/^[$\w_]+$/.test(e)||o.isReserved(e)?'["'+e.replace(a,"\\\\").replace(c,'\\"')+'"]':"."+e},o.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var d=/_([a-z])/g;o.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(d,function(e,t){return t.toUpperCase()})},o.compareFieldsById=function(e,t){return e.id-t.id},o.decorateType=function(t,r){if(t.$type)return r&&t.$type.name!==r&&(o.decorateRoot.remove(t.$type),t.$type.name=r,o.decorateRoot.add(t.$type)),t.$type;e||(e=Mc());var s=new e(r||t.name);return o.decorateRoot.add(s),s.ctor=t,Object.defineProperty(t,"$type",{value:s,enumerable:!1}),Object.defineProperty(t.prototype,"$type",{value:s,enumerable:!1}),s};var u=0;return o.decorateEnum=function(e){if(e.$type)return e.$type;t||(t=Lc());var r=new t("Enum"+u++,e);return o.decorateRoot.add(r),Object.defineProperty(e,"$type",{value:r,enumerable:!1}),r},o.setProperty=function(e,t,r,s){if("object"!=typeof e)throw TypeError("dst must be an object");if(!t)throw TypeError("path must be specified");return function e(t,r,n){var o=r.shift();if("__proto__"===o||"prototype"===o)return t;if(r.length>0)t[o]=e(t[o]||{},r,n);else{var i=t[o];if(i&&s)return t;i&&(n=[].concat(i).concat(n)),t[o]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(o,"decorateRoot",{get:function(){return i.decorated||(i.decorated=new(Ec()))}}),Oa.exports}function kc(){return hc||(hc=1,function(e){var t=e,r=Uc(),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function n(e,t){var r=0,n={};for(t|=0;r<e.length;)n[s[r+t]]=e[r++];return n}t.basic=n([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),t.defaults=n([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",r.emptyArray,null]),t.long=n([0,0,0,1,1],7),t.mapKey=n([0,0,0,5,5,0,0,0,1,1,0,2],2),t.packed=n([1,5,0,0,0,5,5,0,0,0,1,1,0])}(Na)),Na}function Nc(){if(mc)return pc;mc=1,pc=i;var e=xc();((i.prototype=Object.create(e.prototype)).constructor=i).className="Field";var t,r=Lc(),s=kc(),n=Uc(),o=/^required|optional|repeated$/;function i(t,r,i,a,c,d,u){if(n.isObject(a)?(u=c,d=a,a=c=void 0):n.isObject(c)&&(u=d,d=c,c=void 0),e.call(this,t,d),!n.isInteger(r)||r<0)throw TypeError("id must be a non-negative integer");if(!n.isString(i))throw TypeError("type must be a string");if(void 0!==a&&!o.test(a=a.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==c&&!n.isString(c))throw TypeError("extend must be a string");"proto3_optional"===a&&(a="optional"),this.rule=a&&"optional"!==a?a:void 0,this.type=i,this.id=r,this.extend=c||void 0,this.repeated="repeated"===a,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!n.Long&&void 0!==s.long[i],this.bytes="bytes"===i,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=u}return i.fromJSON=function(e,t){var r=new i(e,t.id,t.type,t.rule,t.extend,t.options,t.comment);return t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},Object.defineProperty(i.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this._features.field_presence}}),Object.defineProperty(i.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(i.prototype,"delimited",{get:function(){return this.resolvedType instanceof t&&"DELIMITED"===this._features.message_encoding}}),Object.defineProperty(i.prototype,"packed",{get:function(){return"PACKED"===this._features.repeated_field_encoding}}),Object.defineProperty(i.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this._features.field_presence)}}),i.prototype.setOption=function(t,r,s){return e.prototype.setOption.call(this,t,r,s)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return n.toObject(["edition",this._editionToJSON(),"rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},i.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=s.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof t?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof r&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof r||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=n.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var o;n.base64.test(this.typeDefault)?n.base64.decode(this.typeDefault,o=n.newBuffer(n.base64.length(this.typeDefault)),0):n.utf8.write(this.typeDefault,o=n.newBuffer(n.utf8.length(this.typeDefault)),0),this.typeDefault=o}return this.map?this.defaultValue=n.emptyObject:this.repeated?this.defaultValue=n.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof t&&(this.parent.ctor.prototype[this.name]=this.defaultValue),e.prototype.resolve.call(this)},i.prototype._inferLegacyProtoFeatures=function(e){if("proto2"!==e&&"proto3"!==e)return{};var r={};if("required"===this.rule&&(r.field_presence="LEGACY_REQUIRED"),this.parent&&void 0===s.defaults[this.type]){var n=this.parent.get(this.type.split(".").pop());n&&n instanceof t&&n.group&&(r.message_encoding="DELIMITED")}return!0===this.getOption("packed")?r.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(r.repeated_field_encoding="EXPANDED"),r},i.prototype._resolveFeatures=function(t){return e.prototype._resolveFeatures.call(this,this._edition||t)},i.d=function(e,t,r,s){return"function"==typeof t?t=n.decorateType(t).name:t&&"object"==typeof t&&(t=n.decorateEnum(t).name),function(o,a){n.decorateType(o.constructor).add(new i(a,e,t,r,{default:s}))}},i._configure=function(e){t=e},pc}function Oc(){if(gc)return fc;gc=1,fc=s;var e=xc();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=Nc(),r=Uc();function s(t,r,s,n){if(Array.isArray(r)||(s=r,r=void 0),e.call(this,t,s),void 0!==r&&!Array.isArray(r))throw TypeError("fieldNames must be an Array");this.oneof=r||[],this.fieldsArray=[],this.comment=n}function n(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}return s.fromJSON=function(e,t){return new s(e,t.oneof,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},s.prototype.add=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),e.partOf=this,n(this),this},s.prototype.remove=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");var r=this.fieldsArray.indexOf(e);if(r<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(r,1),(r=this.oneof.indexOf(e.name))>-1&&this.oneof.splice(r,1),e.partOf=null,this},s.prototype.onAdd=function(t){e.prototype.onAdd.call(this,t);for(var r=0;r<this.oneof.length;++r){var s=t.get(this.oneof[r]);s&&!s.partOf&&(s.partOf=this,this.fieldsArray.push(s))}n(this)},s.prototype.onRemove=function(t){for(var r,s=0;s<this.fieldsArray.length;++s)(r=this.fieldsArray[s]).parent&&r.parent.remove(r);e.prototype.onRemove.call(this,t)},Object.defineProperty(s.prototype,"isProto3Optional",{get:function(){if(null==this.fieldsArray||1!==this.fieldsArray.length)return!1;var e=this.fieldsArray[0];return null!=e.options&&!0===e.options.proto3_optional}}),s.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,n){r.decorateType(t.constructor).add(new s(n,e)),Object.defineProperty(t,n,{get:r.oneOfGetter(e),set:r.oneOfSetter(e)})}},fc}function xc(){if(vc)return yc;vc=1,yc=i,i.className="ReflectionObject";const e=Oc();var t,r=Uc(),s={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},n={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},o={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function i(e,t){if(!r.isString(e))throw TypeError("name must be a string");if(t&&!r.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}return Object.defineProperties(i.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),i.prototype.toJSON=function(){throw Error()},i.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var r=e.root;r instanceof t&&r._handleAdd(this)},i.prototype.onRemove=function(e){var r=e.root;r instanceof t&&r._handleRemove(this),this.parent=null,this.resolved=!1},i.prototype.resolve=function(){return this.resolved||this.root instanceof t&&(this.resolved=!0),this},i.prototype._resolveFeaturesRecursive=function(e){return this._resolveFeatures(this._edition||e)},i.prototype._resolveFeatures=function(t){if(!this._featuresResolved){var r={};if(!t)throw new Error("Unknown edition for "+this.fullName);var i=Object.assign(this.options?Object.assign({},this.options.features):{},this._inferLegacyProtoFeatures(t));if(this._edition){if("proto2"===t)r=Object.assign({},n);else if("proto3"===t)r=Object.assign({},o);else{if("2023"!==t)throw new Error("Unknown edition: "+t);r=Object.assign({},s)}return this._features=Object.assign(r,i||{}),void(this._featuresResolved=!0)}if(this.partOf instanceof e){var a=Object.assign({},this.partOf._features);this._features=Object.assign(a,i||{})}else if(this.declaringField);else{if(!this.parent)throw new Error("Unable to find a parent for "+this.fullName);var c=Object.assign({},this.parent._features);this._features=Object.assign(c,i||{})}this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},i.prototype._inferLegacyProtoFeatures=function(){return{}},i.prototype.getOption=function(e){if(this.options)return this.options[e]},i.prototype.setOption=function(e,t,s){return this.options||(this.options={}),/^features\./.test(e)?r.setProperty(this.options,e,t,s):s&&void 0!==this.options[e]||(this.getOption(e)!==t&&(this.resolved=!1),this.options[e]=t),this},i.prototype.setParsedOption=function(e,t,s){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(s){var o=n.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)});if(o){var i=o[e];r.setProperty(i,s,t)}else(o={})[e]=r.setProperty({},s,t),n.push(o)}else{var a={};a[e]=t,n.push(a)}return this},i.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),s=0;s<r.length;++s)this.setOption(r[s],e[r[s]],t);return this},i.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},i.prototype._editionToJSON=function(){if(this._edition&&"proto3"!==this._edition)return this._edition},i._configure=function(e){t=e},yc}function Lc(){if(Ic)return bc;Ic=1,bc=s;var e=xc();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=Za(),r=Uc();function s(t,r,s,n,o,i){if(e.call(this,t,s),r&&"object"!=typeof r)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=n,this.comments=o||{},this.valuesOptions=i,this._valuesFeatures={},this.reserved=void 0,r)for(var a=Object.keys(r),c=0;c<a.length;++c)"number"==typeof r[a[c]]&&(this.valuesById[this.values[a[c]]=r[a[c]]]=a[c])}return s.prototype._resolveFeatures=function(t){return t=this._edition||t,e.prototype._resolveFeatures.call(this,t),Object.keys(this.values).forEach(e=>{var t=Object.assign({},this._features);this._valuesFeatures[e]=Object.assign(t,this.valuesOptions&&this.valuesOptions[e]&&this.valuesOptions[e].features)}),this},s.fromJSON=function(e,t){var r=new s(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},s.prototype.add=function(e,t,s,n){if(!r.isString(e))throw TypeError("name must be a string");if(!r.isInteger(t))throw TypeError("id must be an integer");if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=s||null,this},s.prototype.remove=function(e){if(!r.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},s.prototype.isReservedId=function(e){return t.isReservedId(this.reserved,e)},s.prototype.isReservedName=function(e){return t.isReservedName(this.reserved,e)},bc}function Pc(){if(Cc)return wc;Cc=1,wc=function(n){for(var o,i=r.codegen(["m","w"],n.name+"$encode")("if(!w)")("w=Writer.create()"),a=n.fieldsArray.slice().sort(r.compareFieldsById),c=0;c<a.length;++c){var d=a[c].resolve(),u=n._fieldsArray.indexOf(d),l=d.resolvedType instanceof e?"int32":d.type,h=t.basic[l];o="m"+r.safeProp(d.name),d.map?(i("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",o,d.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",o)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(d.id<<3|2)>>>0,8|t.mapKey[d.keyType],d.keyType),void 0===h?i("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,o):i(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|h,l,o),i("}")("}")):d.repeated?(i("if(%s!=null&&%s.length){",o,o),d.packed&&void 0!==t.packed[l]?i("w.uint32(%i).fork()",(d.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",o)("w.%s(%s[i])",l,o)("w.ldelim()"):(i("for(var i=0;i<%s.length;++i)",o),void 0===h?s(i,d,u,o+"[i]"):i("w.uint32(%i).%s(%s[i])",(d.id<<3|h)>>>0,l,o)),i("}")):(d.optional&&i("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",o,d.name),void 0===h?s(i,d,u,o):i("w.uint32(%i).%s(%s)",(d.id<<3|h)>>>0,l,o))}return i("return w")};var e=Lc(),t=kc(),r=Uc();function s(e,t,r,s){return t.delimited?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,s,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,s,(t.id<<3|2)>>>0)}return wc}var Dc=_c?Tc:(_c=1,Tc=function(){if(Sc)return Bi.exports;Sc=1;var e=Bi.exports=Aa();return e.build="light",e.load=function(t,r,s){return"function"==typeof r?(s=r,r=new e.Root):r||(r=new e.Root),r.load(t,s)},e.loadSync=function(t,r){return r||(r=new e.Root),r.loadSync(t)},e.encoder=Pc(),e.decoder=tc(),e.verifier=rc(),e.converter=oc(),e.ReflectionObject=xc(),e.Namespace=Za(),e.Root=Ec(),e.Enum=Lc(),e.Type=Mc(),e.Field=Nc(),e.OneOf=Oc(),e.MapField=Qa(),e.Service=Xa(),e.Method=Ya(),e.Message=ec(),e.wrappers=Ac(),e.types=kc(),e.util=Uc(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),Bi.exports}());const $c={nested:{easemob:{nested:{pb:{nested:{MessageBody:{fields:{type:{type:"Type",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},contents:{rule:"repeated",type:"Content",id:4},ext:{rule:"repeated",type:"KeyValue",id:5},ackMessageId:{type:"uint64",id:6},msgConfig:{type:"MessageConfig",id:7},ackContent:{type:"string",id:8},meta:{type:"string",id:9},editMessageId:{type:"uint64",id:11},editScope:{type:"EditScope",id:12},stream:{type:"Stream",id:13},userInfoUpdateTime:{type:"int32",id:14},namecardUpdateTime:{type:"int32",id:15},sendToPeer:{type:"bool",id:16},ackMessageIds:{rule:"repeated",type:"uint64",id:17},clearAllUnreadMessageCount:{type:"bool",id:18}},nested:{Content:{fields:{type:{type:"Type",id:1},text:{type:"string",id:2},latitude:{type:"double",id:3},longitude:{type:"double",id:4},address:{type:"string",id:5},displayName:{type:"string",id:6},remotePath:{type:"string",id:7},secretKey:{type:"string",id:8},fileLength:{type:"int32",id:9},action:{type:"string",id:10},params:{rule:"repeated",type:"KeyValue",id:11},duration:{type:"int32",id:12},size:{type:"Size",id:13},thumbnailRemotePath:{type:"string",id:14},thumbnailSecretKey:{type:"string",id:15},thumbnailDisplayName:{type:"string",id:16},thumbnailFileLength:{type:"int32",id:17},thumbnailSize:{type:"Size",id:18},customEvent:{type:"string",id:19},customExts:{rule:"repeated",type:"KeyValue",id:20},buildingName:{type:"string",id:21},subType:{type:"SubType",id:22},title:{type:"string",id:23},summary:{type:"string",id:24},combineLevel:{type:"int32",id:25},imageType:{type:"int32",id:26}},nested:{Type:{values:{TEXT:0,IMAGE:1,VIDEO:2,LOCATION:3,VOICE:4,FILE:5,COMMAND:6,CUSTOM:7,COMBINE:8}},Size:{fields:{width:{type:"double",id:1},height:{type:"double",id:2}}},SubType:{values:{COMBINE:0,GIF:1,SUB_STREAM:10}}}},Type:{values:{NORMAL:0,CHAT:1,GROUPCHAT:2,CHATROOM:3,READ_ACK:4,DELIVER_ACK:5,RECALL:6,CHANNEL_ACK:7,EDIT:8}},EditScope:{values:{BODY:1,BODY_AND_EXT:2}},MessageConfig:{fields:{allowGroupAck:{type:"bool",id:1}}},Stream:{fields:{streamType:{type:"string",id:1},streamSeq:{type:"uint64",id:2},streamStatus:{type:"StreamStatus",id:3},streamError:{type:"uint32",id:4},streamFinishReason:{type:"int32",id:5}},nested:{StreamStatus:{values:{STREAM_START:0,STREAM_START_COMPLETED:1,STREAM_IN_PROGRESS:2,STREAM_COMPLETED:3,STREAM_FULL:4}}}}}},KeyValue:{oneofs:{value:{oneof:["varintValue","floatValue","doubleValue","stringValue"]}},fields:{key:{type:"string",id:1},type:{type:"ValueType",id:2},varintValue:{type:"int64",id:3},floatValue:{type:"float",id:4},doubleValue:{type:"double",id:5},stringValue:{type:"string",id:6}},nested:{ValueType:{values:{BOOL:1,INT:2,UINT:3,LLINT:4,FLOAT:5,DOUBLE:6,STRING:7,JSON_STRING:8}}}},JID:{fields:{appKey:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},clientResource:{type:"string",id:4}}},ConferenceBody:{fields:{sessionId:{type:"string",id:1},operation:{type:"Operation",id:2},conferenceId:{type:"string",id:3},type:{type:"Type",id:4},content:{type:"string",id:5},network:{type:"string",id:6},version:{type:"string",id:7},identity:{type:"Identity",id:8},duration:{type:"string",id:9},peerName:{type:"string",id:10},endReason:{type:"EndReason",id:11},status:{type:"Status",id:12},isDirect:{type:"bool",id:13},controlType:{type:"StreamControlType",id:14},routeFlag:{type:"int32",id:15},routeKey:{type:"string",id:16}},nested:{Status:{fields:{errorCode:{type:"int32",id:1}}},Operation:{values:{JOIN:0,INITIATE:1,ACCEPT_INITIATE:2,ANSWER:3,TERMINATE:4,REMOVE:5,STREAM_CONTROL:6,MEDIA_REQUEST:7}},Type:{values:{VOICE:0,VIDEO:1}},Identity:{values:{CALLER:0,CALLEE:1}},EndReason:{values:{HANGUP:0,NORESPONSE:1,REJECT:2,BUSY:3,FAIL:4,UNSUPPORTED:5,OFFLINE:6}},StreamControlType:{values:{PAUSE_VOICE:0,RESUME_VOICE:1,PAUSE_VIDEO:2,RESUME_VIDEO:3}}}},MSync:{fields:{version:{type:"Version",id:1,options:{default:"MSYNC_V1"}},guid:{type:"JID",id:2},auth:{type:"string",id:3},compressAlgorimth:{type:"uint32",id:4},crypto:{type:"uint32",id:5},userAgent:{type:"string",id:6},pov:{type:"uint64",id:7},command:{type:"Command",id:8},deviceId:{type:"uint32",id:10},encryptType:{rule:"repeated",type:"EncryptType",id:11,options:{packed:!1}},encryptKey:{type:"string",id:12},payload:{type:"bytes",id:9},traceId:{type:"uint64",id:20}},nested:{Version:{values:{MSYNC_V1:0,MSYNC_V2:1}},Command:{values:{SYNC:0,UNREAD:1,NOTICE:2,PROVISION:3,LOGOUT:4}}}},EncryptType:{values:{ENCRYPT_NONE:0,ENCRYPT_AES_128_CBC:1,ENCRYPT_AES_256_CBC:2}},CommSyncUL:{fields:{meta:{type:"Meta",id:1},key:{type:"uint64",id:2},queue:{type:"JID",id:3},isRoam:{type:"bool",id:4},lastFullRoamKey:{type:"uint64",id:5}}},CommSyncDL:{fields:{status:{type:"Status",id:1},metaId:{type:"uint64",id:2},serverId:{type:"uint64",id:3},metas:{rule:"repeated",type:"Meta",id:4},nextKey:{type:"uint64",id:5},queue:{type:"JID",id:6},isLast:{type:"bool",id:7},timestamp:{type:"uint64",id:8},isRoam:{type:"bool",id:9}}},CommNotice:{fields:{queue:{type:"JID",id:1}}},CommUnreadUL:{fields:{}},CommUnreadDL:{fields:{status:{type:"Status",id:1},unread:{rule:"repeated",type:"MetaQueue",id:2},timestamp:{type:"uint64",id:3}}},MetaQueue:{fields:{queue:{type:"JID",id:1},n:{type:"uint32",id:2}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},timestamp:{type:"uint64",id:4},ns:{type:"NameSpace",id:5},payload:{type:"bytes",id:6},routetype:{type:"RouteType",id:7},ext:{rule:"repeated",type:"KeyValue",id:8},meta:{type:"bytes",id:9},directedUsers:{rule:"repeated",type:"string",id:10},env:{type:"string",id:13}},nested:{NameSpace:{values:{STATISTIC:0,CHAT:1,MUC:2,ROSTER:3,CONFERENCE:4,NOTIFY:5,QUERY:6}},RouteType:{values:{ROUTE_ALL:0,ROUTE_ONLINE:1,ROUTE_DIRECT:2}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},reason:{type:"string",id:2},redirectInfo:{rule:"repeated",type:"RedirectInfo",id:3}},nested:{ErrorCode:{values:{OK:0,FAIL:1,UNAUTHORIZED:2,MISSING_PARAMETER:3,WRONG_PARAMETER:4,REDIRECT:5,TOKEN_EXPIRED:6,PERMISSION_DENIED:7,NO_ROUTE:8,UNKNOWN_COMMAND:9,PB_PARSER_ERROR:10,BIND_ANOTHER_DEVICE:11,IM_FORBIDDEN:12,TOO_MANY_DEVICES:13,PLATFORM_LIMIT:14,USER_MUTED:15,ENCRYPT_DISABLE:16,ENCRYPT_ENABLE:17,DECRYPT_FAILURE:18,PERMISSION_DENIED_EXTERNAL:19}}}},RedirectInfo:{fields:{host:{type:"string",id:1},port:{type:"uint32",id:2}}},Provision:{fields:{osType:{type:"OsType",id:1},version:{type:"string",id:2},networkType:{type:"NetworkType",id:3},appSign:{type:"string",id:4},compressType:{rule:"repeated",type:"CompressType",id:5,options:{packed:!1}},encryptType:{rule:"repeated",type:"EncryptType",id:6,options:{packed:!1}},encryptKey:{type:"string",id:7},status:{type:"Status",id:8},deviceUuid:{type:"string",id:9},isManualLogin:{type:"bool",id:10},password:{type:"string",id:11},deviceName:{type:"string",id:12},resource:{type:"string",id:13},auth:{type:"string",id:14},serviceId:{type:"string",id:16},actionVersion:{type:"string",id:17},authToken:{type:"string",id:18},osCustomValue:{type:"uint32",id:19},sessionId:{type:"string",id:20},reason:{type:"string",id:21},protocolCompressType:{rule:"repeated",type:"CompressType",id:22},protocolCompressDirection:{type:"CompressDirection",id:23}},nested:{OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}},CompressType:{values:{COMPRESS_NONE:0,COMPRESS_ZLIB:1,COMPRESS_LZ4:2}},CompressDirection:{values:{ONLY_UP:0,ONLY_DOWN:1,BI:2}}}},Logout:{fields:{sessionId:{type:"string",id:1},reason:{type:"string",id:2},status:{type:"Status",id:3}}},MUCBody:{fields:{mucId:{type:"JID",id:1},operation:{type:"Operation",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},setting:{type:"Setting",id:5},reason:{type:"string",id:6},isChatroom:{type:"bool",id:7},status:{type:"Status",id:8},isThread:{type:"bool",id:9},mucParentId:{type:"JID",id:10},mucName:{type:"string",id:11},eventInfo:{type:"EventInfo",id:12},mucMemberCount:{type:"int32",id:13},ext:{type:"string",id:14},leaveOtherRooms:{type:"bool",id:15},members:{rule:"repeated",type:"string",id:16}},nested:{Operation:{values:{CREATE:0,DESTROY:1,JOIN:2,LEAVE:3,APPLY:4,APPLY_ACCEPT:5,APPLY_DECLINE:6,INVITE:7,INVITE_ACCEPT:8,INVITE_DECLINE:9,KICK:10,GET_BLACKLIST:11,BAN:12,ALLOW:13,UPDATE:14,BLOCK:15,UNBLOCK:16,PRESENCE:17,ABSENCE:18,DIRECT_JOINED:19,ASSIGN_OWNER:20,ADD_ADMIN:21,REMOVE_ADMIN:22,ADD_MUTE:23,REMOVE_MUTE:24,UPDATE_ANNOUNCEMENT:25,DELETE_ANNOUNCEMENT:26,UPLOAD_FILE:27,DELETE_FILE:28,ADD_USER_WHITE_LIST:29,REMOVE_USER_WHITE_LIST:30,BAN_GROUP:31,REMOVE_BAN_GROUP:32,THREAD_CREATE:33,THREAD_DESTROY:34,THREAD_JOIN:35,THREAD_LEAVE:36,THREAD_KICK:37,THREAD_UPDATE:38,THREAD_PRESENCE:39,THREAD_ABSENCE:40,DISABLE_GROUP:41,ABLE_GROUP:42,SET_METADATA:43,DELETE_METADATA:44,GROUP_MEMBER_METADATA_UPDATE:45}},Setting:{fields:{name:{type:"string",id:1},desc:{type:"string",id:2},type:{type:"Type",id:3},maxUsers:{type:"int32",id:4},owner:{type:"string",id:5}},nested:{Type:{values:{PRIVATE_OWNER_INVITE:0,PRIVATE_MEMBER_INVITE:1,PUBLIC_JOIN_APPROVAL:2,PUBLIC_JOIN_OPEN:3,PUBLIC_ANONYMOUS:4}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2},chatroomInfo:{type:"string",id:3}},nested:{ErrorCode:{values:{OK:0,PERMISSION_DENIED:1,WRONG_PARAMETER:2,MUC_NOT_EXIST:3,USER_NOT_EXIST:4,UNKNOWN:5}}}},EventInfo:{fields:{eventType:{type:"EventType",id:1,options:{default:"EVENT_NONE"}},ext:{type:"string",id:2}},nested:{EventType:{values:{EVENT_NONE:0,CIRCLE_CHANNEL:1}}}}}},RosterBody:{fields:{operation:{type:"Operation",id:1},status:{type:"Status",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},reason:{type:"string",id:5},rosterVer:{type:"string",id:6},biDirection:{type:"bool",id:7}},nested:{Operation:{values:{GET_ROSTER:0,GET_BLACKLIST:1,ADD:2,REMOVE:3,ACCEPT:4,DECLINE:5,BAN:6,ALLOW:7,REMOTE_ACCEPT:8,REMOTE_DECLINE:9}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2}},nested:{ErrorCode:{values:{OK:0,USER_NOT_EXIST:1,USER_ALREADY_FRIEND:2,USER_ALREADY_BLACKLIST:3}}}}}},StatisticsBody:{fields:{operation:{type:"Operation",id:1},os:{type:"OsType",id:2},version:{type:"string",id:3},network:{type:"NetworkType",id:4},imTime:{type:"uint32",id:5},chatTime:{type:"uint32",id:6},location:{type:"string",id:7},reason:{type:"string",id:10}},nested:{Operation:{values:{INFORMATION:0,USER_REMOVED:1,USER_LOGIN_ANOTHER_DEVICE:2,USER_KICKED_BY_CHANGE_PASSWORD:3,USER_KICKED_BY_OTHER_DEVICE:4}},OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}}}}}}}}}},qc=e=>{if(!e||0===e.trim().length)throw Fo("Proto type name is required.",{code:Bo,stage:xo,retryable:!1,details:{typeName:e}})};class Gc{constructor(){this.codecMap=new Map}register(e,t){qc(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:r=>{const s=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw Fo("Proto payload must be an object.",{code:Bo,stage:xo,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(r,e),n=t.fromObject(s);return t.encode(n).finish()},decode:e=>{const r=t.decode(e);return t.toObject(r,{longs:String,enums:Number,defaults:!1})}})}get(e){return qc(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Fo("Proto codec not found.",{code:Bo,stage:xo,retryable:!1,details:{typeName:e}})}}const Bc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Fc=e=>{class t extends Dc.Message{constructor(e){super(),((e,t)=>{if(t)for(const r of Object.keys(t)){const s=t[r];null!=s&&(e[r]=s)}})(this,e)}}const r=t;return r.$type=e,r.prototype.$type=e,r},jc=e=>mi.isLong(e),zc=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,Kc=e=>Object.prototype.hasOwnProperty.call(Dc.types.packed,e),Hc=e=>{const t=e.resolve();return t.resolvedType instanceof Dc.Enum||Kc(t.type)},Vc=(e,t)=>t in e?e[t]:void 0,Wc=e=>{const t=e.resolve();return t.resolvedType instanceof Dc.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(Dc.types.basic,r)?Dc.types.basic[t.type]:2);var r},Jc=(e,t)=>jc(e)||"number"==typeof e||"string"==typeof e?e:Bc(e)&&"number"==typeof e.low&&"number"==typeof e.high?new mi(e.low,e.high,t):t?mi.UZERO:mi.ZERO,Zc=(e,t,r)=>{switch(t){case"double":return e.double(Number(r));case"float":return e.float(Number(r));case"int32":return e.int32(Number(r));case"uint32":return e.uint32(Number(r));case"sint32":return e.sint32(Number(r));case"fixed32":return e.fixed32(Number(r));case"sfixed32":return e.sfixed32(Number(r));case"int64":return e.int64(Jc(r,!1));case"uint64":return e.uint64(Jc(r,!0));case"sint64":return e.sint64(Jc(r,!1));case"fixed64":return e.fixed64(Jc(r,!0));case"sfixed64":return e.sfixed64(Jc(r,!1));case"bool":return e.bool(Boolean(r));case"string":return e.string(String(r));case"bytes":return e.bytes((e=>"string"==typeof e?e:zc(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array)(r));default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}},Qc=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},Yc=(e,t)=>{const r=e.uint32();return Qc(e,r,t),r},Xc=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return Qc(e,8,r),void e.skip(8);case 2:{const t=Yc(e,r);return void e.skip(t)}case 5:return Qc(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},ed=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof Dc.Type){const t=e.fork();return rd(n,Bc(r)?r:{},t),t.ldelim(),e}return n instanceof Dc.Enum?(e.int32("number"==typeof r?r:Number(r)),e):Zc(e,s.type,r)},td=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(Kc(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)ed(e,t,s);return e.ldelim(),e}const n=Wc(t);for(const o of r)e.uint32(t.id<<3|n),ed(e,t,o);return e},rd=(e,t,r=Dc.Writer.create())=>{const s=e.fieldsArray.slice().sort(Dc.util.compareFieldsById);for(const n of s){const e=Vc(t,n.name);null!=e&&(n.repeated?td(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|Wc(n)),ed(r,n,e)))}return r},sd=(e,t,r,s)=>{const n=t.resolve(),o=n.resolvedType;return o instanceof Dc.Type?2!==r?void Xc(e,r,s):nd(o,e,Yc(e,s)):o instanceof Dc.Enum?e.int32():((e,t)=>{switch(t){case"double":return e.double();case"float":return e.float();case"int32":return e.int32();case"uint32":return e.uint32();case"sint32":return e.sint32();case"fixed32":return e.fixed32();case"sfixed32":return e.sfixed32();case"int64":return e.int64();case"uint64":return e.uint64();case"sint64":return e.sint64();case"fixed64":return e.fixed64();case"sfixed64":return e.sfixed64();case"bool":return e.bool();case"string":return e.string();case"bytes":return e.bytes();default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}})(e,n.type)},nd=(e,t,r)=>{const s=t instanceof Dc.Reader?t:Dc.Reader.create(t),n=void 0===r?s.len:s.pos+r,o=(e=>{const t={};for(const r of e.fieldsArray)r.repeated&&(t[r.name]=[]);return t})(e),i=e.fieldsById;for(;s.pos<n;){const t=s.pos,r=s.uint32(),c=i[r>>>3],d=7&r;try{if(!c){Xc(s,d,n);continue}if(c.repeated){const e=Array.isArray(o[c.name])?o[c.name]:[];if(Hc(c)&&2===d){const t=Yc(s,n)+s.pos;for(;s.pos<t;)e.push(sd(s,c,0,t))}else{const t=sd(s,c,d,n);void 0!==t&&e.push(t)}o[c.name]=e;continue}const e=sd(s,c,d,n);void 0!==e&&(o[c.name]=e)}catch(a){if(a instanceof RangeError){const o=c?`${c.name}#${c.id}`:`unknown#${r>>>3}`;throw new RangeError(`${a.message}; protobufType=${e.fullName}; field=${o}; tag=${r}; wireType=${d}; tagPosition=${t}; readerPosition=${s.pos}; messageEnd=${n}`)}throw a}}return o},od=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,id=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof Dc.Type)return null;if(r.resolvedType instanceof Dc.Enum){if(t?.enums===String){return r.resolvedType.valuesById[r.typeDefault]??r.typeDefault}return r.typeDefault}return"bytes"===r.type?t?.bytes===String?"":t?.bytes===Array?[]:new Uint8Array:r.long&&jc(r.typeDefault)?od(r.typeDefault,t):r.typeDefault},ad=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof Dc.Type?Bc(t)?cd(s.resolvedType,t,r):t:s.resolvedType instanceof Dc.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&jc(t)?od(t,r):"bytes"===s.type&&zc(t)?((e,t)=>t?.bytes===String?Dc.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},cd=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(Dc.util.compareFieldsById)){const e=Vc(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>ad(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=id(n,r)):s[n.name]=ad(n,e,r)}return s},ud=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>rd(e,Bc(t)?t:{},r),e.decode=(t,r)=>nd(e,t,r),e.fromObject=e=>Bc(e)?e:{},e.toObject=(t,r)=>cd(e,Bc(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},ld=e=>{ud(e);for(const t of e.nestedArray)if(t instanceof Dc.Type)ld(t);else if(t instanceof Dc.Namespace)for(const e of t.nestedArray)e instanceof Dc.Type&&ld(e)},hd=e=>{for(const t of e.nestedArray)t instanceof Dc.Type?ld(t):t instanceof Dc.Namespace&&hd(t)},pd=()=>{const e=Dc.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>Fc(e),Dc.Type.prototype.setup=function(){return ud(this),this},Dc.Type.prototype.create=function(e){return e?{...e}:{}},Dc.Type.prototype.encode=function(e,t){return rd(this,Bc(e)?e:{},t)},Dc.Type.prototype.decode=function(e,t){return nd(this,e,t)},Dc.Type.prototype.fromObject=function(e){return Bc(e)?e:{}},Dc.Type.prototype.toObject=function(e,t){return cd(this,Bc(e)?e:{},t)},Dc.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let md=!1,fd=null,gd=null,yd=null;const vd=e=>e.startsWith(".")?e.slice(1):e,bd=e=>e instanceof Dc.Namespace,Id=e=>e instanceof Dc.Type,wd=e=>{for(const t of e.nestedArray)Id(t)?ld(t):bd(t)&&wd(t)},Cd=()=>{md||(Dc.util.Long=mi,Dc.configure(),md=!0),pd();const e=Dc.Root.fromJSON($c);return wd(e),e},Sd=(e,t)=>{const r=e.nestedArray;for(const s of r){if(Id(s)){const e=vd(s.fullName);ld(s),t.registerType(e,s);continue}bd(s)&&Sd(s,t)}},Td=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return Fo(`Static proto ${r} failed.`,{code:Bo,stage:xo,retryable:!1,details:{typeName:e,operation:r,cause:s}})},_d=()=>fd||(fd=Cd(),fd),Rd=()=>{if(yd)return yd;const e=(()=>{if(gd)return gd;const e=new Gc,t=_d();return Sd(t,e),gd=e,e})();return yd={encode(t,r){try{return e.getOrThrow(vd(t)).encode(r)}catch(s){throw Td(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(vd(t)).decode(r)}catch(s){throw Td(t,s,"decode")}}},yd},Ad=e=>{const t={};if("function"==typeof e.forEach)return e.forEach((e,r)=>{t[r]=e}),t;const r=e.get?.("content-type");return r&&(t["content-type"]=r),t},Md=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(r){const s=r.method??"GET",n={...r.headers??{}},o=new AbortController,i=r.timeoutMs??e?.timeoutMs??15e3,a=setTimeout(()=>{o.abort()},i),c=((e,t,r)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==r)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(r,n,s);try{const e=await t(r.url,{method:s,headers:n,body:c,signal:r.signal??o.signal});let i;if("arraybuffer"===r.responseType)i=await e.arrayBuffer();else if("text"===r.responseType)i=await e.text();else{const t=e.headers.get("content-type")??"",r=await e.text();i=t.includes("application/json")&&r?JSON.parse(r):r}return{status:e.status,headers:Ad(e.headers),data:i}}catch(d){throw Fo("Request adapter execution failed.",{code:$o,stage:ko,retryable:!0,details:{url:r.url,method:s,cause:d instanceof Error?d.message:String(d)}})}finally{clearTimeout(a)}}}},Ed=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Ud=e=>"function"==typeof e.on&&"function"==typeof e.off,kd=(e,t,r)=>{if(Ed(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(Ud(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw Fo("Socket event listener API is unsupported.",{code:Go,stage:Oo,retryable:!1,details:{event:t}})},Nd=(e,t,r)=>{if(Ed(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(Ud(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=kd(e,t,(...e)=>{n(),r(...e)}),n}throw Fo("Socket one-time listener API is unsupported.",{code:Go,stage:Oo,retryable:!1,details:{event:t}})},Od=e=>{return"string"==typeof e||(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))||"undefined"!=typeof Blob&&e instanceof Blob?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e&&"object"==typeof e&&"data"in e?Od(e.data):null;var t},xd=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return kd(e,"open",()=>{t.forEach(e=>{e()})}),kd(e,"message",(...e)=>{const t=Od(e[0]);null!==t&&r.forEach(e=>{e(t)})}),kd(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),kd(e,"close",(...e)=>{const t=(e=>{const[t,r]=e;if(t&&"object"==typeof t){const e=t;return{code:"number"==typeof e.code?e.code:void 0,reason:"string"==typeof e.reason?e.reason:void 0}}return{code:"number"==typeof t?t:void 0,reason:"string"==typeof r?r:ArrayBuffer.isView(r)?(new TextDecoder).decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)):void 0}})(e);n.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==zo)throw Fo("Socket is not open.",{code:Go,stage:Oo,retryable:!0,details:{readyState:e.readyState}});return e.send(t),Promise.resolve()},close(t,r){e.close(t,r)},onOpen:e=>(t.add(e),()=>{t.delete(e)}),onMessage:e=>(r.add(e),()=>{r.delete(e)}),onError:e=>(s.add(e),()=>{s.delete(e)}),onClose:e=>(n.add(e),()=>{n.delete(e)})}},Ld=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((r,s)=>{let n;try{n=new t(e.url,e.protocols);try{n.binaryType="arraybuffer"}catch{}}catch(l){return void s(Fo("Socket creation failed.",{code:Go,stage:Oo,retryable:!0,details:{cause:l instanceof Error?l.message:String(l)}}))}let o,i=()=>{},a=()=>{},c=!1;const d=()=>{void 0!==o&&(clearTimeout(o),o=void 0)},u=()=>{c||(c=!0,i(),a(),d(),n.close(),s(Fo("Socket connection timed out.",{code:Go,stage:Oo,retryable:!0,details:{url:e.url,reason:"timeout"}})))};i=Nd(n,"open",()=>{c||(c=!0,i(),a(),d(),r(xd(n)))}),a=Nd(n,"error",e=>{if(c)return;c=!0,i(),a(),d();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;s(Fo("Socket connection failed before open.",{code:Go,stage:Oo,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(o=setTimeout(u,e.timeoutMs))})}},Pd=(e,t)=>{throw Fo("Upload adapter execution failed.",{code:qo,stage:No,retryable:"abort"!==e,details:{reason:e,url:t.url}})},Dd=e=>{const t=new FormData;return Object.entries(e.fields??{}).forEach(([e,r])=>{t.append(e,r)}),((e,t)=>{if("web-file"!==t.source.sourceType)throw Fo("Web upload adapter only supports web-file source.",{code:qo,stage:No,retryable:!1,details:{sourceType:t.source.sourceType}});const r=t.source.file;if(!r)throw Fo("Upload source file is required for web-file uploads.",{code:qo,stage:No,retryable:!1,details:{sourceType:t.source.sourceType}});const s="undefined"!=typeof Blob&&r instanceof Blob,n=t.source.name??"upload.bin";s?e.append("file",r,n):e.append("file",r)})(t,e),t},$d=(e,t,r)=>new Promise((s,n)=>{const o=e(),i=r.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const r=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:r})})})(o,r),o.addEventListener("abort",()=>{try{Pd("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),o.addEventListener("timeout",()=>{try{Pd("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),o.addEventListener("error",()=>{try{Pd("network",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),o.addEventListener("load",()=>{s({status:o.status,body:o.responseText})});try{const e=Dd(r);o.timeout=i,o.open("POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,r])=>{e.setRequestHeader(t,r)})})(o,r.headers),o.send(e)}catch(a){n(Fo("Upload adapter execution failed.",{code:qo,stage:No,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),qd=(e,t)=>e?"timeout":"abort",Gd=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,r=e?.fetchImpl;if("function"==typeof t||"function"==typeof r)return{upload(s){if("function"==typeof t)return $d(t,e,s);if("function"==typeof r)return(async(e,t,r)=>{const s=r.timeoutMs??t?.timeoutMs??3e4;let n=!1;const o="undefined"!=typeof AbortController?new AbortController:void 0,i=o&&Number.isFinite(s)?setTimeout(()=>{n=!0,o.abort()},s):void 0,a=((e,t)=>e??t?.signal)(r.signal,o);try{const t=Dd(r),s=await e(r.url,{method:"POST",headers:r.headers,body:t,signal:a}),n=await s.text(),o=r.source.size;return"number"==typeof o&&r.onProgress?.({loaded:o,total:o,percent:o>0?100:void 0}),{status:s.status,body:n}}catch(c){const e=c instanceof Error&&"AbortError"===c.name;throw Fo("Upload adapter execution failed.",{code:qo,stage:No,retryable:!e,details:{reason:e?qd(n):"network",url:r.url,cause:c instanceof Error?c.message:String(c)}})}finally{i&&clearTimeout(i)}})(r,e,s);throw Fo("Upload adapter execution failed.",{code:qo,stage:No,retryable:!1,details:{reason:"missing-upload-runtime",url:s.url}})}}},Bd=(e,t)=>{const r=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append("file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw Fo("React Native upload adapter only supports rn-uri source.",{code:qo,stage:No,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),r},Fd=e=>{const t=e?.fetchImpl,r=e?.formDataCtor;if("function"==typeof t&&"function"==typeof r)return{async upload(s){const n=s.timeoutMs??e?.timeoutMs??3e4,o="function"==typeof AbortController?new AbortController:void 0;let i=!1;const a=o&&Number.isFinite(n)?setTimeout(()=>{i=!0,o.abort()},n):void 0;try{const e=Bd(r,s),n=await t(s.url,{method:"POST",headers:s.headers,body:e,signal:s.signal??o?.signal}),i=await n.text(),a=s.source.size;return"number"==typeof a&&s.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:n.status,body:i}}catch(c){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===qo&&t.stage===No})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw Fo("React Native upload adapter execution failed.",{code:qo,stage:No,retryable:!e||i,details:{url:s.url,reason:e?i?"timeout":"abort":"network",cause:c instanceof Error?c.message:String(c)}})}finally{void 0!==a&&clearTimeout(a)}}}},zd=(e,t)=>e+t&4294967295,Kd=(e,t,r,s,n,o)=>{return zd((i=zd(zd(t,e),zd(s,o)))<<(a=n)|i>>>32-a,r);var i,a},Hd=(e,t,r,s,n,o,i)=>Kd(t&r|~t&s,e,t,n,o,i),Vd=(e,t,r,s,n,o,i)=>Kd(t&s|r&~s,e,t,n,o,i),Wd=(e,t,r,s,n,o,i)=>Kd(t^r^s,e,t,n,o,i),Jd=(e,t,r,s,n,o,i)=>Kd(r^(t|~s),e,t,n,o,i),Zd=(e,t)=>{let[r,s,n,o]=e;r=Hd(r,s,n,o,t[0]??0,7,-680876936),o=Hd(o,r,s,n,t[1]??0,12,-389564586),n=Hd(n,o,r,s,t[2]??0,17,606105819),s=Hd(s,n,o,r,t[3]??0,22,-1044525330),r=Hd(r,s,n,o,t[4]??0,7,-176418897),o=Hd(o,r,s,n,t[5]??0,12,1200080426),n=Hd(n,o,r,s,t[6]??0,17,-1473231341),s=Hd(s,n,o,r,t[7]??0,22,-45705983),r=Hd(r,s,n,o,t[8]??0,7,1770035416),o=Hd(o,r,s,n,t[9]??0,12,-1958414417),n=Hd(n,o,r,s,t[10]??0,17,-42063),s=Hd(s,n,o,r,t[11]??0,22,-1990404162),r=Hd(r,s,n,o,t[12]??0,7,1804603682),o=Hd(o,r,s,n,t[13]??0,12,-40341101),n=Hd(n,o,r,s,t[14]??0,17,-1502002290),s=Hd(s,n,o,r,t[15]??0,22,1236535329),r=Vd(r,s,n,o,t[1]??0,5,-165796510),o=Vd(o,r,s,n,t[6]??0,9,-1069501632),n=Vd(n,o,r,s,t[11]??0,14,643717713),s=Vd(s,n,o,r,t[0]??0,20,-373897302),r=Vd(r,s,n,o,t[5]??0,5,-701558691),o=Vd(o,r,s,n,t[10]??0,9,38016083),n=Vd(n,o,r,s,t[15]??0,14,-660478335),s=Vd(s,n,o,r,t[4]??0,20,-405537848),r=Vd(r,s,n,o,t[9]??0,5,568446438),o=Vd(o,r,s,n,t[14]??0,9,-1019803690),n=Vd(n,o,r,s,t[3]??0,14,-187363961),s=Vd(s,n,o,r,t[8]??0,20,1163531501),r=Vd(r,s,n,o,t[13]??0,5,-1444681467),o=Vd(o,r,s,n,t[2]??0,9,-51403784),n=Vd(n,o,r,s,t[7]??0,14,1735328473),s=Vd(s,n,o,r,t[12]??0,20,-1926607734),r=Wd(r,s,n,o,t[5]??0,4,-378558),o=Wd(o,r,s,n,t[8]??0,11,-2022574463),n=Wd(n,o,r,s,t[11]??0,16,1839030562),s=Wd(s,n,o,r,t[14]??0,23,-35309556),r=Wd(r,s,n,o,t[1]??0,4,-1530992060),o=Wd(o,r,s,n,t[4]??0,11,1272893353),n=Wd(n,o,r,s,t[7]??0,16,-155497632),s=Wd(s,n,o,r,t[10]??0,23,-1094730640),r=Wd(r,s,n,o,t[13]??0,4,681279174),o=Wd(o,r,s,n,t[0]??0,11,-358537222),n=Wd(n,o,r,s,t[3]??0,16,-722521979),s=Wd(s,n,o,r,t[6]??0,23,76029189),r=Wd(r,s,n,o,t[9]??0,4,-640364487),o=Wd(o,r,s,n,t[12]??0,11,-421815835),n=Wd(n,o,r,s,t[15]??0,16,530742520),s=Wd(s,n,o,r,t[2]??0,23,-995338651),r=Jd(r,s,n,o,t[0]??0,6,-198630844),o=Jd(o,r,s,n,t[7]??0,10,1126891415),n=Jd(n,o,r,s,t[14]??0,15,-1416354905),s=Jd(s,n,o,r,t[5]??0,21,-57434055),r=Jd(r,s,n,o,t[12]??0,6,1700485571),o=Jd(o,r,s,n,t[3]??0,10,-1894986606),n=Jd(n,o,r,s,t[10]??0,15,-1051523),s=Jd(s,n,o,r,t[1]??0,21,-2054922799),r=Jd(r,s,n,o,t[8]??0,6,1873313359),o=Jd(o,r,s,n,t[15]??0,10,-30611744),n=Jd(n,o,r,s,t[6]??0,15,-1560198380),s=Jd(s,n,o,r,t[13]??0,21,1309151649),r=Jd(r,s,n,o,t[4]??0,6,-145523070),o=Jd(o,r,s,n,t[11]??0,10,-1120210379),n=Jd(n,o,r,s,t[2]??0,15,718787259),s=Jd(s,n,o,r,t[9]??0,21,-343485551),e[0]=zd(r,e[0]),e[1]=zd(s,e[1]),e[2]=zd(n,e[2]),e[3]=zd(o,e[3])},Qd=(e,t)=>{const r=new Array(16).fill(0);for(let s=0;s<16;s+=1){const n=t+4*s;r[s]=(e[n]??0)|(e[n+1]??0)<<8|(e[n+2]??0)<<16|(e[n+3]??0)<<24}return r},Yd=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},Xd=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)Zd(t,Qd(e,r));const s=new Array(16).fill(0);let n=0;for(;r<e.length;r+=1){const t=n>>2;s[t]=(s[t]??0)|(e[r]??0)<<n%4*8,n+=1}const o=n>>2;s[o]=(s[o]??0)|128<<n%4*8,n>55&&(Zd(t,s),s.fill(0));const i=8*e.length;return s[14]=4294967295&i,s[15]=Math.floor(i/4294967296),Zd(t,s),t.map(Yd).join("")},eu=async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{image:t,width:t.width,height:t.height,cleanup:()=>{t.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw Fo("Image decode capability is missing for current platform",{code:Do,stage:Lo,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,r)=>{const s=new Image;s.onload=()=>{e({image:s,width:s.naturalWidth||s.width,height:s.naturalHeight||s.height,cleanup:()=>{URL.revokeObjectURL(t)}})},s.onerror=()=>{URL.revokeObjectURL(t),r(Fo("Image decode failed",{code:qo,stage:Lo,retryable:!1,details:{reason:"image load error"}}))},s.src=t})},tu=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw Fo("Web image processor only supports web file source",{code:Do,stage:Lo,retryable:!1,details:{sourceType:e.sourceType}});return e.file},ru=()=>({async getImageInfo(e){const t=tu(e),r=await eu(t);try{return{width:r.width,height:r.height,mimeType:e.mimeType,fileSize:e.size,isGif:"image/gif"===e.mimeType}}finally{r.cleanup()}},async generateBigImage(e,t){const r=tu(e),s=await eu(r);try{const r=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(s.width,s.height,t.maxShortEdge),o=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const r=document.createElement("canvas");return r.width=e,r.height=t,r}throw Fo("Canvas capability is missing for current platform",{code:Do,stage:Lo,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),i=o.getContext("2d");if(!i)throw Fo("Canvas 2d context is missing",{code:Do,stage:Lo,retryable:!1});i.drawImage(s.image,0,0,r.width,r.height);const a="image/png"===(n=e.mimeType)||"image/webp"===n?n:"image/jpeg",c=await(async(e,t,r)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:r});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((s,n)=>{e.toBlob(e=>{e?s(e):n(Fo("Image encode failed",{code:qo,stage:Lo,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,r)});throw Fo("Canvas encode capability is missing for current platform",{code:Do,stage:Lo,retryable:!1,details:{reason:"canvas encode unavailable"}})})(o,a,t.quality),d=(e=>e.name??"image")(e),u="undefined"!=typeof File?new File([c],d,{type:a,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:u??c,name:d,mimeType:a,size:u?.size??c.size},width:r.width,height:r.height,fileName:d,fileType:a,fileSize:u?.size??c.size,webFile:u}}finally{s.cleanup()}var n},async computeMd5(e){const t=tu(e),r=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw Fo("Binary read capability is missing for current platform",{code:Do,stage:Lo,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,r)=>{const s=new FileReader;s.onerror=()=>{r(Fo("Binary read failed",{code:qo,stage:Lo,retryable:!1}))},s.onload=()=>{s.result instanceof ArrayBuffer?t(s.result):r(Fo("Binary read returned invalid result",{code:qo,stage:Lo,retryable:!1}))},s.readAsArrayBuffer(e)})})(t);return Xd(new Uint8Array(r))}}),su=e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"errMsg"in e){const t=e.errMsg;if("string"==typeof t)return t}return String(e)},nu=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw Fo("Miniapp image processor only supports miniapp path source",{code:Do,stage:Lo,retryable:!1,details:{sourceType:e.sourceType}});return e.path},ou=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw Fo("Miniapp file system capability is missing",{code:Do,stage:Lo,retryable:!1,details:{capability:"getFileSystemManager"}})},iu=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},au=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(su(e)))}})}).catch(e=>{throw Fo("Miniapp image info read failed",{code:qo,stage:Lo,retryable:!1,details:{src:t,cause:su(e)}})}),cu=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,du=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await au(e,t);return cu(t,r)},uu=e=>({async getImageInfo(t){const r=nu(t),s=await au(e,r),n=iu(s.type)??t.mimeType;return{width:s.width,height:s.height,mimeType:n,fileSize:t.size,isGif:"image/gif"===n}},async generateBigImage(t,r){const s=nu(t);if("function"!=typeof e.compressImage)throw Fo("Miniapp image compress capability is missing",{code:Do,stage:Lo,retryable:!1,details:{capability:"compressImage"}});const n=await au(e,s),o=cu(s,n),i=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(n.width,n.height,r.maxShortEdge),a=await new Promise((t,s)=>{e.compressImage?.({src:o,quality:Math.max(0,Math.min(100,Math.round(100*r.quality))),compressedWidth:i.width,compressedHeight:i.height,success:e=>{e.tempFilePath?t(e.tempFilePath):s(new Error("compressImage missing tempFilePath"))},fail:e=>{s(e instanceof Error?e:new Error(su(e)))}})}).catch(e=>{throw Fo("Miniapp image compress failed",{code:qo,stage:Lo,retryable:!1,details:{src:o,cause:su(e)}})}),c=await du(e,a),d=await au(e,c),u=iu(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=ou(e);return s.getFileInfo?new Promise((e,r)=>{s.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{r(e instanceof Error?e:new Error(su(e)))}})}).catch(e=>{throw Fo("Miniapp file info read failed",{code:qo,stage:Lo,retryable:!1,details:{filePath:t,cause:su(e)}})}):r})(e,c,t.size);return{source:{sourceType:"miniapp-path",path:c,name:t.name,mimeType:u,size:l},width:d.width,height:d.height,fileName:t.name,fileType:u,fileSize:l}},async computeMd5(t){const r=nu(t),s=await du(e,r),n=await(async(e,t)=>{const r=ou(e),s=await new Promise((e,s)=>{r.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{s(e instanceof Error?e:new Error(su(e)))}})}).catch(e=>{throw Fo("Miniapp file read failed",{code:qo,stage:Lo,retryable:!1,details:{filePath:t,cause:su(e)}})});return s instanceof ArrayBuffer?new Uint8Array(s):"function"==typeof TextEncoder?(new TextEncoder).encode(s):Uint8Array.from(Array.from(s).map(e=>255&e.charCodeAt(0)))})(e,s);return Xd(n)}}),lu=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),hu=[/\bquota\b/i,/\bexceed(?:ed)?\s+storage\s+max(?:imum)?\s+size\b/i,/\b(?:storage\s+)?max(?:imum)?\s+size\b.*\bexceed(?:ed)?\b/i,/\bstorage\b.*\blimit\b.*\b(?:exceed(?:ed)?|reach(?:ed)?)\b/i],pu=(e,t)=>{if("object"!=typeof e||null===e)return null;const r=e[t];return"string"==typeof r?r:null},mu=e=>{if(!e)return!1;const t=pu(e,"name");if(t&&lu.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,pu(e,"message"),pu(e,"errMsg")].some(e=>null!==e&&hu.some(t=>t.test(e)))},fu=e=>{if(e instanceof Error)return e;const t=pu(e,"message")??pu(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},gu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",yu=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),vu=e=>e===Eo.ALIPAY_MINIAPP||e===Eo.DINGTALK_MINIAPP,bu=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=t.endsWith("==")?2:t.endsWith("=")?1:0,s=Math.max(0,Math.floor(3*t.length/4)-r),n=new Uint8Array(s);let o=0;for(let i=0;i<t.length;i+=4){const e=gu.indexOf(t[i]??""),r=gu.indexOf(t[i+1]??""),a=t[i+2]??"=",c=t[i+3]??"=",d="="===a?0:gu.indexOf(a),u="="===c?0:gu.indexOf(c);if(e<0||r<0||d<0||u<0)return new ArrayBuffer(0);const l=e<<18|r<<12|d<<6|u;for(const t of[16,8,0])o<s&&(n[o]=l>>t&255,o+=1)}return n.buffer},Iu=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),wu=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Cu=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Iu(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?Cu(r.data,t+1):e},Su=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return wu(e);if(Iu(e))try{return wu(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return wu(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e))return e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)?Uint8Array.from(e):void 0;if("object"!=typeof e)return;const r=e;if("data"in r&&r.data!==e){const e=Su(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=Su(r.buffer,t+1);if(!e)return;const s="number"==typeof r.byteOffset&&Number.isInteger(r.byteOffset)?r.byteOffset:0,n="number"==typeof r.byteLength&&Number.isInteger(r.byteLength)?r.byteLength:e.byteLength-s;if(s<0||n<0||s+n>e.byteLength)return;return e.slice(s,s+n)}},Tu=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(vu(t)){const s=(e=>{let t="";for(let r=0;r<e.length;r+=3){const s=e[r]??0,n=e[r+1],o=e[r+2],i=s<<16|(n??0)<<8|(o??0);t+=gu[i>>18&63],t+=gu[i>>12&63],t+=void 0===n?"=":gu[i>>6&63],t+=void 0===o?"=":gu[63&i]}return t})(r);return To("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:r.byteLength,encodedCharacters:s.length,sourcePrefixHex:yu(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},_u=(e,t)=>"string"!=typeof e&&vu(t),Ru=(e,t)=>{const r=Cu(e.data);if("string"==typeof r){if(!vu(t))return r;const s=bu(r),n=new Uint8Array(s);return To("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:r===e.data?"string":"wrapped-string",sourceCharacters:r.length,decodedBytes:s.byteLength,decodedPrefixHex:yu(n.subarray(0,8)),decodedSuffixHex:yu(n.subarray(Math.max(0,n.length-8)))}),s}const s=Su(r);if(!s){const s="object"==typeof e.data&&null!==e.data?e.data:void 0;return void To("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof r,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:s?Object.keys(s).slice(0,10):[],isBuffer:e.isBuffer})}if(!vu(t))return s.buffer;const n=(e=>{let t="";for(const s of e){if(9!==s&&10!==s&&13!==s&&32!==s&&!(s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||43===s||45===s||47===s||61===s||95===s))return;t+=String.fromCharCode(s)}const r=t.replace(/\s/g,"");if(0!==r.length&&r.length%4!=1&&/^[A-Za-z0-9+/_-]+={0,2}$/.test(r))return r})(s);if(!n)return To("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,sourcePrefixHex:yu(s.subarray(0,8))}),s.buffer;const o=bu(n),i=new Uint8Array(o);return To("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,decodedBytes:o.byteLength,decodedPrefixHex:yu(i.subarray(0,8)),decodedSuffixHex:yu(i.subarray(Math.max(0,i.length-8)))}),o},Au=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Mu=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],Eu=e=>e instanceof Error?e.message:Au(e)&&"string"==typeof e.errMsg?e.errMsg:Au(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),Uu=e=>e?{...e}:{},ku=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},Nu=e=>{try{e.close()}catch{}},Ou=(e,t)=>new Promise((r,s)=>{let n=!1,o=()=>{};const i=(e,r,i)=>{n||(n=!0,o(),s(Fo(e,{code:$o,stage:ko,retryable:i,details:{url:t.url,method:"GET",cause:Eu(r)}})))},a=e.downloadFile?.({url:t.url,header:Uu(t.headers),timeout:t.timeoutMs??15e3,success:s=>{const a=s.tempFilePath??s.apFilePath;a?((e,t)=>new Promise((r,s)=>{const n=e.getFileSystemManager?.();n?n.readFile({filePath:t,success:e=>{const t=Su(e.data);t?r(t.buffer):s(new Error("downloaded file response is not binary"))},fail:s}):s(new Error("getFileSystemManager returned no file system manager"))}))(e,a).then(e=>{n||(n=!0,o(),To("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:s.apFilePath?"apFilePath":"tempFilePath",status:s.statusCode??200,bytes:e.byteLength}),r({status:s.statusCode??200,headers:s.header??{},data:e}))}).catch(e=>{i("Mini program downloaded file read failed.",e,!1)}):i("Mini program download did not return a file path.",s,!1)},fail:e=>{i("Mini program file download failed.",e,!0)}});o=ku(t.signal,()=>{a?.abort(),i("Mini program file download aborted.","abort",!1)})}),xu=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((r,s)=>{let n=()=>{};const o=e.request({url:t.url,method:t.method??"GET",header:Uu(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{n(),r({status:e.statusCode,headers:e.header??{},data:e.data})},fail:e=>{n(),s(Fo("Mini program request failed.",{code:$o,stage:ko,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:Eu(e)}}))}});n=ku(t.signal,()=>{o.abort(),s(Fo("Mini program request aborted.",{code:$o,stage:ko,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):Ou(e,t)}),Lu=(e,t)=>({connect:r=>new Promise((s,n)=>{let o,i,a=!1;const c=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},d=(e,t,s)=>{a||(a=!0,c(),o&&Nu(o),n(Fo(t,{code:Go,stage:Oo,retryable:s,details:{url:r.url,cause:Eu(e)}})))},u=e=>{if(!(Mu(r=e,"send")&&Mu(r,"close")&&Mu(r,"onOpen")&&Mu(r,"onMessage")&&Mu(r,"onError")&&Mu(r,"onClose")))return void d(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var r;const n=e;if(a)return void Nu(n);o=n;const i=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?Nu(n):(a=!0,c(),i(),s(((e,t,r=jo)=>{const s=new Set,n=new Set,o=new Set,i=new Set;let a=r;return e.onOpen(()=>{a=zo,s.forEach(e=>{e()})}),e.onMessage(e=>{const r=Ru(e,t);void 0!==r&&n.forEach(e=>{e(r)})}),e.onError(e=>{o.forEach(t=>{t(e)})}),e.onClose(e=>{a=Ho,i.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(r){if(a!==zo)throw Fo("Mini program socket is not open.",{code:Go,stage:Oo,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:Tu(r,t),..._u(r,t)?{isBuffer:!0}:{},success:s,fail:e=>{n(Fo("Mini program socket send failed.",{code:Go,stage:Oo,retryable:!0,details:{cause:Eu(e)}}))}})})},close(t,r){a=Ko,e.close({code:t,reason:r})},onOpen:e=>(s.add(e),()=>{s.delete(e)}),onMessage:e=>(n.add(e),()=>{n.delete(e)}),onError:e=>(o.add(e),()=>{o.delete(e)}),onClose:e=>(i.add(e),()=>{i.delete(e)})}})(n,t,zo)))},l=e=>{i(),d(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};n.onOpen(u),n.onError(l)};let l;"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(i=setTimeout(()=>{d("timeout","Mini program socket connection timed out.",!0)},r.timeoutMs));try{l=e.connectSocket({url:r.url,...t===Eo.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(r.protocols)?[...r.protocols]:"string"==typeof r.protocols?[r.protocols]:void 0,fail:e=>{d(e,"Mini program socket connect failed.",!0)}})}catch(p){return void d(p,"Mini program socket creation failed.",!0)}var h;"object"!=typeof(h=l)||null===h||"function"!=typeof h.then?u(l):Promise.resolve(l).then(e=>u(e),e=>d(e,"Mini program socket connect failed.",!0))})}),Pu=e=>({upload:t=>new Promise((r,s)=>{const n=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw Fo("Mini program upload only supports miniapp-path source.",{code:qo,stage:No,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let o=()=>{};const i=e.uploadFile({url:t.url,filePath:n.path,name:"file",header:Uu(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{o(),r({status:e.statusCode,body:e.data})},fail:e=>{o(),s(Fo("Mini program upload failed.",{code:qo,stage:No,retryable:!0,details:{url:t.url,path:n.path,cause:Eu(e)}}))}});i.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),o=ku(t.signal,()=>{i.abort(),s(Fo("Mini program upload aborted.",{code:qo,stage:No,retryable:!1,details:{url:t.url,path:n.path,reason:"abort"}}))})})}),Du=(e,t)=>{const r=(e=>e===Eo.ALIPAY_MINIAPP||e===Eo.DINGTALK_MINIAPP)(t);return{async getItem(t){if(Mu(e,"getStorageSync"))try{const s=(e=>Au(e)&&"data"in e?e.data:e)(e.getStorageSync(r?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return Mu(e,"getStorage")?new Promise(r=>{e.getStorage({key:t,success:e=>{r("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{r(null)}})}):null},async setItem(t,s){if(Mu(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(mu(n))throw fu(n)}else if(Mu(e,"setStorage"))return new Promise((r,o)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{mu(e)?o(fu(e)):r()}})}catch(n){if(mu(n))return void o(fu(n));r()}})},async removeItem(t){if(Mu(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(Mu(e,"removeStorage"))return new Promise(r=>{try{e.removeStorage({key:t,success:r,fail:()=>{r()}})}catch{r()}})}}},$u=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>Mu(e,"getNetworkType")?new Promise(t=>{e.getNetworkType?.({success:e=>{t(e.networkType??"unknown")},fail:()=>{t("unknown")}})}):Promise.resolve("unknown"),onNetworkChange(t){const r=e=>{t(e.isConnected)};return Mu(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),Mu(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{Mu(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return Mu(e,"onAppShow")&&e.onAppShow(r),Mu(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{Mu(e,"offAppShow")&&e.offAppShow(r),Mu(e,"offAppHide")&&e.offAppHide(s)}}}),qu=(e,t=Eo.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(Mu(e,"request")&&Mu(e,"connectSocket")&&Mu(e,"uploadFile"))return e;throw Fo("Mini program platform capability is missing.",{code:Do,stage:Uo,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),n="function"==typeof s.getImageInfo?uu(s):void 0;return{request:xu(s),socket:Lu(s,r),upload:Pu(s),runtime:$u(s,t),storage:Du(s,r),imageProcessor:n}},Gu=[Eo.WEB,Eo.ELECTRON_RENDERER,Eo.REACT_NATIVE],Bu=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Fu=e=>Gu.includes(e),ju=(e,t)=>e!==Eo.UNIAPP?Fu(e):!ii(t)&&!Ku(t)&&ri(t),zu=e=>Bu(e,"getImageInfo")&&Bu(e,"getFileSystemManager"),Ku=e=>!ii(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),Hu=(e,t)=>{if(Fu(e)&&e!==Eo.REACT_NATIVE)return ru();if(ui(e)&&zu(t))return uu(t);if(e===Eo.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(ri(e))return ru();if(zu(e.uni))return uu(e.uni);if(zu(e.wx))return uu(e.wx)}},Vu=e=>{const t=e.localStorage;if(t)return{getItem:e=>Promise.resolve(t.getItem(e)),setItem:(e,r)=>(t.setItem(e,r),Promise.resolve()),removeItem:e=>(t.removeItem(e),Promise.resolve())};const r=new Map;return{getItem(e){const t=r.has(e)?r.get(e)??null:null;return Promise.resolve(t)},setItem:(e,t)=>(r.set(e,t),Promise.resolve()),removeItem:e=>(r.delete(e),Promise.resolve())}},Wu=(e,t,r,s)=>{if(e===Eo.UNIAPP&&Ku(r)&&void 0!==r.uni&&Qo(r.uni))return{...qu(r.uni,e,t),proto:Rd()};if(((e,t)=>!ju(e,t)&&ui(e))(e,r)&&Qo(s))return{...qu(s,e,t),proto:Rd()};const n=r.XMLHttpRequest,o=ju(e,r),i=o?Md({fetchImpl:r.fetch}):void 0,a=o?Ld({webSocketCtor:r.WebSocket}):void 0,c=e===Eo.REACT_NATIVE?Fd({fetchImpl:r.fetch,formDataCtor:r.FormData}):o?Gd({xhrFactory:"function"==typeof n?()=>new n:void 0,fetchImpl:r.fetch}):void 0,d=o&&e!==Eo.REACT_NATIVE?(u={platform:e,windowRef:r.window,documentRef:r.document,navigatorRef:r.navigator},{getPlatform:()=>u.platform,getNetworkType:()=>!1===u.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(u.navigatorRef?.connection?.type??u.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=u.windowRef;if(!t)return()=>{};const r=()=>{e(!0)},s=()=>{e(!1)};return t.addEventListener("online",r),t.addEventListener("offline",s),"boolean"==typeof u.navigatorRef?.onLine&&e(u.navigatorRef.onLine),()=>{t.removeEventListener("online",r),t.removeEventListener("offline",s)}},onAppVisibilityChange(e){const t=u.documentRef;if(!t)return()=>{};const r=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",r),r(),()=>{t.removeEventListener("visibilitychange",r)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var u;return{request:i,upload:c,socket:a,runtime:d,proto:Rd(),storage:Vu(r),imageProcessor:o&&e!==Eo.REACT_NATIVE?ru():Hu(e,s)}},Ju=(e,t)=>{if(void 0!==e)return e;throw Fo("Platform adapter initialization failed.",{code:Po,stage:Uo,retryable:!1,details:{capability:t}})},Zu=e=>{const t=Wo(e?.runtimeInput),r=di(t,e?.prefer),s=r.platform,n=Wu(s,r.hostPlatform,t,r.global),o=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,n),i={...n,...o},a=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(i);hi(a);return{platform:s,platformId:s,capability:a,request:Ju(i.request,"request"),upload:Ju(i.upload,"upload"),socket:Ju(i.socket,"socket"),runtime:Ju(i.runtime,"runtime"),proto:Ju(i.proto,"proto"),storage:Ju(i.storage,"storage"),imageProcessor:i.imageProcessor}},Qu=e=>{if(e instanceof rs)return e;if((e=>"object"==typeof e&&null!==e)(e)){const t=e.details;if(e.code===Do){const r=t?.capability;if(e.stage===Lo&&"string"==typeof r&&r.includes("FileSystem")){const r=e instanceof Error?e.message:"Upload failed";return new rs(r,{code:$r,details:t})}return new rs("Upload capability is missing for current platform",{code:Lr,details:t})}if(e.stage===No)return(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("abort"))})(t)?new rs("Upload canceled",{code:Gr,details:t}):(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("timeout"))})(t)?new rs("Upload timeout",{code:qr,details:t}):new rs("Upload failed",{code:$r,details:t})}const t=e instanceof Error?e.message:"Upload failed";return new rs(t,{code:$r,details:{cause:e}})},Yu={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Xu{constructor(e={}){this.attemptCount=0,this.config={...Yu,...e}}getRetryDelay(){const e=Math.max(this.attemptCount-1,0),t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),r=Math.min(t,this.config.maxDelay);return r/2+r/2*Math.min(1,Math.max(0,this.config.randomSource()))}recordAttempt(){this.attemptCount++}reset(){this.attemptCount=0}shouldRetry(){return this.attemptCount<this.config.maxAttempts}getAttemptCount(){return this.attemptCount}async waitForRetry(){const e=this.getRetryDelay();return So(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const el={interval:3e4,timeout:6e4},tl="function"==typeof TextDecoder?new TextDecoder:null;class rl{constructor(e={}){this.websocket=null,this.heartbeatTimer=null,this.timeoutTimer=null,this.lastPongTime=0,this.onTimeoutCallback=null,this.sendPing=null,this.probeResolvers=[],this.messageDisposer=null,this.handlePong=e=>{const t=this.extractMessageText(e);if(!t)return;const r=this.parseJson(t);if(!rl.isRecord(r))return;"pong"===rl.readString(r.type)&&(this.markAlive(),So("Pong received"))},this.config={...el,...e}}start(e,t,r){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=r??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),So("Heartbeat started",{interval:this.config.interval})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.timeoutTimer&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.messageDisposer?.(),this.messageDisposer=null,this.websocket=null,this.sendPing=null,this.resolveProbe(!1),So("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===zo)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{_o("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),So("Ping sent")}catch(e){_o("Failed to send ping:",e),this.resolveProbe(!1)}else this.resolveProbe(!1)}extractMessageText(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return(e=>{for(const t of e)if(32!==t&&9!==t&&10!==t&&13!==t)return 123===t;return!1})(t)?tl?.decode(t)??Ao(t):null}return null}parseJson(e){try{return JSON.parse(e)}catch{return null}}static isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static readString(e){return"string"==typeof e?e:void 0}resetTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=setTimeout(()=>{To("Heartbeat timeout"),this.onTimeoutCallback&&this.onTimeoutCallback()},this.config.timeout)}markAlive(){this.lastPongTime=Date.now(),this.resetTimeout(),this.resolveProbe(!0)}getLastPongTime(){return this.lastPongTime}async probeOnce(e,t){try{if(e.readyState!==zo)return!1;this.attachWebSocket(e);const r=t??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},r);this.probeResolvers.push(r=>{clearTimeout(t),e(r)}),this.sendPingInternal()})}catch(r){return To("Heartbeat probe failed",r),!1}}attachWebSocket(e){this.websocket!==e&&(this.messageDisposer?.(),this.websocket=e,this.messageDisposer=e.onMessage(e=>{this.handlePong(e)}))}resolveProbe(e){if(0===this.probeResolvers.length)return;const t=[...this.probeResolvers];this.probeResolvers=[];for(const r of t)r(e)}removeProbeResolver(e){this.probeResolvers=this.probeResolvers.filter(t=>t!==e)}}let sl=null;function nl(){return sl||(sl=_d()),sl}const ol="websdk2:device-info",il="webim",al="web",cl=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,o=Wo().localStorage,i=()=>{if(!o)return null;try{const t=o.getItem(ol);if(!t)return null;const r=JSON.parse(t);if("object"==typeof(e=r)&&null!==e&&!Array.isArray(e)&&"string"==typeof r.deviceId&&"string"==typeof r.deviceName&&"string"==typeof r.deviceUuid)return{deviceId:r.deviceId,deviceName:r.deviceName,deviceUuid:r.deviceUuid}}catch{return null}var e;return null},a=e=>{if(o)try{o.setItem(ol,JSON.stringify(e))}catch{}},c=e=>void 0===s?e:{deviceId:`custom${s}_${e.deviceUuid}`,deviceName:n??r,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=i();if(e)return c(e);if(r===il){const e=`${al}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${al}_${r}`,deviceName:r,deviceUuid:`${al}_${t}`});return a(e),e}const n={deviceId:`webim_${al}_${r}`,deviceName:`webim_${al}_${r}`,deviceUuid:`webim_${al}_${r}`};return a(n),n}if(r===il){const e=`random_${al}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${al}_${r}`,deviceName:r,deviceUuid:`random_${al}_${t}`})}return{deviceId:`webim_${al}_${r}`,deviceName:`webim_${al}_${r}`,deviceUuid:`webim_${al}_${r}`}},dl=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),ul=e=>{if("string"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?`${e}`:"";if("bigint"==typeof e)return e.toString();if(e&&"object"==typeof e&&"low"in e&&"high"in e&&"number"==typeof e.low&&"number"==typeof e.high){const t=e;return new mi(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},ll=e=>{const t=[];for(const[r,s]of Object.entries(e))if(void 0!==s)if("boolean"!=typeof s)if("number"!=typeof s)if("string"!=typeof s)try{t.push({key:r,type:vn,stringValue:JSON.stringify(s)})}catch{t.push({key:r,type:yn,stringValue:Object.prototype.toString.call(s)})}else t.push({key:r,type:yn,stringValue:s});else Number.isInteger(s)?t.push({key:r,type:hn,varintValue:s}):t.push({key:r,type:gn,doubleValue:s});else t.push({key:r,type:ln,varintValue:s?1:0});return t},hl=e=>{if(!e||0===e.length)return{};const t={};for(const r of e){const e="string"==typeof r.key?r.key:"";if(!e)continue;const s="number"==typeof r.type?r.type:yn;if(s!==ln)if(s!==hn&&s!==pn&&s!==mn)if(s!==fn)if(s!==gn){if(s!==vn)t[e]="string"==typeof r.stringValue?r.stringValue:"";else if("string"==typeof r.stringValue)try{t[e]=JSON.parse(r.stringValue)}catch{t[e]=r.stringValue}}else t[e]=Number(r.doubleValue??0);else t[e]=Number(r.floatValue??0);else t[e]=Number(r.varintValue??0);else t[e]=Boolean(r.varintValue)}return t},pl=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,ml="X-Request-Id",fl=new Set(["mute"]),gl={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},yl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},vl=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},bl=(e,t)=>{const r=e?.map(e=>yl(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Il=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=vl(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,o=Number(n);return Number.isFinite(o)&&o>0?o:void 0},wl=e=>{const t=vl(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=gl[s];if(!e)continue;let t=n;if(fl.has(s))t=!0===n||"true"===n;else if("max_users"===s){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(r[e]=t)}return Object.keys(r).length>0?r:void 0},Cl=e=>{const t=vl(e);if(!t)return{attributes:{},keyList:[]};const r=t.result&&"object"==typeof t.result&&!Array.isArray(t.result)?t.result:{},s=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},n=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[];return{attributes:Object.fromEntries(n.map(e=>[e,s[e]]).filter(e=>"string"==typeof e[1])),keyList:n,from:yl(t.operator)??yl(t.username)}},Sl=(e,t)=>({eventName:e,payload:t}),Tl=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=yl(e.from?.name),s=(n=e.to,yl(n?.[0]?.name));var n;switch(e.operation){case 1:return Sl(qe,t);case 10:return Sl(Fe,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return Sl(Ge,{...t,memberIds:bl(e.members,r),ext:e.ext??e.eventExt});case 18:return Sl(Be,{...t,memberIds:bl(e.members,r)});case 20:return Sl(Ze,{...t,oldOwnerId:r,newOwnerId:s});case 21:return Sl(We,{...t,adminId:s??r});case 22:return Sl(Je,{...t,adminId:s??r});case 23:{const r=(e=>{const t=vl(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,o]of Object.entries(r)){const e=Number(o);n&&Number.isFinite(e)&&(s[n]=e)}return Object.keys(s).length>0?s:null})(e.ext??e.eventExt),n=r?Object.keys(r):bl(e.members,s),o=46388736e5;return Sl(je,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,o])),muteExpire:Il(e.reason,e.eventExt)??o})}case 24:return Sl(ze,{...t,userIds:bl(e.members,s)});case 25:return Sl(Qe,{...t,announcement:e.reason??""});case 26:return Sl(Qe,{...t,announcement:""});case 29:return Sl(Ke,{...t,userIds:bl(e.members,s)});case 30:return Sl(He,{...t,userIds:bl(e.members,s)});case 31:return Sl(Ve,{...t,isMuted:!0});case 32:return Sl(Ve,{...t,isMuted:!1});case 14:return Sl(Ye,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:wl(e.eventExt)});case 43:{const s=Cl(e.eventExt);return Sl(Xe,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=Cl(e.eventExt);return Sl(et,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},_l=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Rl=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},Al=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Ml=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),El=e=>({userId:e}),Ul=(e,t,r)=>{const s={userId:r};for(const n of Al){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},kl=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const i of n)s.set(i.userId,Ml(i));const o=r.filter(e=>!s.has(e));if(o.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:o});for(const t of e)s.set(t.userId,t)}for(const i of r)s.has(i)||s.set(i,El(i));return s},Nl=e=>_l(e)?e:null,Ol=e=>{if("string"==typeof e)return e},xl=e=>{const t=Ol(e)?.trim();return t||void 0},Ll=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}},Pl=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Dl=e=>{const t=Nl(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},$l=e=>{const t=Nl(e);return t?Nl(t.data)?t.data:t:null},ql=(e,t)=>{const r=Nl(e),s=r&&Nl(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Ll(n[0])},Gl=(e,t)=>{const r=(e=>{const t=Nl(e);return t?Ll(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},Bl=e=>xl(e.groupId)??xl(e.groupid)??xl(e.id)??"",Fl=e=>Ol(e.name)??Ol(e.groupname)??Ol(e.groupName)??"",jl=e=>{const t=Dl(e),r=Nl(t[0])??$l(e)??{},s=(e=>{const t=Nl(e);if(!t)return null;const r=Bl(t);return r?{groupId:r,name:Fl(t),description:Ol(t.description),memberCount:Ll(t.memberCount)??Ll(t.affiliations_count),public:Pl(t.public),joinApprovalRequired:Pl(t.joinApprovalRequired)??Pl(t.approval)??Pl(t.membersonly)??Pl(t.members_only),allowInvites:Pl(t.allowInvites)??Pl(t.allowinvites)??Pl(t.allow_user_invites),maxMembers:Ll(t.maxMembers)??Ll(t.maxusers),role:xl(t.role)??xl(t.permission),disabled:Pl(t.disabled)}:null})(r)??{groupId:Bl(r),name:Fl(r)},n=xl(r.owner)??xl(r.admin)??xl(r.member),o=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>Nl(e)).filter(e=>null!==e).map(e=>Ll(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?El(n):void 0,inviteNeedConfirm:Pl(r.inviteNeedConfirm)??Pl(r.invite_need_confirm),muteAllMembers:Pl(r.mute),ext:Ol(r.ext)??Ol(r.custom),createdAt:Ll(r.createdAt)??Ll(r.created),joinedAt:o,avatarUrl:Ol(r.avatar),messageBlocked:Pl(r.messageBlocked)??Pl(r.isMessageBlocked)??Pl(r.shieldgroup)}},zl=e=>El(e),Kl=e=>Dl(e).map(e=>xl(e)).filter(e=>Boolean(e)).map(e=>zl(e)),Hl=e=>{const t=Nl(e);if(!t)return null;const r=xl(t.fileId)??xl(t.file_id);if(!r)return null;const s=Ol(t.fileName)??Ol(t.file_name)??r,n=xl(t.fileOwner)??xl(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?zl(n):void 0,fileSize:Ll(t.fileSize)??Ll(t.file_size),createdAt:Ll(t.createdAt)??Ll(t.created)}},Vl=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Wl={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Jl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Zl=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Ql=(e,t)=>{const r=e?.map(e=>Jl(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Yl=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=Zl(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,o=Number(n);return Number.isFinite(o)&&o>0?o:void 0},Xl=e=>{const t=Zl(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Wl[s];if(!e)continue;let t=n;if(Vl.has(s))t=!0===n||"true"===n;else if("max_users"===s){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(r[e]=t)}return Object.keys(r).length>0?r:void 0},eh=(e,t)=>{const r=Zl(t)??Zl(e);return Hl(r??void 0)??void 0},th=(e,t)=>{const r=Zl(t)??Zl(e);return Jl(r?.fileId)??Jl(r?.file_id)??Jl(e)??""},rh=(e,t)=>({eventName:e,payload:t}),sh=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=Jl(e.from?.name),s=(n=e.to,Jl(n?.[0]?.name));var n;switch(e.operation){case 4:return rh(Y,{...t,applicantId:r,reason:e.reason});case 5:return rh(X,{...t,accepterId:r});case 6:return rh(ee,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return rh(Q,{...t,inviterId:r,reason:e.reason});case 8:return rh(te,{...t,inviteeId:r,reason:e.reason});case 9:return rh(re,{...t,inviteeId:r,reason:e.reason});case 10:return rh(se,t);case 1:return rh(ne,t);case 19:return rh(oe,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=Zl(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,o]of Object.entries(r)){const e=Jl(n),t=Number(o);e&&Number.isFinite(t)&&t>0&&(s[e]=t)}return Object.keys(s).length>0?s:null})(e.ext),n=r?Object.keys(r):Ql(e.members,s);return rh(ie,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??Yl(e.reason,e.eventExt)})}case 24:return rh(ae,{...t,userIds:Ql(e.members,s)});case 29:return rh(ce,{...t,userIds:Ql(e.members,s)});case 30:return rh(de,{...t,userIds:Ql(e.members,s)});case 31:return rh(ue,{...t,isMuted:!0});case 32:return rh(ue,{...t,isMuted:!1});case 21:return rh(le,{...t,administratorId:s??r});case 22:return rh(he,{...t,administratorId:s??r});case 20:return rh(pe,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=Ql(e.members,r);return rh(me,{...t,memberIds:s})}case 18:{const s=Ql(e.members,r);return rh(fe,{...t,memberIds:s})}case 25:return rh(ge,{...t,announcement:e.reason??""});case 26:return rh(ge,{...t,announcement:""});case 27:return rh(ye,{...t,sharedFile:eh(e.reason,e.eventExt)});case 28:return rh(ve,{...t,fileId:th(e.reason,e.eventExt)});case 14:return rh(be,{...t,shouldFetchGroupDetail:!0,groupPatch:Xl(e.eventExt)});case 41:return rh(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return rh(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=Zl(e);if(!t)return{attribute:{}};const r=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},s=Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]));return{userId:Jl(t.username),attribute:s}})(e.eventExt);return rh(we,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},nh=new WeakMap,oh=(e,t)=>{nh.set(e,t)},ih=e=>nh.get(e)??null,ah=(e,t)=>{const r=ih(e);r&&oh(t,r)},ch=new WeakMap,dh=e=>ch.get(e),uh=new WeakMap,lh=e=>uh.get(e),hh=(e,t)=>{const r=uh.get(e);r&&uh.set(t,r)},ph="singleChat",mh="groupChat",fh=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},gh=e=>{if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&e.trim().length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}},yh=e=>{if(!Array.isArray(e))return;const t=e.map(e=>fh(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},vh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),bh=(...e)=>{for(const t of e){const e=fh(t);if(e)return e}},Ih=(e,t)=>Boolean(e&&t&&e===t),wh=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),Ch=(e,t,r)=>{const s=yh(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>fh(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const o=fh(r?.name);return o?[o]:[]},Sh=e=>{const t=gh(e);if(void 0!==t)return t;if("string"==typeof e){const t=e.match(/(\d+)/);if(t){const e=Number(t[1]);return Number.isFinite(e)?e:void 0}}},Th=(e,t)=>{const r=bh(e.to?.[0]?.clientResource);if(1!==e.to?.length||fh(e.to[0]?.name)!==t.userId||!wh(t.userId,r,t))return null;const s=(n=e.from,fh(n?.name)??"");var n;if(!s)return To("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const o=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return To("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"contact",operation:o,targetUserId:s,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:r,timestamp:e.timestamp,raw:e.raw}},_h=(e,t)=>{if(!e.groupId)return To("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=bh(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!wh(fh(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 0:return"GROUP_CREATE";case 1:return"GROUP_DESTROY";case 2:return"GROUP_JOIN";case 3:return"GROUP_LEAVE";case 4:return"GROUP_APPLY";case 5:return"GROUP_APPLY_ACCEPT";case 6:return"GROUP_APPLY_DECLINE";case 7:return"GROUP_INVITE";case 8:return"GROUP_INVITE_ACCEPT";case 9:return"GROUP_INVITE_DECLINE";case 10:return"GROUP_KICK";case 12:return"GROUP_BAN";case 13:return"GROUP_ALLOW";case 15:return"GROUP_BLOCK";case 16:return"GROUP_UNBLOCK";case 20:return"GROUP_ASSIGN_OWNER";case 21:return"GROUP_ADD_ADMIN";case 22:return"GROUP_REMOVE_ADMIN";case 23:return"GROUP_ADD_MUTE";case 24:return"GROUP_REMOVE_MUTE";case 29:return"GROUP_ADD_USER_WHITE_LIST";case 30:return"GROUP_REMOVE_USER_WHITE_LIST";case 31:return"GROUP_ALL_BAN";case 32:return"GROUP_REMOVE_ALL_BAN";case 45:return"GROUP_MEMBER_METADATA_CHANGED";case 14:return"GROUP_UPDATED";default:return To("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Ch(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:fh(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Rh=(e,t)=>{if(!e.threadId)return To("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=bh(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!wh(fh(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 33:return"THREAD_CREATE";case 35:return"THREAD_JOIN";case 38:return"THREAD_UPDATE";case 36:return"THREAD_LEAVE";case 34:return"THREAD_DESTROY";case 37:return"THREAD_KICK";default:return To("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Ch(e.members,e.to,e.from);return{category:"thread",operation:s,threadId:e.threadId,parentId:e.parentId,userIds:n.length>0?n:void 0,operatorId:fh(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Ah=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=bh(e.res,e.raw?.resource,e.raw?.clientResource);if(Ih(r,t.clientResource))return So("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const s="chat"===(n=e.type)||"singleChat"===n?ph:mh;var n;const o=fh(e.id)??(s===ph?fh(e.from):void 0);if(!o)return To("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const i=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return To("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"conversation",operation:i,conversationId:o,conversationType:s,mark:"mark"===e.operation||"mark_delete"===e.operation?Sh(e.ext):void 0,operatorId:fh(e.from),deviceId:r,timestamp:gh(e.ts),raw:e.raw}},Mh=(e,t)=>{const r=bh(e.resource,e.raw?.resource,e.raw?.clientResource);if(Ih(r,t.clientResource))return So("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=fh(e.to);if(!s)return To("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=fh(e.lastMsgId),o=yh(e.msgIdList)??(n?[n]:void 0),i=gh(e.deleteTime);if(!o&&void 0===i)return To("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:s}),null;const a=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(To("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===a?null:{category:"messageRemoved",operation:a,conversationId:s,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?mh:ph,messageIds:o,beforeTimestamp:i,deviceId:r,raw:e.raw}},Eh=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},Uh=2147483647,kh=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>Uh?void 0:r},Nh=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>Uh?Math.floor(e/1e3):Math.floor(e);return kh(t)};var Oh=4096,xh=65547,Lh=15,Ph=2113929216,Dh=65536,$h=65536,qh=10485760,Gh={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Bh={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Fh(e){if(!(e>0))return $h;if(e<=$h)return $h;if(e>1073741823)return e;for(var t=$h;t<e;)t*=2;return t}var jh={byU16:0,byU32:1},zh=0,Kh=1,Hh=2,Vh=0,Wh=1;function Jh(e,t){return e[t]|e[t+1]<<8}function Zh(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Qh(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var Yh="fast";function Xh(e){return 2654435761*(e>>>0)>>>20&4095}function ep(e){return 2654435761*(e>>>0)>>>19&8191}function tp(e,t,r){if("fast"===Yh){var s=Zh(e,t);return r===jh.byU16?ep(s):Xh(s)}throw new Error("Unsupported hash strategy: "+Yh)}function rp(e,t,r,s,n){r[t]=e-n}function sp(e,t,r,s,n){rp(t,tp(e,t,s),r,0,n)}function np(e,t,r,s){return t[e]+s}function op(e,t,r,s,n){return np(tp(e,t,s),r,0,n)}function ip(e,t,r,s){for(var n=t;t<s-3;){if(Zh(e,t)!==Zh(e,r)){for(;t<s&&e[t]===e[r];)t++,r++;return t-n}t+=4,r+=4}for(;t<s&&e[t]===e[r];)t++,r++;return t-n}function ap(e,t,r,s,n,o,i,a,c,d){var u,l,h,p=e.hashTable,m=s,f=m-e.dictSize,g=e.dictionary,y=e.dictionaryStart,v=y+e.dictSize,b=e.dictSize>0?v-s:0,I=s,w=s+n,C=w-12,S=w-5,T=0,_=o>0?o:r.length,R=0;if(n>Ph)return 0;switch(c){case zh:default:u=s,l=s;break;case Kh:u=s-e.currentOffset,l=s-e.dictSize;break;case Hh:u=s-e.currentOffset,l=s}if(a===jh.byU16&&n>=xh)return 0;if(n<13)return up(t,r,I,w,T,_,i);sp(t,m,p,a,u),h=tp(t,++m,a);e:for(;;){var A,M,E=m,U=1,k=64;do{var N=h;if(m=E,E+=U,U=k++>>>6,E>C)return up(t,r,I,w,T,_,i);A=np(N,p,0,u),c===Hh&&(A<s?(R=b,l=y):(R=0,l=s)),h=tp(t,E,a),rp(m,N,p,0,u)}while(d===Wh&&A<f||a!==jh.byU16&&A+65535<m||!cp(t,g,m,A,R,c,s));for(;m>I&&A+R>l;){var O=A+R-1;if(t[m-1]!==(c===Hh&&A<s?g[O-y+e.dictionaryStart]:t[O]))break;m--,A--}var x=m-I;if(M=T++,i&&T+x+8+Math.floor(x/255)>_)return 0;if(x>=Lh){var L=x-Lh;for(r[M]=240;L>=255;)r[T++]=255,L-=255;r[T++]=L}else r[M]=x<<4;if(x>=16&&r.set&&t.subarray)r.set(t.subarray(I,I+x),T),T+=x;else for(var P=0;P<x;P++)r[T++]=t[I+P];t:for(;;){var D;if(Qh(r,T,m-A),T+=2,c===Hh&&A<s){var $=m+(v-(A+R));if($>S&&($=S),(m+=4+(D=dp(t,g,m+4,A+R+4-y+e.dictionaryStart,$,v-y)))===$&&$<S){var q=ip(t,m,s,S);D+=q,m+=q}}else m+=4+(D=ip(t,m+4,A+4,S));if(i&&T+6+(D>>>8)>_)return 0;if(D>=15){for(r[M]+=15,D-=15;D>=510;)r[T++]=255,r[T++]=255,D-=510;D>=255&&(D-=255,r[T++]=255),r[T++]=D}else r[M]+=D;if(I=m,m>C)break e;if(sp(t,m-2,p,a,u),A=op(t,m,p,a,u),c===Hh&&(A<s?(R=b,l=y):(R=0,l=s)),sp(t,m,p,a,u),!((d!==Wh||A>=f)&&A+65535>=m&&cp(t,g,m,A,R,c,s)))break t;r[M=T++]=0}h=tp(t,++m,a)}return up(t,r,I,w,T,_,i)}function cp(e,t,r,s,n,o,i){var a,c=Zh(e,r);o===Hh&&s+n<i?a=Zh(t,s+n):a=Zh(e,s+n);return c===a}function dp(e,t,r,s,n,o,i){for(var a=r;s<o&&r<n&&t[s]===e[r];)s++,r++;return r-a}function up(e,t,r,s,n,o,i){var a=s-r;if(i&&n+a+1+Math.floor((a+255-Lh)/255)>o)return 0;if(a>=Lh){for(t[n++]=240,a-=Lh;a>=255;)t[n++]=255,a-=255;t[n++]=a}else t[n++]=a<<4;var c=r,d=s,u=d-c;if(u>=16&&t.set&&e.subarray)t.set(e.subarray(c,d),n),n+=u;else for(var l=c;l<d;l++)t[n++]=e[l];return n}function lp(e,t,r,s){var n,o=0;if(s&&t.ip>=r)return-1;do{if(o+=n=e[t.ip++],t.ip>r)return-1;if(o>2147483647)return-1}while(255===n);return o}function hp(e,t,r,s,n,o,i,a,c,d,u,l,h){if(null==e)return-1;if(o<0)return-1;var p=r,m=r+s,f=n,g=n+o,y=u-h,v=l+h,b=h<65536;if(0===o)return 1===s&&0===e[p]?0:-1;if(0===s)return-1;for(;;){var I,w,C,S;if(p>=m)return-(p-r)-1;if((w=(I=e[p++])>>>4)===Lh){var T=lp(e,A={ip:p},m-Lh,!0);if(p=A.ip,-1===T)return-(p-r)-1;if(f+(w+=T)<f)return-(p-r)-1;if(p+w<p)return-(p-r)-1}if(C=f+w,i&&(C>g-12||p+w>m-8)||!i&&C>g-8){if(!i&&C!==g)return-(p-r)-1;if(i&&(p+w!==m||C>g))return-(p-r)-1;if(w>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+w),f);else for(var _=0;_<w;_++)t[f+_]=e[p+_];p+=w,f+=w;break}if(w>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+w),f);else for(_=0;_<w;_++)t[f+_]=e[p+_];if(f=C,(p+=w)+2>m)return-(p-r)-1;var R=Jh(e,p);if(p+=2,S=C-R,b&&S+h<u)return-(p-r)-1;if(0===R)return-(p-r)-1;if(15===(w=15&I)){var A;T=lp(e,A={ip:p},m-5+1,!1);if(p=A.ip,-1===T)return-(p-r)-1;if(f+(w+=T)<f)return-(p-r)-1}if(w+=4,d===Hh&&S<u){if(f+w>g-5)return-(p-r)-1;if(w<=u-S){var M=v-(u-S);for(_=0;_<w;_++)t[f+_]=t[M+_];f+=w}else{var E=u-S;for(M=v-E,_=0;_<E;_++)t[f+_]=t[M+_];var U=w-E;if(U>(f+=E)-u)for(var k=u,N=f+U;f<N;)t[f++]=t[k++];else{for(_=0;_<U;_++)t[f+_]=t[u+_];f+=U}}}else{if(S<y)return-(p-r)-1;if(C=f+w,f-S<8)for(t[f]=t[S],t[f+1]=t[S+1],t[f+2]=t[S+2],t[f+3]=t[S+3],f+=4,S+=4;f<C;)t[f++]=t[S++];else for(;f<C;)t[f++]=t[S++]}}return i?f-n:p-r}function pp(){return{hashTable:new Uint32Array(Oh),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function mp(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function fp(e,t,r,s,n,o,i,a){s=s||0;var c=e.dictionaryStart+e.dictSize,d=s;if(e.initCheck)return 0;e.dictSize>0&&d>c&&(d=c),function(e){if(e.currentOffset>2147483648){for(var t=e.currentOffset-65536,r=e.dictionaryStart+e.dictSize,s=0;s<e.hashTable.length;s++)e.hashTable[s]<t?e.hashTable[s]=0:e.hashTable[s]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=r-e.dictSize}}(e);var u,l=s+n;e.dictionary&&l>e.dictionaryStart&&l<c&&(e.dictSize=c-l,e.dictSize>65536&&(e.dictSize=65536),e.dictSize<4&&(e.dictSize=0),e.dictionaryStart=c-e.dictSize);var h=e.dictSize<65536&&e.dictSize<e.currentOffset?Wh:Vh;return e.dictionary&&c===s?(u=ap(e,t,r,s,n,i||0,a||!1,jh.byU32,Kh,h),e.dictSize+=n,e.currentOffset+=n,u):(u=ap(e,t,r,s,n,i||0,a||!1,jh.byU32,Hh,h),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function gp(e,t,r,s){var n=e.dictionaryStart+e.dictSize;s>65536&&(s=65536),s>e.dictSize&&(s=e.dictSize);var o=n-s;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(o,o+s),r);else for(var i=0;i<s;i++)t[r+i]=e.dictionary[o+i];return e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,s}function yp(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function vp(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function bp(e,t,r,s,n,o,i){var a;if(e.prefixEnd===o){if((a=hp(t,r,s,n,o,i,!0,0,0,Hh,e.prefixEnd-e.prefixSize,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize+=a,e.prefixEnd+=a}else{if(e.extDictSize=e.prefixSize,e.extDictStart=e.prefixEnd-e.extDictSize,(a=hp(t,r,s,n,o,i,!0,0,0,Hh,o,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=o+a}return a}function Ip(e){var t=(e=e||{}).minWorkArea||$h,r=e.maxWorkArea||qh,s=e.shrinkThreshold||t;t<$h&&(t=$h),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Dh+t,this.maxBufferSize=Dh+r,this.shrinkThreshold=Dh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Gh.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=pp()}function wp(e){var t=(e=e||{}).minWorkArea||$h,r=e.maxWorkArea||qh,s=e.shrinkThreshold||t;t<$h&&(t=$h),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Dh+t,this.maxBufferSize=Dh+r,this.shrinkThreshold=Dh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Gh.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Ip.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Dh?this.offset:Dh,n=this.offset>Dh?this.offset-Dh:0;t.set(this.ringBuffer.subarray(n,n+s),0),gp(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},Ip.prototype.compress=function(e,t){var r=e.length;if(r<=0)return Bh.PARAM_ERROR;if(r>this.maxBufferSize-Dh)return Bh.PARAM_ERROR;if(r>this.ringBufferSize-Dh){var s=Fh(r),n=Dh+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Bh.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(gp(this.stream,this.ringBuffer,0,Dh),this.offset=Dh);var o=this.offset;this.ringBuffer.set(e,o);var i=fp(this.stream,this.ringBuffer,t,o,r,0,t.length,!0);return i<=0?Bh.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),i)},Ip.prototype.reset=function(){this.offset=0,mp(this.stream)},Ip.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Ip.prototype._tryAutoShrink=function(){this.shrinkMode!==Gh.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Gh.AUTO_IMMEDIATE||this.shrinkMode===Gh.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Ip.prototype.getWorkArea=function(){return this.ringBufferSize-Dh},Ip.prototype.getRingBufferSize=function(){return this.ringBufferSize},Ip.prototype.getBaseBufferSize=function(){return this.minBufferSize},Ip.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Ip.prototype.getCurrentOffset=function(){return this.offset},Ip.prototype.getShrinkMode=function(){return this.shrinkMode},Ip.prototype.setShrinkMode=function(e){this.shrinkMode=e},Ip.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Ip.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Dh,r=this.maxBufferSize-Dh;if(e<t||e>r)return Bh.PARAM_ERROR;this.shrinkThreshold=Dh+e},wp.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Dh?this.offset:Dh,n=this.offset>Dh?this.offset-Dh:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,vp(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},wp.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return Bh.PARAM_ERROR;if(r>this.maxBufferSize-Dh)return Bh.PARAM_ERROR;if(r>this.ringBufferSize-Dh){var n=Fh(r),o=Dh+n;if(o>this.maxBufferSize&&(o=this.maxBufferSize),!this._resizeBuffer(o))return Bh.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var i=this.offset-Dh;i>0&&this.ringBuffer.set(this.ringBuffer.subarray(i,i+Dh),0),vp(this.streamDecode,this.ringBuffer,0,Dh),this.offset=Dh}var a=bp(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?Bh.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},wp.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},wp.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},wp.prototype._tryAutoShrink=function(){this.shrinkMode!==Gh.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Gh.AUTO_IMMEDIATE||this.shrinkMode===Gh.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},wp.prototype.getWorkArea=function(){return this.ringBufferSize-Dh},wp.prototype.getRingBufferSize=function(){return this.ringBufferSize},wp.prototype.getBaseBufferSize=function(){return this.minBufferSize},wp.prototype.getMaxBufferSize=function(){return this.maxBufferSize},wp.prototype.getCurrentOffset=function(){return this.offset},wp.prototype.getShrinkMode=function(){return this.shrinkMode},wp.prototype.setShrinkMode=function(e){this.shrinkMode=e},wp.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},wp.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Dh,r=this.maxBufferSize-Dh;if(e<t||e>r)return Bh.PARAM_ERROR;this.shrinkThreshold=Dh+e};const Cp={LZ4_MAX_INPUT_SIZE:Ph,BLOCK_MAX_SIZE:65536,DICT_SIZE:Dh,DEFAULT_WORK_AREA:$h,DEFAULT_MAX_WORK:qh,SHRINK_MODE:Gh,LZ4_ERROR:Bh,alignToPowerOf2:Fh,calcDefaultBufferSize:function(){return 131072},calcDefaultMaxBufferSize:function(){return 10551296},setHashStrategy:function(e){if("fast"!==e&&"compatible"!==e)throw new Error("Invalid hash strategy: "+e+'. Use "fast" or "compatible".');Yh=e},getHashStrategy:function(){return Yh},compress:function(e,t,r,s,n){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0)return 0;if(r+s>e.length)return 0;if(s>Ph)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var o=s<xh?jh.byU16:jh.byU32;return ap({hashTable:new Uint32Array(o===jh.byU16?8192:Oh),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,o,zh,Vh)},compressLimited:function(e,t,r,s,n,o){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0||o<0)return 0;if(r+s>e.length)return 0;if(s>Ph)return 0;if(o<1)return 0;if(0===s)return t[n]=0,1;var i=s<xh?jh.byU16:jh.byU32;return ap({hashTable:new Uint32Array(i===jh.byU16?8192:Oh),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,o,!0,i,zh,Vh)},compressBound:function(e){return e<0||e>Ph?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,r,s,n,o){return null==e||null==t?-1:(n=n||0,(r=r||0)<0||n<0||s<0||o<0||r+s>e.length||n+o>t.length?-1:hp(e,t,r,s,n,o,!0,0,0,zh,n,null,0))},decompressFast:function(e,t,r,s,n){return hp(e,t,r=r||0,0,s=s||0,n,!1,0,0,Kh,s-65536,0,65536)},createStream:pp,resetStream:mp,loadDict:function(e,t,r,s){if(e.initCheck&&mp(e),s<4)return e.dictionary=null,e.dictSize=0,0;s>65536&&(r=r+s-65536,s=65536);var n=r-e.currentOffset;e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,e.currentOffset+=s;for(var o=r,i=r+s;o<=i-4;)sp(t,o,e.hashTable,jh.byU32,n),o+=3;return s},compressContinue:fp,saveDict:gp,createStreamDecode:yp,setStreamDecode:vp,decompressSafeContinue:bp,RingBufferEncoder:Ip,RingBufferDecoder:wp,_hashU16:ep,_hashU32:Xh,_TABLE_TYPE:jh},Sp=268435455,Tp=new Uint32Array(256);let _p=!1;function Rp(e){!function(){if(!_p){for(let e=0;e<256;e+=1){let t=e;for(let e=0;e<8;e+=1)t=1&t?3988292384^t>>>1:t>>>1;Tp[e]=t>>>0}_p=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(Tp[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var Ap=(e=>(e[e.NONE=-1]="NONE",e[e.UPLINK_ONLY=0]="UPLINK_ONLY",e[e.DOWNLINK_ONLY=1]="DOWNLINK_ONLY",e[e.BIDIRECTIONAL=2]="BIDIRECTIONAL",e))(Ap||{});const Mp=268435455;class Ep{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Cp.DEFAULT_WORK_AREA,maxWorkArea:Cp.DEFAULT_MAX_WORK,shrinkMode:Cp.SHRINK_MODE.MANUAL};this.encoder=new Cp.RingBufferEncoder(e),this.decoder=new Cp.RingBufferDecoder(e)}compress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length>Mp)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=Cp.compressBound(t.length),s=new Uint8Array(r),n=this.encoder.compress(t,s);if(n<0)throw new Error(`LZ4 compression failed with error code: ${n}`);const o=s.subarray(0,n),i=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>Sp)throw new Error("encodeLength: Length exceeds maximum: 268435455");if(0===e)return new Uint8Array([0]);const t=[];let r=e;for(;r>0;){let e=127&r;r>>>=7,r>0&&(e|=128),t.push(e)}return new Uint8Array(t)}(t.length),a=Rp(t),c=new Uint8Array(i.length+4+n);let d=0;c.set(i,d),d+=i.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(o,d),c}decompress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length<5)throw new Error("Compressed data is too short: must contain at least length and CRC32");const r={offset:0},s=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let r=0,s=0;for(;t.offset<e.length;){const n=e[t.offset]??0;if(t.offset+=1,r|=(127&n)<<s,!(128&n))return r>>>0;if(s+=7,s>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,r);if(s>Mp)throw new Error(`Original size exceeds maximum allowed: ${s}`);if(t.length<r.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const n=new DataView(t.buffer,t.byteOffset+r.offset,4).getUint32(0,!1);r.offset+=4;const o=t.subarray(r.offset),i=new Uint8Array(s),a=this.decoder.decompress(o,i,s);if(a<0||a!==s)throw new Error(`LZ4 decompression failed: expected ${s}, got ${a}`);const c=Rp(i);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return i}reset(){this.encoder.reset(),this.decoder.reset()}}const Up=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),kp=(e,t)=>rd(e,t).finish();class Np{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=cl({useFixedDeviceId:e.useFixedDeviceId??!0,deviceId:e.deviceId??"webim",customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform}),r=`${Date.now()}:`;return{appKey:e.appKey,userId:e.userId,token:e.token,domain:e.domain??"easemob.com",version:e.version??"4.11.0",uiKitVersion:e.uiKitVersion,osType:void 0!==e.customOSPlatform?5:e.osType??16,deviceId:t.deviceId,deviceName:t.deviceName,deviceUuid:t.deviceUuid,clientResource:t.deviceId,customOSPlatform:e.customOSPlatform,loginExtensionInfo:e.loginExtensionInfo,encryptType:[Gs],compressType:[Bs],sessionId:r,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.useCustomAttachmentUpload=e.useCustomAttachmentUpload??!1}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=nl(),t=e.lookupType("easemob.pb.Provision"),r=e.lookupType("easemob.pb.MSync"),s={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[Bs],encryptType:[Gs],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,auth:`$t$${this.context.token}`,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},n=kp(t,s),o={version:0,guid:dl({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),auth:`$t$${this.context.token}`,command:is,deviceId:0,encryptType:[Gs],payload:n,traceId:pl()};return kp(r,o)}encodeHeartbeat(){const e=nl(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=kp(t,{}),n={version:0,encryptType:[Gs],command:ns,payload:s,traceId:pl()};return kp(r,n)}encodeStatisticRebuild(){const e=nl(),t=e.lookupType("easemob.pb.StatisticsBody"),r=e.lookupType("easemob.pb.Meta"),s=e.lookupType("easemob.pb.CommSyncUL"),n=e.lookupType("easemob.pb.MSync"),o=kp(t,{operation:0}),i=r.decode(new Uint8Array);i.id=Date.now(),i.ns=Ns,i.payload=o;const a=s.decode(new Uint8Array);a.meta=i;const c=kp(s,a);return kp(n,{version:0,encryptType:[Gs],command:ss,payload:c,traceId:pl()})}decodeProvision(e){const t=nl().lookupType("easemob.pb.Provision").decode(e),r=t.status??{},s="number"==typeof r.errorCode?r.errorCode:zs,n="string"==typeof r.reason?r.reason:void 0,o="string"==typeof t.resource?t.resource:void 0,i="string"==typeof t.authToken?t.authToken:void 0,a=Array.isArray(t.protocolCompressType)?t.protocolCompressType:void 0,c="number"==typeof t.protocolCompressDirection?t.protocolCompressDirection:void 0;return this.configureCompression(a,c),{ok:s===js,statusCode:s,reason:n,resource:o,authToken:i,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=nl().lookupType("easemob.pb.Logout").decode(e),r=t.status&&"object"==typeof t.status?t.status:void 0;return{sessionId:"string"==typeof t.sessionId?t.sessionId:void 0,reason:"string"==typeof t.reason?t.reason:void 0,statusCode:"number"==typeof r?.errorCode?r.errorCode:void 0}}decodeSyncStatisticOperations(e){const t=nl().lookupType("easemob.pb.CommSyncDL").decode(e),r=Array.isArray(t.metas)?t.metas:[],s=[];for(const n of r){const e=this.decodeStatisticMeta(n);e&&s.push(e)}return s}decodeMsync(e){const t=nl().lookupType("easemob.pb.MSync").decode(e);return{command:"number"==typeof t.command?t.command:-1,payload:this.normalizeBinaryPayload(t.payload)}}normalizeBinaryPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array}decodeSync(e){const t=nl(),r=t.lookupType("easemob.pb.CommSyncDL"),s=t.lookupType("easemob.pb.MessageBody"),n=r.decode(e);So("decodeSync commSyncDl",{hasMetas:Array.isArray(n.metas)});const o=Array.isArray(n.metas)?n.metas:[],i=this.decodeAck(n);i?.ok&&(i.chatRoomInfo=this.decodeChatRoomJoinInfo(o));const a=ul(n.metaId),c=ul(n.nextKey),d=n.queue??void 0,u="boolean"==typeof n.isLast?n.isLast:void 0,l=[],h=[];if(a&&"0"!==a){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(o,s):void 0;for(const t of o){const e=this.decodeNotifyMeta(t);e.length>0&&h.push(...e)}return{ack:i,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u,replacedMessage:e}}for(const p of o){const e=this.decodeChatMeta(p,s);e&&l.push(e);const t=this.decodeChatActionMeta(p,s);t&&h.push(t);const r=this.decodeNotifyMeta(p);r.length>0&&h.push(...r)}return{ack:i,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u}}decodeReplacedMessage(e,t){for(const r of e){const e=this.decodeChatMeta(r,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Os)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e;return this.decodeMessage(r,s)}catch{return null}}decodeChatActionMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Os)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e,o="number"==typeof s.type?s.type:cs;if(o!==hs&&o!==ms&&o!==fs&&o!==gs&&o!==ps)return null;const i=this.readJid(r.to),a=Number(ul(r.timestamp))||Date.now(),c=this.resolveActionConversationType(i.domain,s.meta,s),{senderId:d,receiverId:u}=this.resolveIncomingMessageParties(r,s,c),l=this.resolveActionConversationId(d,u,c);if(o===fs)return!0===s.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:a}}:l?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a}}:null;if(o===hs){So("Received READ_ACK MessageBody",s);const e=(Array.isArray(s.ackMessageIds)?s.ackMessageIds:[]).map(e=>ul(e)).filter(e=>Boolean(e)),t=ul(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=hl(Array.isArray(s.ext)?s.ext.filter(Up):void 0),n=Up(r.group_ack_count)?r.group_ack_count:{},o=e.flatMap(e=>{const t=n[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a,..."groupChat"===c?{receiptDetails:o}:{}}}}if(o===ps){const e=ul(s.ackMessageId);return e&&l?{type:"message_delivered",data:{messageId:e,from:d,to:u,conversationId:l,conversationType:"singleChat"}}:null}if(o===ms){const e=ul(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const h=ul(s.editMessageId),p=(Array.isArray(s.contents)?s.contents:[])[0],m=p?this.decodeContent(p):null;if(!h||!l||!m)return null;const f=this.resolveModifiedInfo(s.meta);return{type:"message_updated",data:{messageId:h,conversationId:l,conversationType:c,timestamp:a,message:{type:m.type,body:m.body,ext:hl(s.ext),...f?{modifiedInfo:f}:{}}}}}catch{return null}}decodeNotifyMeta(e){if(!e||"object"!=typeof e)return[];const t=e,r="number"==typeof t.ns?t.ns:void 0;if(r!==Ps&&r!==Ls&&r!==xs&&r!==Ns)return[];const s=t.payload;let n=null;return s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),n?r===Ls?this.decodeRosterMeta(t,n):r===xs?this.decodeMucMeta(t,n):r===Ns?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const r=nl(),s=r.lookupType("easemob.pb.StatisticsBody").decode(t);if("string"!=typeof s.location||0===s.location.length)return[];const n=JSON.parse(s.location);if(!Up(n)||!Array.isArray(n.group_ack))return[];const o=this.readMetaTimestamp(e)??Date.now(),i=new Map;for(const e of n.group_ack){if(!Up(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[r,s]of Object.entries(e)){if("groupId"===r)continue;const e="number"==typeof s?s:"string"==typeof s&&s.trim().length>0?Number(s):Number.NaN;!r||!Number.isInteger(e)||e<0||i.set(r,{conversationId:t,count:e})}}return So("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(i,([e,{conversationId:t,count:r}])=>({messageId:e,conversationId:t,count:r}))}),Array.from(i,([e,{conversationId:t,count:r}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:o,receiptDetails:[{messageId:e,count:r}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==Ns)return null;const r=t.payload;let s=null;if(r instanceof Uint8Array?s=r:r instanceof ArrayBuffer?s=new Uint8Array(r):ArrayBuffer.isView(r)&&(s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!s)return null;try{const e=nl(),t=e.lookupType("easemob.pb.StatisticsBody").decode(s);return{operation:"number"==typeof t.operation?t.operation:-1,reason:"string"==typeof t.reason?t.reason:void 0}}catch{return null}}decodeRosterMeta(e,t){try{const r=nl(),s=r.lookupType("easemob.pb.RosterBody").decode(t),n="number"==typeof s.operation?s.operation:-1,o=this.readRosterJid(s.from),i=this.readRosterJidList(s.to),a="string"==typeof s.reason?s.reason:"",c="string"==typeof s.rosterVer&&s.rosterVer.trim().length>0?s.rosterVer:void 0,d=o.name??"",u=i[0]?.name??"";if(!d&&!u)return[];const l=Th({operation:n,from:o,to:i,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(l)return[this.createMultiDeviceNotify(l)];const h=this.mapRosterOperationToEvent(n,{from:d,to:u,message:a,rosterVersion:c});return h?[{type:"contact",eventName:h.eventName,data:h.payload}]:[]}catch{return[]}}readRosterJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0}}readRosterJidList(e){return Array.isArray(e)&&0!==e.length?e.map(e=>this.readRosterJid(e)):[]}readJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0,domain:"string"==typeof t.domain?t.domain:void 0}}decodeMucMeta(e,t){try{const r=nl(),s=r.lookupType("easemob.pb.MUCBody").decode(t),n="number"==typeof s.operation?s.operation:-1,o=!0===s.isChatroom,i=!0===s.isThread,a=this.readJid(s.from),c=Array.isArray(s.to)?s.to.map(e=>this.readJid(e)):[],d=s.eventInfo&&"object"==typeof s.eventInfo?s.eventInfo:void 0,u=Array.isArray(s.members)?s.members.filter(e=>"string"==typeof e):[],l=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(i){const t=Rh({operation:n,threadId:this.readJid(s.mucId).name??"",threadName:"string"==typeof s.mucName?s.mucName:void 0,parentId:this.readJid(s.mucParentId).name??void 0,from:a,to:c,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const r=37===n&&c.some(e=>e.name===this.context.userId),o=this.readJid(s.mucId).name??"",i=this.readJid(s.mucParentId).name??"";return r&&o&&i?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:o,name:"string"==typeof s.mucName?s.mucName:void 0,muc_parent_id:i,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!o){const t=_h({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=o?Tl({operation:n,chatRoomId:this.readJid(s.mucId).name??"",chatRoomName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u}):sh({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u,source:l});return h?[{type:o?"chatroom":"group",eventName:o?"onChatRoomNotify":"onGroupNotify",data:h}]:[]}catch{return[]}}mapRosterOperationToEvent(e,t){const r={from:t.from,to:t.to,message:t.message,userInfo:{userId:t.from||t.to}};switch(((e,t)=>{t&&ch.set(e,t)})(r,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:r};case 3:return{eventName:"onContactDeleted",payload:r};case 4:return{eventName:"onContactAdded",payload:r};case 5:case 9:return{eventName:"onContactRefuse",payload:r};case 8:return{eventName:"onContactAgreed",payload:r};default:return null}}decodeNotifyPayload(e){try{let t="";for(let o=0;o<e.length;o+=1){const r=e[o];if(void 0===r)return[];t+=`%${r.toString(16)}`}const r=decodeURIComponent(t),s=JSON.parse(r);So("Decoded MSync notify payload",{payload:s});const n="string"==typeof s.type?s.type:"";if(!n)return[];if("thread"===n){return[{type:n,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:Up(s.data)?s.data:s}}]}if("conv"===n){const e=Up(s.data)?s.data:s,t=[],r="string"==typeof e.op?e.op:"";if("pin"===r||"pin_delete"===r)return[{type:n,eventName:"onPinnedMessageChanged",data:e}];const o=Ah({operation:r,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return o&&t.push(this.createMultiDeviceNotify(o)),t}if("roaming_delete"===n){const e=Up(s.data)?s.data:s,t=Mh({chatType:"string"==typeof e.chatType?e.chatType:void 0,to:"string"==typeof e.to?e.to:void 0,resource:"string"==typeof e.resource?e.resource:void 0,msgIdList:Array.isArray(e.msgIdList)?e.msgIdList.filter(e=>"string"==typeof e):void 0,deleteTime:e.deleteTime,lastMsgId:"string"==typeof e.lastMsgId?e.lastMsgId:void 0,messageRoamingType:"string"==typeof e.messageRoamingType?e.messageRoamingType:void 0,raw:e},this.msyncCodecContext());return t?[this.createMultiDeviceNotify(t)]:[]}if("user_notification_mute"===n){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const r=[];for(const s of e){if(!vh(s))continue;const e=bh(s.operator_resource,s.resource,s.clientResource);if(Ih(e,t.clientResource))continue;const n=fh(s.group)??fh(s.user);if(!n||!vh(s.data))continue;const o=fh(s.group)?mh:ph,i=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:o,remindType:fh(i.type),silentMode:i,deviceId:e,raw:s})}return r})(Up(s.data)&&Array.isArray(s.data.values)?s.data.values:Array.isArray(s.values)?s.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:n,data:s.data??s}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,r=Number(ul(t));if(Number.isFinite(r)&&r>0)return r}msyncCodecContext(){return{userId:this.context.userId,clientResource:this.context.clientResource}}createMultiDeviceNotify(e){return{type:"multiDevice",eventName:Eh(e.category),data:e}}decodeNotice(e){const t=nl().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=nl().lookupType("easemob.pb.CommUnreadDL").decode(e);return{queues:(Array.isArray(t.unread)?t.unread:[]).map(e=>e&&"object"==typeof e?e:null).map(e=>e?.queue&&"object"==typeof e.queue?e.queue:null).filter(e=>Boolean(e))}}encodeBackQueue(e){const t=nl(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=kp(r,{queue:e}),o={version:0,encryptType:[Gs],command:ss,payload:n,traceId:pl()};return kp(s,o)}encodeLastSession(e,t){const r=nl(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),o=kp(s,{queue:e,key:t}),i={version:0,encryptType:[Gs],command:ss,payload:o,traceId:pl()};return kp(n,i)}encodeChatMessage(e,t){const r=nl(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i=this.buildContent(e),a=this.resolveMessageProfileVersionFields(e),c=this.buildMessageMeta(e),d=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),u={type:this.resolveChatType(e),from:{name:this.context.userId},to:{name:d.name},contents:[i],ext:ll(e.ext??{}),...c?{meta:c}:{},...a,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=kp(s,u),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e),f={id:t,to:dl({appKey:this.context.appKey,name:d.name,domain:h,clientResource:d.clientResource}),ns:Os,payload:l,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}},g=kp(n,{meta:f}),y={version:0,encryptType:[Gs],command:ss,payload:g,traceId:pl()};return kp(o,y)}encodeActionMessage(e,t){const r=nl(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i=r.lookupEnum("easemob.pb.MessageBody.EditScope"),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:t,from:this.context.userId,to:e.conversationId,sender:{userId:this.context.userId},conversationId:e.conversationId,conversationType:e.conversationType,type:e.messageType,sendStatus:"sending",ext:e.ext??{},timestamp:Date.now(),body:e.body})]:[],d={type:this.resolveActionMessageType(e),from:{name:this.context.userId},to:{name:a.name},contents:c,ext:ll(e.ext??{})};"recall"!==e.kind&&"deliveryAck"!==e.kind||(d.ackMessageId=e.messageId),"sendMessageReadReceipts"===e.kind&&(d.ackMessageIds=e.messageIds,"groupChat"===e.conversationType&&(d.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1,d.clearAllUnreadMessageCount=e.clearAllUnreadMessageCount??!0),"update"===e.kind&&(d.editMessageId=e.messageId,d.editScope=e.ext&&Object.keys(e.ext).length>0?i.values.BODY_AND_EXT:i.values.BODY);const u=kp(s,d);if("clearAllConversationUnreadMessageCount"===e.kind){const e=s.decode(u),r=s.fields.clearAllUnreadMessageCount;So("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:d.type,fieldId:r?.id,requestedValue:d.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(e,"clearAllUnreadMessageCount"),decodedValue:e.clearAllUnreadMessageCount,messageBodyBytes:u.byteLength,wireTailHex:Array.from(u.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const l={id:t,to:dl({appKey:this.context.appKey,name:a.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:a.clientResource}),ns:Os,payload:u,routetype:Ds,directedUsers:[],ext:[]},h=kp(n,{meta:l}),p={version:0,encryptType:[Gs],command:ss,payload:h,traceId:pl()};return kp(o,p)}encodeChatRoomOperation(e,t){const r=nl(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i={mucId:dl({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(i.ext=e.ext),void 0!==e.leaveOtherRooms&&(i.leaveOtherRooms=e.leaveOtherRooms));const a=kp(s,i),c={id:t,from:dl({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:xs,payload:a},d=kp(n,{meta:c}),u={version:0,encryptType:[Gs],command:ss,payload:d,traceId:pl()};return kp(o,u)}decodeServerMessageMeta(e){const t=nl(),r=t.lookupType("easemob.pb.Meta"),s=t.lookupType("easemob.pb.MessageBody");try{const t=r.decode(e);return this.decodeChatMeta(t,s)}catch{return null}}async normalizeIncoming(e){if(e instanceof Uint8Array)return e;if(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))return new Uint8Array(e);var t;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if((e=>"undefined"!=typeof Blob&&e instanceof Blob||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e)){const t=await e.arrayBuffer();return new Uint8Array(t)}return"string"==typeof e?Ro(e):e&&"object"==typeof e&&"data"in e?this.normalizeIncoming(e.data):new Uint8Array}decompressIncoming(e){if(!this.compressor||!this.compressor.enableDownlinkCompression)return e;try{return this.compressor.decompress(e)}catch{return this.compressionFailureCount+=1,null}}prepareOutgoing(e){if(!this.compressor||!this.compressor.enableUplinkCompression)return e;try{return this.compressor.compress(e)}catch{throw this.compressionFailureCount+=1,new Error("compress outgoing message failed")}}resetCompressionNegotiation(){this.compressor?.reset(),this.disableCompression()}toProtocolId(e){return(e=>{if(/^\d+$/.test(e))return e;const t=mi.fromString("1099511628211",!0);let r=mi.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(mi.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()})(e)}decodeChatRoomJoinInfo(e){const t=nl().lookupType("easemob.pb.MUCBody");for(const s of e){if(!Up(s)||s.ns!==xs)continue;const e=s.payload,n=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(n)try{const e=t.decode(n);if(!Up(e)||!Up(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!Up(s))continue;const o=s[this.context.userId];if(!Up(o))continue;const i=o;return{..."boolean"==typeof i.is_all_mute?{isAllMembersMuted:i.is_all_mute}:{},..."number"==typeof i.create_timestamp?{createTimestamp:i.create_timestamp}:{},..."boolean"==typeof i.is_in_white_list?{isInAllowlist:i.is_in_white_list}:{},..."number"==typeof i.member_count?{memberCount:i.member_count}:{},muteExpireTimestamp:"number"==typeof i.mute_duration&&0!==i.mute_duration?i.mute_duration:-1}}catch(r){_o("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=ul(e.metaId);if(!t||"0"===t)return;const r=e.status??{},s="number"==typeof r.errorCode?r.errorCode:zs,n="string"==typeof r.reason?r.reason:void 0;return{protocolId:t,serverId:ul(e.serverId),ok:s===js,statusCode:s,reason:n}}decodeMessage(e,t){const r="number"==typeof t.type?t.type:ds;if(!this.isPublicMessageType(r))return null;const s=(Array.isArray(t.contents)?t.contents:[])[0];if(!s)return null;const n=this.resolveConversationType(r),{senderUserId:o,senderId:i,receiverId:a}=this.resolveIncomingMessageParties(e,t,n),c=i===this.context.userId?"SEND":"RECEIVE",d="singleChat"===n?"SEND"===c?a:i:a,u=this.decodeContent(s);if(!u)return null;const l=hl(t.ext),h=hl(e.ext),p=Number(ul(e.timestamp))||Date.now(),m=ul(e.id),f=this.resolveBroadcast(h),g=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),v=this.resolveContentReplaced(y),b=this.resolveReactions(y),I=this.resolveModifiedInfo(y),w=this.resolveChatThreadMessageContext(y),C=this.resolveChatThreadOverview(y),S=this.resolveProfileVersionTime(t.userInfoUpdateTime),T=this.resolveProfileVersionTime(t.namecardUpdateTime),_={msgServerId:m,msgLocalId:"",from:i,to:a,sender:{userId:o},conversationId:d,conversationType:n,type:u.type,sendStatus:"sent",ext:l,timestamp:p,body:u.body,direct:c,isOnline:this.resolveMessageIsOnline(r,h)};oh(_,{userInfoUpdateTime:S,namecardUpdateTime:T});const R=this.decodeStreamMeta(t.stream,s);R&&(_.type="text",_.body={content:R.fullText},_.stream=R),void 0!==f&&(_.isBroadcast=f),void 0!==g&&(_.priority=g),void 0!==v&&(_.isContentReplaced=v),b&&(_.reactions=b),I&&(_.modifiedInfo=I),w&&(_.isChatThread=!0,_.chatThread=w);const A=this.resolvePeerRead(y,n,c);void 0!==A&&(_.isPeerRead=A);const M=this.resolveGroupReadCount(y,n);void 0!==M&&(_.groupReadCount=M),C&&(_.chatThreadOverview=C);const E=t.msgConfig;return E?.allowGroupAck&&(_.needReadReceipt=!0),_}resolveMessageProfileVersionFields(e){const t=ih(e),r={};return"number"==typeof t?.userInfoUpdateTime&&(r.userInfoUpdateTime=t.userInfoUpdateTime),"groupChat"===e.conversationType&&"number"==typeof t?.namecardUpdateTime&&(r.namecardUpdateTime=t.namecardUpdateTime),r}buildMessageMeta(e){const t={};return e.isChatThread&&(t.thread={}),Object.keys(t).length>0?JSON.stringify(t):""}resolveProfileVersionTime(e){return kh(ul(e))}isPublicMessageType(e){return e===ds||e===us||e===ls}resolveMessageIsOnline(e,t){if(e===ls)return!0;const r=t.is_online;return"boolean"==typeof r?r:"number"==typeof r?0!==r:"string"!=typeof r||"0"!==r}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const r=e,s=Number(ul(r.streamSeq));if(!Number.isFinite(s))return;const n="number"==typeof r.streamStatus?r.streamStatus:Ms,o="number"==typeof r.streamError?r.streamError:0,i="number"==typeof r.streamFinishReason?r.streamFinishReason:void 0,a=this.resolveContentText(t),c=a;return{customType:"string"==typeof r.streamType?r.streamType:void 0,seq:s,status:this.mapStreamStatus(n,o),errorType:o,finishReason:i,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?rt.ERROR:e===Rs?rt.START:e===As?rt.START_COMPLETED:e===Es?rt.COMPLETED:e===Us?rt.FULL:rt.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}buildContent(e){if("text"===e.type){const t=e.body;return{type:ys,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:Ss,action:t.action}}if("custom"===e.type){const t=e.body;return{type:Ts,customEvent:t.event,customExts:ll(t.params??{})}}if("location"===e.type){const t=e.body;return{type:Is,latitude:t.latitude,longitude:t.longitude,address:t.address,buildingName:t.buildingName}}if("image"===e.type){const r=e.body,s=r.isGif||r.isOriginalImage?"original":"large";return{type:vs,displayName:r.filename,remotePath:r.originalImageUrl??"",imageType:(t=s,t===Wn?1:2),secretKey:r.secret,fileLength:r.fileLength,size:{width:r.width,height:r.height},subType:r.isGif?1:void 0,thumbnailRemotePath:r.thumbnailUrl,thumbnailDisplayName:r.filename}}var t;if("video"===e.type){const t=e.body;return{type:bs,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,size:t.width&&t.height?{width:t.width,height:t.height}:void 0,thumbnailRemotePath:t.thumbnailUrl,thumbnailSecretKey:t.secret,thumbnailDisplayName:t.filename}}if("voice"===e.type){const t=e.body;return{type:ws,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,thumbnailDisplayName:t.filename}}if("combine"===e.type){const t=e.body;return{type:ys,subType:0,text:lh(e)??"版本过低",displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,title:t.title,summary:t.summary,combineLevel:t.combineLevel}}const r=e.body;return{type:Cs,displayName:r.filename,remotePath:r.url,secretKey:r.secret,fileLength:r.fileLength,thumbnailDisplayName:r.filename}}decodeContent(e){const t="number"==typeof e.type?e.type:ys,r="string"==typeof e.remotePath&&e.remotePath.length>0||"string"==typeof e.title&&e.title.length>0||"string"==typeof e.summary&&e.summary.length>0||"number"==typeof e.combineLevel&&e.combineLevel>0,s=Object.prototype.hasOwnProperty.call(e,"subType")&&0===e.subType;if(t===_s||t===ys&&(s||r)){return{type:"combine",body:{title:"string"==typeof e.title?e.title:"",summary:"string"==typeof e.summary?e.summary:"",filename:"string"==typeof e.displayName?e.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof e.remotePath?e.remotePath:void 0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,combineLevel:"number"==typeof e.combineLevel?e.combineLevel:0}}}if(t===ys)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===Ss)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===Ts){const t=hl(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===Is)return{type:"location",body:{latitude:"number"==typeof e.latitude?e.latitude:0,longitude:"number"==typeof e.longitude?e.longitude:0,address:"string"==typeof e.address?e.address:void 0,buildingName:"string"==typeof e.buildingName?e.buildingName:void 0}};if(t===vs){const t=e.size??{},r="number"==typeof t.width?t.width:0,s="number"==typeof t.height?t.height:0,n=io(e.imageType)===Wn,o="string"==typeof e.remotePath?e.remotePath:"",i=no(o,{deriveVariants:!this.useCustomAttachmentUpload}),a="string"==typeof e.thumbnailRemotePath&&e.thumbnailRemotePath.length>0?e.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof e.displayName?e.displayName:"image",filetype:"application/octet-stream",width:r,height:s,isGif:1===e.subType,isOriginalImage:n,originalImageUrl:i.originalImageUrl,bigImageUrl:i.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:a??i.thumbnailUrl}}}if(t===bs){const t=e.size??{},r="number"==typeof t.width?t.width:void 0,s="number"==typeof t.height?t.height:void 0,n="string"==typeof e.thumbnailRemotePath?e.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,width:r,height:s,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:n}}}if(t===ws){return{type:"voice",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}if(t===Cs){return{type:"file",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}return null}resolveChatType(e){switch(e.conversationType){case"groupChat":return us;case"chatRoom":return ls;default:return ds}}resolveActionConversationType(e,t,r){const s=this.resolveConversationTypeFromMeta(t);if(s)return s;const n=r?.msgConfig&&"object"==typeof r.msgConfig?r.msgConfig:null;return!0===n?.allowGroupAck||"conference.easemob.com"===e?"groupChat":"singleChat"}resolveConversationTypeFromMeta(e){if("string"!=typeof e||0===e.length)return null;try{const t=JSON.parse(e),r=t.edit_msg&&"object"==typeof t.edit_msg?t.edit_msg:void 0,s=("string"==typeof t.chat_type?t.chat_type:void 0)??("string"==typeof t.chatType?t.chatType:void 0)??("string"==typeof t.type?t.type:void 0)??("string"==typeof r?.chat_type?r.chat_type:void 0);if("chat:user"===s||"singleChat"===s)return"singleChat";if("chat:group"===s||"groupChat"===s)return"groupChat";if("chat:room"===s||"chatRoom"===s)return"chatRoom"}catch{}return null}resolveActionConversationId(e,t,r){return"singleChat"===r?e===this.context.userId?t:e:t}resolveOutboundMessageTarget(e,t){if("singleChat"!==t)return{name:e};const r=`${this.context.userId}/`;if(!e.startsWith(r))return{name:e};const s=e.slice(r.length);return s?{name:this.context.userId,clientResource:s}:{name:e}}resolveIncomingMessageParties(e,t,r){const s=this.readJid(e.from),n=this.readJid(e.to),o=this.readJid(t.from),i=this.readJid(t.to),a=o.name??s.name??"",c=i.name??n.name??"";if(!("singleChat"===r&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:s.clientResource&&s.clientResource!==this.context.clientResource?`${a}/${s.clientResource}`:a,receiverId:n.clientResource?`${c}/${n.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return fs;case"sendMessageReadReceipts":return hs;case"deliveryAck":return ps;case"recall":return ms;case"update":return gs;default:return ds}}resolveConversationType(e){return e===us?"groupChat":e===ls?"chatRoom":"singleChat"}resolveDirectedUsers(e){return"singleChat"===e.conversationType?[]:Array.isArray(e.receiverList)?e.receiverList:[]}resolveDeliverOnlineOnly(e){if("boolean"==typeof e.deliverOnlineOnly)return e.deliverOnlineOnly;if("cmd"===e.type){const t=e.body;return Boolean(t.deliverOnlineOnly)}return!1}resolveMetaExt(e){return"chatRoom"!==e.conversationType?[]:e.priority?ll({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?qs:this.resolveDeliverOnlineOnly(e)?$s:Ds}resolveBroadcast(e){if(!Object.prototype.hasOwnProperty.call(e,"is_broadcast"))return;const t=e.is_broadcast;return"boolean"==typeof t?t:"number"==typeof t?0!==t:"string"==typeof t?"1"===t||"true"===t.toLowerCase():Boolean(t)}resolvePriority(e){if(!Object.prototype.hasOwnProperty.call(e,"chatroom_msg_tag"))return;const t=Number(e.chatroom_msg_tag);return 0===t?"high":2===t?"low":"normal"}resolveContentReplaced(e){const t=this.parseMetaPayload(e);if(t&&Object.prototype.hasOwnProperty.call(t,"callback_replace"))return Boolean(t.callback_replace)}resolveMessageMetaPayload(e,t){const r=this.parseMetaPayload(e),s=this.parseMetaPayload(t);return r&&s?{...s,...r}:r??s??e??t}resolvePeerRead(e,t,r){if("singleChat"!==t||"SEND"!==r)return;const s=this.parseMetaPayload(e);return"boolean"==typeof s?.isRead?s.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const r=this.parseMetaPayload(e),s=r?.group_read_ack;return"number"==typeof s&&Number.isInteger(s)&&s>=0?s:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),r=t?.edit_msg;if(!Up(r))return;const s="string"==typeof r.operator?r.operator:"",n=this.toFiniteNumber(r.count),o=this.toFiniteNumber(r.edit_time);return s&&void 0!==n&&void 0!==o?{operatorId:s,operationCount:n,operationTime:o}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),r=t?.thread;if(!Up(r)||0===Object.keys(r).length)return;const s=this.readString(r.msg_parent_id??r.messageId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const o=this.readString(r.thread_name??r.chatThreadName);return{messageId:s,parentId:n,...o?{chatThreadName:o}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),r=t?.thread_overview??t?.threadOverview;if(!Up(r)||0===Object.keys(r).length)return;const s=this.readString(r.id??r.thread_id??r.chatThreadId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const o=this.readString(r.name),i=this.resolveChatThreadOverviewLastMessage(r.last_message??r.lastMessage,s);return{chatThreadId:s,parentId:n,...o?{name:o}:{},...void 0!==i?{lastMessage:i}:{},...this.numberField("createdAt",r.create_timestamp??r.createdAt),...this.numberField("updatedAt",r.update_timestamp??r.updatedAt),...this.numberField("messageCount",r.message_count??r.messageCount)}}resolveChatThreadOverviewLastMessage(e,t){if(!Up(e)||0===Object.keys(e).length)return null;const r=this.readString(e.msgId??e.msg_id??e.id);if(!r)return null;const s=this.toFiniteNumber(e.timestamp)??0,n=this.resolveThreadLastMessagePayload(e),o=this.readString(n?.from)??this.readString(e.from)??"",i=this.readString(n?.to)??this.readString(e.to)??t,a=Array.isArray(n?.bodies)?n.bodies:[],c=Up(a[0])?a[0]:null,d=this.readString(c?.type)??this.readString(e.type),u=this.mapThreadMessageType(d),l=this.normalizeThreadLastMessageBody(u,c,e),h=t,p=o===this.context.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:o,to:i,sender:{userId:o},conversationId:h,conversationType:"groupChat",type:u,sendStatus:"sent",ext:Up(n?.ext)?n.ext:{},timestamp:s,body:l,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(Up(t))return t;if("string"==typeof t){const e=this.parseMetaPayload(t);if(e)return e}return null}mapThreadMessageType(e){switch(e){case"txt":default:return"text";case"img":return"image";case"loc":return"location";case"audio":return"voice";case"video":return"video";case"file":return"file";case"cmd":return"cmd";case"custom":return"custom";case"combine":return"combine";case"text":case"image":case"voice":case"location":return e}}normalizeThreadLastMessageBody(e,t,r){if(!t){return{content:this.readString(r.msg??r.content??r.text)??""}}switch(e){case"text":default:return{content:this.readString(t.msg??t.content??t.text)??""};case"image":{const e=this.readString(t.url)??"",r=no(e,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(t.filename)??"image",filetype:this.readString(t.filetype)??"application/octet-stream",width:this.toFiniteNumber(t.width)??0,height:this.toFiniteNumber(t.height)??0,isGif:!0===t.isGif,isOriginalImage:!1,originalImageUrl:r.originalImageUrl,bigImageUrl:r.bigImageUrl,thumbnailUrl:this.readString(t.thumb)??r.thumbnailUrl,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)}}case"voice":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"voice",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"video":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"video",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,width:this.toFiniteNumber(t.width),height:this.toFiniteNumber(t.height),thumbnailUrl:this.readString(t.thumb),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"file":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"file",filetype:this.readString(t.filetype)??"application/octet-stream",secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"location":return{latitude:this.toFiniteNumber(t.lat??t.latitude)??0,longitude:this.toFiniteNumber(t.lng??t.longitude)??0,address:this.readString(t.addr??t.address),buildingName:this.readString(t.buildingName)};case"cmd":return{action:this.readString(t.action)??""};case"custom":return{event:this.readString(t.event??t.customEvent)??"",params:Up(t.params??t.customExts)?t.params??t.customExts:{}};case"combine":return{title:this.readString(t.title)??"",summary:this.readString(t.summary)??"",filename:this.readString(t.filename)??"combine",filetype:"application/octet-stream",url:this.readString(t.url),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength),combineLevel:this.toFiniteNumber(t.combineLevel)??0}}}readString(e){return"string"==typeof e&&e.length>0?e:void 0}numberField(e,t){const r=this.toFiniteNumber(t);return void 0===r?{}:{[e]:r}}parseMetaPayload(e){const t=this.normalizeMetaPayload(e);if(t){if(0===t.length)return null;try{const e=JSON.parse(Ao(t));return Up(e)?e:null}catch{return null}}if(Up(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return Up(t)?t:null}catch{return null}return null}toFiniteNumber(e){const t="number"==typeof e?e:"string"==typeof e?Number(e):Number.NaN;return Number.isFinite(t)?t:void 0}resolveReactions(e){const t=this.parseMetaPayload(e),r=t?.reaction;if(Array.isArray(r)&&0!==r.length)return r.filter(Up).map(e=>({reaction:"string"==typeof e.reaction?e.reaction:"",count:"number"==typeof e.count?e.count:0,userList:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof e.state?e.state:void 0}))}normalizeMetaPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null}mapPriorityToTag(e){return"high"===e?0:"low"===e?2:1}getRequestedCompressTypes(){return this.compressionFailureCount>=this.maxCompressionFailures?[]:[Fs]}configureCompression(e,t){if(!e||!e.includes(Fs))return void this.disableCompression();this.compressor||(this.compressor=new Ep);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===Ap.UPLINK_ONLY||r===Ap.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===Ap.DOWNLINK_ONLY||r===Ap.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?Ap.UPLINK_ONLY:1===e?Ap.DOWNLINK_ONLY:2===e?Ap.BIDIRECTIONAL:Ap.NONE}disableCompression(){this.compressor&&(this.compressor.mode=Ap.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Op=1e3,xp="direct";class Lp{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 r=0;r<this.events.length;r+=1){const s=this.events[r];s&&s.appKey===e&&(this.events[r]={appKey:t,wire:{...s.wire,body:{...s.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 r=0;r<this.events.length&&t.length<this.batchSize;){const s=this.events[r];s?.appKey===e.appKey?(t.push(s.wire),this.events.splice(r,1)):r+=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 Pp{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 r=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});(r.status<200||r.status>=300)&&this.onFailure?.({reason:"non-success-response",status:r.status})}catch(r){this.onFailure?.({reason:"transport-error",message:r instanceof Error?r.message:String(r)})}else this.onFailure?.({reason:"request-adapter-unavailable",eventCount:t.length})}}const Dp={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},$p=()=>{const e=Wo(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class qp{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??$p;const t=new Pp({requestAdapter:e.requestAdapter,debug:e.debug,now:this.now,onFailure:t=>{e.onDiagnostic?.("DataReport transport failed",t)}}),r=e.send??((e,r)=>t.send(e,r));this.queue=new Lp({send:r,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:Dp[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 r=`opr_${this.randomId()}`,s=this.now();let n=!1,o=!1,i=`req_${this.randomId()}`,a=0,c="";const d=()=>!n&&!o&&this.session?.sessionId===t,u=(t,s,n,o,i)=>{d()&&(a=i.success?0:i.code,c=i.success?"":i.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:s,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(n),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-o),code:i.code,codeDesc:i.description??"",isLastApi:0,isSuccess:i.success?1:0,accessChannel:this.session?.accessChannel??xp,msgId:e.msgId,messageType:e.messageType,resultCount:i.resultCount}))},l=(e,t,r,s)=>{const n=this.now();let o=!1;return{retry:()=>(s.next+=1,l(e,t,s.next,s)),finish:s=>{o||(o=!0,u(e,t,r,n,s))}}};return{startRequest:(e={})=>(i=`req_${this.randomId()}`,l(e,i,1,{next:1})),finish:t=>{d()&&(n=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:i,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-s),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??c,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??xp,msgId:e.msgId,messageType:e.messageType,resultCount:t.resultCount}))},discard:()=>{o=!0}}}reset(){this.currentState="disabled",this.session=void 0,this.queue.clear()}enqueue(e,t){const r=this.session;if(!r||"disabled"===this.currentState)return;const s={lts:this.now(),net:this.networkType,appkey:r.appKey,sdkServiceId:r.serviceId,sdkProduct:0,uikitVersion:r.uikitVersion??"",...t},n={eventId:e,body:Object.fromEntries(Object.entries(s).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:r.appKey,wire:n})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let Gp;const Bp=e=>{Gp?.applyDnsSwitch(e)},Fp=e=>{Gp?.updateNetworkType(e)},jp=e=>{if("disabled"!==Gp?.state)return Gp?.startOperation(e)},zp=()=>{Gp?.reset(),Gp=void 0};class Kp{constructor(e,r){this.serverUrlIndex=0,this.websocket=null,this.provisionTimeoutId=null,this.reconnectAttempts=0,this.messageReceiver=null,this.provisionPromise=null,this.provisionResolve=null,this.provisionReject=null,this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames=new Set,this.offlineMessageQueueReports=new Map,this.offlineMessageQueueCounts=new Map,this.offlineMessageTotalCount=0,this.reconnectTimerId=null,this.reconnectInProgress=!1,this.reconnectPaused=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.hasEverConnected=!1,this.isOnline=!0,this.internalHandlerId="__internal:connection-manager",this.suppressNextCloseEvent=!1,this.socketDisposers=[],this.inboundMessageQueue=Promise.resolve(),this.socketGeneration=0,this.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:3e4,autoReconnectNumMax:10,connectTimeout:1e4,...e},this.eventHub=r,this.msyncCodec=new Np({appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,userId:e.userId,token:e.token,useReplacedMessageContents:e.useReplacedMessageContents,useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,serviceId:e.serviceId}),this.serverUrls=this.normalizeServerUrls(e),this.config.serverUrl=this.serverUrls[0]??this.config.serverUrl,this.connection={status:t,serverUrl:this.config.serverUrl,userId:e.userId,token:e.token,reconnectAttempts:0},this.connectionRetry=new Xu({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new rl({interval:this.config.heartBeatWait,timeout:6e4}),this.connectionEventNormalizer=new Mo,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[m]:e=>{this.handleSendTimeout(e)}})}getConnectionStatus(){return this.connection.status}getWebSocket(){return this.websocket}getMsyncCodec(){return this.msyncCodec}getClientResource(){return this.msyncCodec.getContext().clientResource}setMessageReceiver(e){this.messageReceiver=e}renewToken(e,t){const r=Date.now();if(t<=r)throw new Wr("Token is expired",{code:lt,details:{stage:"token"}});return this.config.token=e,this.connection.token=e,this.msyncCodec.updateToken(e),this.setupTokenLifecycle(e,t,r),To("Connection token renewed",{userId:this.config.userId,expireAt:t}),{token:e,expireAt:t}}handleOnline(){To("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0;const e=this.offlineRecoverPending?S:C;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){To("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.stopHeartbeat(),this.closeWebSocket(E,!0),To("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void To("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const e=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(T,!0,!0),this.resumeReconnect(T)}}catch(t){if(To("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(T,!0,!0),this.resumeReconnect(T)}}resumeReconnect(e){this.isLoggedIn&&(this.reconnectInProgress?To("Reconnect recovery skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.connection.status===s&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),To("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===_&&To("Message send timeout received without reconnect",e))}resetReconnectState(){this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connectionRetry.reset()}getReconnectDiagnostic(){return{status:this.connection.status,isOnline:this.isOnline,isLoggedIn:this.isLoggedIn,isLoginPhase:this.isLoginPhase,reconnectInProgress:this.reconnectInProgress,reconnectPaused:this.reconnectPaused,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId}}normalizeServerUrls(e){const t=(e.serverUrls??[]).filter(e=>"string"==typeof e&&e.length>0);return t.length>0?[...t]:[e.serverUrl]}pickNextServerUrl(){if(0===this.serverUrls.length)return this.config.serverUrl;const e=this.serverUrlIndex%this.serverUrls.length,t=this.serverUrls[e]??this.config.serverUrl;return this.serverUrlIndex=(e+1)%this.serverUrls.length,this.config.serverUrl=t,this.connection.serverUrl=t,t}resolveEffectiveMaxAttempts(){return this.isLoginPhase&&0===this.config.autoReconnectNumMax?1:this.config.autoReconnectNumMax}isNonRetryableError(e){if(!(e instanceof Wr))return!1;const t=e.details;if(!t||"object"!=typeof t)return!1;return!1===t.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(Ao(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null)}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay();To("Reconnect retry scheduled",{delayMs:Math.round(e),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise(t=>{this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,t()},e)})}buildConnectionEventPayload(e,t){const r=this.connection.error instanceof Wr?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:r?.code,errorMessage:r?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,r){if(e===t&&!this.hasEverConnected)return;if(e===o&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===t||e===o))return;const s=this.buildConnectionEventPayload(e,r),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,r,n=!1){const o=this.connection.status!==e;(o||n)&&(o&&(this.connection.status=e,this.connection.lastConnectedAt=e===s?Date.now():void 0),r&&this.dispatchConnectionEvent(e,t),So("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:n}))}clampTimerDelay(e){return e<=0?0:Math.min(e,2**31-1)}clearTokenTimers(){this.tokenWillExpireTimerId&&(clearTimeout(this.tokenWillExpireTimerId),this.tokenWillExpireTimerId=null),this.tokenExpiredTimerId&&(clearTimeout(this.tokenExpiredTimerId),this.tokenExpiredTimerId=null)}setupTokenLifecycle(e,t,r=Date.now()){this.clearTokenTimers();const s=Math.max(t-r,0),n=r+Math.floor(.8*s);this.tokenLifecycle={token:e,issuedAt:r,expireAt:t,willExpireAt:n,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(n-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(e){if(e&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return void To("Provision auth token has invalid payload");const r=Number(t.expires_in);if(!Number.isFinite(r))return void To("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(t){To("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,To("Token will expire"),this.eventHub.dispatch(u,void 0))}emitTokenExpired(){this.tokenLifecycle||(this.tokenLifecycle={token:this.connection.token??"",issuedAt:Date.now(),expireAt:Date.now(),willExpireAt:Date.now(),willExpireEmitted:!0,expiredEmitted:!1});const e=this.tokenLifecycle;e.expiredEmitted||(e.expiredEmitted=!0,To("Token expired"),this.eventHub.dispatch(l,void 0))}isTokenExpiredConnectionError(e){return e instanceof Wr&&e.code===lt}handleTokenExpiredDisconnect(e){To("Connection closing because token expired",{source:e}),this.connection.error=new Wr("Token expired",{code:lt,details:{stage:"token",source:e,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(U,!0,!0),this.updateStatus(t,U,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(T)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,6e4)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(){if(!this.reconnectInProgress)if(this.connection.status!==s&&this.connection.status!==r){this.isLoginPhase=!0,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(I,!0),this.isLoggedIn=!0}catch(e){throw this.isLoggedIn=!1,e}finally{this.isLoginPhase=!1}}else To("Connection already established or connecting")}async connectWithRetry(e,i){if(To("Reconnect flow requested",{reason:e,throwOnFailure:i,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void To("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()});if(this.connection.status===s&&this.websocket)return;if(this.reconnectPaused)return void To("Reconnect flow skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let a=null,c=null;const d=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),To("Reconnect flow started",{reason:e,throwOnFailure:i,maxAttempts:d,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<d;){this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const t=this.isLoginPhase?r:n;To("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:d,reason:e,nextStatus:t,...this.getReconnectDiagnostic()}),this.updateStatus(t,e,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(e)}catch(u){if(a=u,To("Connection attempt failed",{attempt:this.reconnectAttempts,reason:e,error:a}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(a))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(a)){c=a;break}}if(this.connectionRetry.getAttemptCount()>=d)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){To("Reconnect retry loop interrupted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:d,...this.getReconnectDiagnostic()});break}await this.waitForReconnectDelay()}if(c){if(this.connection.error=c,i)throw this.updateStatus(t,A,!1),c;return this.reconnectPaused=!0,void this.updateStatus(t,A,!0)}if(i)throw this.updateStatus(t,A,!1),a??new Wr("Connection failed",{code:gt,details:{stage:"ws"}});this.reconnectPaused=!0,To("Reconnect attempts exhausted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:d,lastError:a,...this.getReconnectDiagnostic()}),this.updateStatus(o,M,!0)}finally{this.reconnectInProgress=!1,To("Reconnect flow finished",{reason:e,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(w,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(s,e,!0),this.hasEverConnected=!0,this.connection.error=void 0,this.resetReconnectState(),this.offlineRecoverPending=!1,this.reconnectPaused=!1,this.sendPostProvisionInitialSync(),this.websocket&&this.startHeartbeat(this.websocket),To("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}async triggerReconnect(e){To("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.isLoggedIn?this.reconnectInProgress?To("Reconnect trigger skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.reconnectPaused?To("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}):(this.connection.status===s&&this.websocket&&this.closeWebSocket(e,!0,!0),await this.connectWithRetry(e,!1)):To("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()})}handleDisconnection(e){To("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t,e,!0),e!==U&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(e))}closeWebSocket(e,r,s=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),s&&this.updateStatus(t,e,r)):s&&this.updateStatus(t,e,r)}createWebSocketConnection(){return new Promise((e,t)=>{const r=this.pickNextServerUrl();So("WebSocket connecting",{url:r}),this.clearSocketListeners();let s=!1;const n=setTimeout(()=>{s=!0,To("WebSocket connection attempt timed out",{url:r,connectTimeout:this.config.connectTimeout,...this.getReconnectDiagnostic()}),t(new Wr("Connection timeout",{code:ft,details:{stage:"ws"}}))},this.config.connectTimeout);this.socketAdapter.connect({url:r,timeoutMs:this.config.connectTimeout}).then(o=>{if(clearTimeout(n),s||this.reconnectPaused)return To("WebSocket connection result discarded",{url:r,cancelled:s,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void o.close();this.websocket=o,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(o,this.socketGeneration),this.startProvision().then(()=>{if(this.resetProvisionHandlers(),s||this.reconnectPaused)return To("Provision result discarded",{url:r,cancelled:s,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void this.closeWebSocket(A,!1,!1);e()}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(A,!1,!1),t(e instanceof Error?e:new Error(String(e)))})}).catch(e=>{if(clearTimeout(n),s)return;const r=e instanceof Wr?e:new Wr("Failed to create WebSocket",{code:gt,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});this.handleConnectionError(r,A),t(r)})}).catch(e=>{if(e instanceof Wr)throw e;const t=new Wr("Failed to create WebSocket",{code:gt,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});throw this.handleConnectionError(t,A),t})}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(To("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(R))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new Wr("Provision interrupted",{code:It,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,t){if(_o("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(t)}handleTerminalConnectionError(e,r){if(To("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(t,r,!0,!0)}async handleWebSocketMessage(e,t){try{if(t!==this.socketGeneration)return;So("WebSocket message received",{dataType:typeof e});const s=await this.msyncCodec.normalizeIncoming(e);if(t!==this.socketGeneration)return;if(So("handleWebSocketMessage data",{length:s.length}),!s.length)return;const n=this.msyncCodec.decompressIncoming(s);if(!n){const e=null!==this.provisionReject;return _o("Failed to decompress mSync payload, closing connection",{stage:e?"provision":"connected"}),void(e?(this.rejectPendingProvision(new Wr("Failed to decompress Provision payload",{code:gt,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(A,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(n))return void So("Ignore server normal close payload",{length:n.length});let o=null;try{o=this.msyncCodec.decodeMsync(n)}catch(r){const e=r instanceof Error?r:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void To("Discard invalid mSync payload",{length:n.length,message:e.message,prefixHex:Array.from(n.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(n.subarray(Math.max(0,n.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw To("Invalid mSync payload signature",{length:n.length,prefixHex:Array.from(n.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),So("handleWebSocketMessage decoded",{command:o.command}),o.command){case is:this.handleProvisionMessage(o.payload);break;case as:this.handleLogoutMessage(o.payload);break;case os:this.handleNoticeMessage(o.payload);break;case ns:this.handleUnreadMessage(o.payload);break;case ss:this.handleSyncMessage(o.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");_o("Failed to handle mSync payload",e),this.handleConnectionError(e,A)}}startProvision(){this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(new Wr("Provision timeout",{code:vt,details:{stage:"provision",retryable:!0}}))},1e4);try{const e=this.msyncCodec.encodeProvision();So("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new Wr("Provision send failed",{code:gt,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(e){const t=this.msyncCodec.decodeProvision(e);if(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t.ok)this.msyncCodec.updateResource(t.resource),this.setupTokenLifecycleFromProvision(t.authToken),this.provisionResolve?.();else{To("Provision rejected",{statusCode:t.statusCode,reason:t.reason});const e=Nn(t.statusCode,t.reason),r=e.code===Fr?bt:e.code;this.provisionReject?.(new Wr("Provision rejected",{code:r,details:{stage:"provision",reason:t.reason,statusCode:t.statusCode,retryable:e.retryable}}))}}handleNoticeMessage(e){const{queue:t}=this.msyncCodec.decodeNotice(e),r=t?this.getQueueId(t):null,s=!!t&&this.isSelfQueue(t),n=!!t&&this.isQueueInList(t);t&&r&&(s||n||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(e){const{queues:t}=this.msyncCodec.decodeUnread(e),r=t.filter(e=>this.getQueueId(e));if(r.length){r.length!==t.length&&To("Unread queues without usable identity were ignored",{ignoredCount:t.length-r.length}),this.startOfflineMessageSync(r);for(const e of r)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(e){const t=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(t)return void this.handleTerminalConnectionError(t,A);if(!this.messageReceiver)return;const r=this.messageReceiver.handleSyncPayload(e);if(So("handleSyncMessage result",{result:r}),!r)return;(void 0!==r.queue||void 0!==r.nextKey||void 0!==r.isLast)&&this.handleSyncQueueState(r)}handleSyncQueueState(e){So("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:r,queueId:s}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(s)){const t=this.offlineMessageQueueCounts.get(s)??0;this.offlineMessageQueueCounts.set(s,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const n=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(s),this.removeQueueEntry(r),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(n){if(n!==this.nextKey||!this.isSameQueue(r,this.currentQueue))return this.nextKey=n,this.currentQueueId=s,this.currentQueue=r,void this.sendLastSession(r,n);this.removeQueueEntry(r),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,r=t?this.getQueueName(t):null,s=t?this.getQueueId(t):null,n=void 0!==t&&null!==s&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&s&&n)return{queue:t,queueId:s};const o=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,i=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,a=o??i??this.queues[0],c=a?this.getQueueName(a):null,d=a?this.getQueueId(a):null;return a&&d?(To("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:r,responseQueueId:s,fallbackQueueName:c,fallbackQueueId:d,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:e.isLast,hasNextKey:Boolean(e.nextKey)}),{queue:a,queueId:d}):null}handleLogoutMessage(e){const t=this.msyncCodec.decodeLogout(e);To("Logout message received",t)}resolveStatisticDisconnectError(e){for(const t of e)switch(t.operation){case 1:return new Wr("User has been removed",{code:Ht,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 2:return new Wr("The user is already logged on another device",{code:Kt,details:{stage:"statistics",operation:t.operation,retryable:!1,...t.reason?{loginInfoCustomExt:t.reason}:{}}});case 3:return new Wr("The user was kicked by changing password",{code:Vt,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 4:return new Wr("The user was kicked by other device",{code:Wt,details:{stage:"statistics",operation:t.operation,retryable:!1}})}return null}resetProvisionHandlers(){this.provisionResolve=null,this.provisionReject=null,this.provisionPromise=null}rejectPendingProvision(e){const t=this.provisionReject;return!!t&&(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t(e),this.resetProvisionHandlers(),!0)}disconnect(){return this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.clearReconnectTimer(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.offlineRecoverPending=!1,this.closeWebSocket(R,!0,!0),this.updateStatus(t,R,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),To("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){if(e.socketAdapter)return e.socketAdapter;const t=Ld({webSocketCtor:"function"==typeof WebSocket?WebSocket:void 0});if(t)return t;throw Fo("Socket capability is missing for current platform",{code:"PLATFORM_MISSING_CAPABILITY",stage:"socket",retryable:!1,details:{capability:"socket"}})}attachSocketListeners(e,t){this.clearSocketListeners(),this.socketDisposers=[e.onMessage(r=>{this.websocket===e&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(r,t)))}),e.onError(()=>{if(this.websocket!==e)return;To("WebSocket error",{stage:"ws"});const t=new Wr("WebSocket connection error",{code:gt,details:{stage:"ws"}});this.handleConnectionError(t,A)}),e.onClose(t=>{this.websocket===e&&this.handleWebSocketClose(t)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===zo)try{const t=this.msyncCodec.prepareOutgoing(e);So("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{_o("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){_o("Failed to send mSync payload",t),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const t=this.msyncCodec.encodeBackQueue(e);So("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){So("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const r=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(r)}sendNextQueue(){So("sendNextQueue queues",{size:this.queues.length});const e=this.queues[0];e&&this.sendBackqueue(e)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(e){const t=new Set;for(const r of e){const e=this.getQueueId(r);e&&t.add(e)}if(0!==t.size){for(const e of t)this.offlineMessageQueueNames.add(e);if(!this.offlineMessageSyncing){this.offlineMessageSyncing=!0,this.offlineMessageSyncLifecycleActive=!this.offlineMessageSyncLifecycleDispatched,this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleDispatched=!0),this.offlineMessageTotalCount=0,this.offlineMessageQueueCounts.clear(),this.offlineMessageQueueReports.clear(),this.offlineMessageReport=jp({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of t){this.offlineMessageQueueCounts.set(e,0);const t=this.offlineMessageReport?.startRequest({requestName:"MSYNC_SYNCOFFLINEMESSAGE",method:"WS",url:e});t&&this.offlineMessageQueueReports.set(e,t)}this.offlineMessageSyncLifecycleActive&&this.eventHub.dispatch(h,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const t=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:t}),this.offlineMessageQueueReports.delete(e),this.offlineMessageQueueNames.delete(e),this.offlineMessageQueueNames.size>0||(this.offlineMessageSyncing=!1,this.offlineMessageReport?.finish({code:0,success:!0,resultCount:this.offlineMessageTotalCount}),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleActive=!1,this.eventHub.dispatch(p,void 0)))}isQueueInList(e){return this.queues.some(t=>this.isSameQueue(t,e))}isSelfQueue(e){const t=this.getQueueName(e),r=this.getQueueResource(e),s=this.msyncCodec.getContext();return t===s.userId&&r===s.clientResource}getQueueName(e){return"string"==typeof e.name&&e.name.trim().length>0?e.name:null}getQueueResource(e){return this.getQueueField(e,"clientResource")}getQueueId(e){const t=this.getQueueName(e);if(t)return`name:${t}`;const r=this.getQueueField(e,"domain"),s=this.getQueueResource(e);if(r)return`domain:${r}|resource:${s??""}`;if(s)return`resource:${s}`;const n=this.getQueueField(e,"appKey");return n?`appKey:${n}`:null}getQueueField(e,t){const r=e[t];return"string"==typeof r&&r.trim().length>0?r:null}isSameQueue(e,t){if(!e||!t)return!1;const r=this.getQueueId(e),s=this.getQueueId(t);return null!==r&&r===s}resetSyncState(){this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames.clear(),this.offlineMessageReport?.discard(),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageTotalCount=0}}const Hp=new class{constructor(){this.store=new Map}set(e,t){e&&this.store.set(e,t)}get(e){if(e)return this.store.get(e)}consume(e){const t=this.get(e);return t&&this.store.delete(e),t}delete(e){e&&this.store.delete(e)}clear(){this.store.clear()}},Vp=e=>{if((e=>"undefined"!=typeof File&&e instanceof File)(e)){if("undefined"==typeof URL||"function"!=typeof URL.createObjectURL)return;return URL.createObjectURL(e)}return(e=>"object"==typeof e&&null!==e&&"path"in e&&"string"==typeof e.path)(e)?e.path:(e=>"object"==typeof e&&null!==e&&"uri"in e&&"string"==typeof e.uri)(e)?e.uri:void 0},Wp=()=>{const e=Wo().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},Jp=new Uint8Array([99,109]),Zp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Qp=e=>Array.isArray(e)&&e.every(Zp),Yp=e=>"string"==typeof e?e:void 0,Xp=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,em=e=>{const t=new Uint8Array(4);return t[0]=e>>>24&255,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=255&e,t},tm=(e,t)=>{const r=e[t],s=e[t+1],n=e[t+2],o=e[t+3];if("number"!=typeof r||"number"!=typeof s||"number"!=typeof n||"number"!=typeof o)throw new Yr("Combine payload length header is invalid",{code:lr});return r<<24|s<<16|n<<8|o},rm=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},sm=(e,t)=>{const r=nl().lookupType(e).decode(t);if(!Zp(r))throw new Error(`${e} decoded result is invalid`);return r},nm=e=>Zp(e)&&"string"==typeof e.name?e.name:"",om=(e,t,r)=>{const s=(Qp(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=Xp(e.type)??ys,r=Boolean(Yp(e.remotePath))||Boolean(Yp(e.title))||Boolean(Yp(e.summary))||(Xp(e.combineLevel)??0)>0,s=t===ys&&0===e.subType&&r;if(t===_s||s){const t=Xp(e.combineLevel)??0;return{type:"combine",body:{title:Yp(e.title)??"",summary:Yp(e.summary)??"",filename:Yp(e.displayName)??"combine",filetype:"application/octet-stream",url:Yp(e.remotePath),secret:Yp(e.secretKey),fileLength:Xp(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ys)return{type:"text",body:{content:Yp(e.text)??""}};if(t===Ss)return{type:"cmd",body:{action:Yp(e.action)??""}};if(t===Ts){const t=hl(Qp(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:Yp(e.customEvent)??"",params:t}}}if(t===Is)return{type:"location",body:{latitude:Xp(e.latitude)??0,longitude:Xp(e.longitude)??0,address:Yp(e.address),buildingName:Yp(e.buildingName)}};if(t===vs){const t=Zp(e.size)?e.size:{},r=Yp(e.remotePath)??"",s=no(r),n=Yp(e.thumbnailRemotePath),o=io(e.imageType)===Wn;return{type:"image",body:{localUrl:"",filename:Yp(e.displayName)??"image",filetype:"application/octet-stream",width:Xp(t.width)??0,height:Xp(t.height)??0,isGif:1===e.subType,isOriginalImage:o,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:Yp(e.secretKey),fileLength:Xp(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===bs){const t=Zp(e.size)?e.size:{};return{type:"video",body:{url:Yp(e.remotePath)??"",filename:Yp(e.displayName)??"video",filetype:"application/octet-stream",duration:Xp(e.duration)??0,width:Xp(t.width),height:Xp(t.height),secret:Yp(e.secretKey),fileLength:Xp(e.fileLength),thumbnailUrl:Yp(e.thumbnailRemotePath)}}}if(t===ws)return{type:"voice",body:{url:Yp(e.remotePath)??"",filename:Yp(e.displayName)??"voice",filetype:"application/octet-stream",duration:Xp(e.duration)??0,secret:Yp(e.secretKey),fileLength:Xp(e.fileLength)}};if(t===Cs)return{type:"file",body:{url:Yp(e.remotePath)??"",filename:Yp(e.displayName)??"file",filetype:"application/octet-stream",secret:Yp(e.secretKey),fileLength:Xp(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const o=nm(e.from)||nm(r?.from)||`unknown-${t}`,i=nm(e.to)||nm(r?.to)||`unknown-${t}`,a=(c=e.type)===us?"groupChat":c===ls?"chatRoom":"singleChat";var c;const d=i||o,u=Number(ul(r?.timestamp))||Date.now(),l=hl(Qp(e.ext)?e.ext:void 0),h={msgServerId:ul(r?.id),msgLocalId:"",type:n.type,sender:{userId:o},conversationId:d,conversationType:a,timestamp:u,body:n.body,ext:l};return"number"==typeof n.combineLevel&&(h.body.combineLevel=n.combineLevel),h},im=(e,t)=>{const r=[];try{const n=sm("easemob.pb.Meta",e),o=(s=n.payload)instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):void 0;if(o&&o.length>0){const e=sm("easemob.pb.MessageBody",o);return om(e,t,n)}r.push("Meta payload is empty")}catch(n){r.push(n instanceof Error?n.message:String(n))}var s;try{const r=sm("easemob.pb.MessageBody",e);return om(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=sm("easemob.pb.MessageBody.Content",e);return om({type:ds,from:{name:`unknown-${t}`},to:{name:`unknown-${t}`},contents:[r],ext:[]},t)}catch(n){r.push(n instanceof Error?n.message:String(n))}throw new Error(r.join("; "))},am=(e,t)=>{const r=Ao(e);try{const e=JSON.parse(r);if(!Zp(e))throw new Yr("Combine payload item is invalid",{code:lr,details:{index:t}});return e}catch(s){if(s instanceof Yr)throw s;try{return im(e,t)}catch(n){throw new Yr("Combine payload item parse failed",{code:lr,details:{index:t,cause:s instanceof Error?s.message:String(s),protobufCause:n instanceof Error?n.message:String(n)}})}}},cm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),dm=(e,t,r)=>{throw new Zr(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},um=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:cm(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},lm=(e,t)=>{if(e.sender.userId||dm(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,ir),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||dm(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,ir),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&dm(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,ir),cm(e.body)||dm(`messageList[${t}] body must be object`,`messageList[${t}].body`,ir),"combine"===e.type){const r=um(e);(!Number.isInteger(r)||r<0)&&dm(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,ir),r>10&&dm(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ar)}},hm=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&dm("messageList must not be empty","messageList",ir),(!Number.isInteger(t)||t<=0||t>300)&&dm("max items is invalid","maxItems",ir),e>t&&dm(`messageList max length is ${t}`,"messageList",cr)},pm=e=>{hm(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?lm(r,t):dm(`messageList[${t}] is required`,`messageList[${t}]`,ir)}},mm=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=um(r);e>t&&(t=e)}return t+1},fm=e=>{(!Number.isInteger(e)||e<=0)&&dm("combineLevel must be positive integer","combineLevel",ir),e>10&&dm("combineLevel must be <= 10","combineLevel",ar)},gm=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class ym{constructor(e,t,r,s){this.websocket=null,this.pendingMessages=new Map,this.ackTimeout=15e3,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=t,this.eventHub=r,this.msyncCodec=e,this.attachmentUploader=s??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(e,t){const r=this.msyncCodec.toProtocolId(e.msgLocalId);if(st(e))throw new Qr("Stream message send is not supported",{code:or,details:{msgLocalId:e.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==zo){const t=this.msyncCodec.toProtocolId(e.msgLocalId);throw new Qr("WebSocket is not connected",{code:St,details:{msgLocalId:e.msgLocalId,protocolId:t,retryable:!0}})}let s={...e,sendStatus:"sending"};ah(e,s),So("Message send queued",{msgLocalId:e.msgLocalId,protocolId:r,type:e.type,conversationType:e.conversationType,conversationId:e.conversationId});try{const e="combine"===s.type?this.prepareCombineMessage(s):s,r={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,t):e,sendStatus:"sending"};ah(s,r),s=r,t?.onSending?.(r);const n=await this.doSendMessage(r);return t?.onSuccess?.(n),n}catch(n){const e={...s,sendStatus:"failed"};throw ah(s,e),t?.onFailed?.(e,n instanceof Error?n:new Error(String(n))),n}}async sendAction(e,t){const r=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&So("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:r,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const s=this.msyncCodec.encodeActionMessage(e,r);"clearAllConversationUnreadMessageCount"===e.kind&&So("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:r,payloadBytes:s.byteLength});const n="recall"===e.kind?"MSYNC_RECALLMESSAGE":"update"===e.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${e.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"message",operationName:n,operationType:"MESSAGE",requestName:n,msgId:e.messageId,messageType:gm(e.conversationType)}))}async sendChatRoomOperation(e,t){const r=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),s=this.msyncCodec.encodeChatRoomOperation(e,r),n="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"chatroom",operationName:n,operationType:"CHATROOM",requestName:n,msgId:e.chatRoomId}))}async doSendMessage(e){const t=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:e.msgLocalId,messageType:gm(e.conversationType)});return new Promise((r,s)=>{const n=this.msyncCodec.toProtocolId(e.msgLocalId),o=setTimeout(()=>{this.pendingMessages.delete(n),this.finishPendingDataReport(t,{code:Tt,success:!1,description:"Message ACK timeout"}),s(new Qr("Message ACK timeout",{code:Tt,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(n,{kind:"message",message:e,protocolId:n,timeoutId:o,resolve:e=>{clearTimeout(o),r(e)},reject:e=>{clearTimeout(o),s(e)},report:t});try{if(!this.websocket||this.websocket.readyState!==zo)throw new Qr("WebSocket is not connected",{code:St,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(e,n),i=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(i)).catch(r=>{const i=r instanceof Error?r.message:String(r);this.pendingMessages.delete(n),clearTimeout(o),this.finishPendingDataReport(t,{code:-1,success:!1,description:i}),To("Message send socket failure",{msgLocalId:e.msgLocalId,protocolId:n,websocketReadyState:this.websocket?.readyState??null,cause:i}),s(new Qr(`WebSocket send failed: ${i}`,{code:St,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0,cause:i}}))}),So("Message sent",{msgLocalId:e.msgLocalId,protocolId:n})}catch(i){if(this.pendingMessages.delete(n),clearTimeout(o),this.finishPendingDataReport(t,{code:i instanceof Qr?i.code:At,success:!1,description:i instanceof Error?i.message:String(i)}),i instanceof Qr)throw i;throw new Qr("Message encode failed",{code:At,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}})}})}async sendProtocolPayload(e,t,r,s){return new Promise((n,o)=>{const i=setTimeout(()=>{this.pendingMessages.delete(e),this.finishPendingDataReport(s,{code:Tt,success:!1,description:"Message ACK timeout"}),o(new Qr("Message ACK timeout",{code:Tt,details:{protocolId:e,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(e,{kind:"action",protocolId:e,timeoutId:i,createAckError:r,resolve:n,reject:o,report:s});try{if(!this.websocket||this.websocket.readyState!==zo)throw new Qr("WebSocket is not connected",{code:St,details:{protocolId:e,retryable:!0}});const r=this.msyncCodec.prepareOutgoing(t);Promise.resolve(this.websocket.send(r)).catch(t=>{const r=t instanceof Error?t.message:String(t);this.pendingMessages.delete(e),clearTimeout(i),this.finishPendingDataReport(s,{code:-1,success:!1,description:r}),o(new Qr(`WebSocket action send failed: ${r}`,{code:St,details:{protocolId:e,retryable:!0,cause:r}}))})}catch(a){if(this.pendingMessages.delete(e),clearTimeout(i),this.finishPendingDataReport(s,{code:a instanceof Qr?a.code:At,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof Qr)throw a;o(new Qr("Message encode failed",{code:At,details:{protocolId:e,retryable:!1}}))}})}prepareCombineMessage(e){const t=e.body,r=t.messageList??[];pm(r);const s=mm(r);fm(s);const n=(e=>{try{const t=e.map((e,t)=>{const r=JSON.stringify(e);if(!r)throw new Qr("Combine payload item encode failed",{code:dr,details:{index:t}});return Ro(r)}),r=Jp.length+t.reduce((e,t)=>e+4+t.length,0)+1,s=new Uint8Array(r);let n=0;s.set(Jp,n),n+=Jp.length;for(const e of t){const t=em(e.length);s.set(t,n),n+=t.length,s.set(e,n),n+=e.length}const o=rm(s.subarray(0,s.length-1));return s[s.length-1]=o,s}catch(t){if(t instanceof Qr)throw t;throw new Qr("Combine payload encode failed",{code:dr,details:{cause:t instanceof Error?t.message:String(t)}})}})(r),o=new ArrayBuffer(n.byteLength);new Uint8Array(o).set(n);const i=new File([o],t.filename||"combine",{type:t.filetype||"application/octet-stream"}),a=Vp(i);if(!a&&!this.attachmentUploader)throw new Qr("Combine payload local url generation failed",{code:dr});Hp.set(e.msgLocalId,i);const c={...e,body:{...t,combineLevel:s,fileLength:n.byteLength,filename:t.filename||"combine",filetype:t.filetype||"application/octet-stream",url:a??t.url}};return ah(e,c),hh(e,c),c}handleAck(e,t,r,s){const n=this.pendingMessages.get(e);if(!n)return void So("Received ACK without a tracked pending message",{protocolId:e});if("action"===n.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),void n.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:s});const o={...n.message,...this.resolveReplacedMessage(n.message,r),sendStatus:"sent",msgServerId:t||r?.msgServerId||n.message.msgServerId};ah(n.message,o),this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),"image"!==o.type&&"video"!==o.type&&"voice"!==o.type&&"file"!==o.type&&"combine"!==o.type||Hp.delete(o.msgLocalId),So("Message ACK matched",{protocolId:e,msgLocalId:o.msgLocalId,msgServerId:o.msgServerId??null,type:o.type,conversationType:o.conversationType,conversationId:o.conversationId}),this.eventHub.dispatch(b,o),n.resolve(o)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const r=this.pendingMessages.get(e);if(!r)return;if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof Qr?t.code:-1,success:!1,description:t.message}),void r.reject(t);const s={...r.message,sendStatus:"failed"};ah(r.message,s),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof Qr?t.code:-1,success:!1,description:t.message}),To("Message send failed after ACK/error",{protocolId:e,msgLocalId:s.msgLocalId,type:s.type,conversationType:s.conversationType,conversationId:s.conversationId,error:t.message}),r.reject(t)}handleAckFailure(e,t,r,s){const n=this.pendingMessages.get(e);if(n)return"action"===n.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t,success:!1,description:r??s.message}),void n.reject(n.createAckError?.(t,r)??s)):void this.handleSendError(e,s)}setWebSocket(e){this.websocket=e}destroy(){for(const[e,t]of this.pendingMessages)clearTimeout(t.timeoutId),this.finishPendingDataReport(t.report,{code:-1,success:!1,description:"Message sender destroyed"}),t.reject(new Qr("Message sender destroyed",{code:Rt,details:"message"===t.kind?{msgLocalId:t.message.msgLocalId,protocolId:e,retryable:!1}:{protocolId:e,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(e){if(("message"===e.category?this.messageReportCount:this.chatRoomReportCount)>=Op){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(To("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=jp({operationName:e.operationName,operationType:e.operationType,msgId:e.msgId,messageType:e.messageType});if(t)return"message"===e.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:e.category,operation:t,request:t.startRequest({requestName:e.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(e,t){e&&!e.released&&(e.released=!0,e.request.finish(t),e.operation.finish(t),"message"===e.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<Op&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<Op&&(this.chatRoomReportSaturated=!1)))}}class vm{constructor(e){this.sessions=new Map,this.ttlMs=e?.ttlMs??3e5,this.maxSessions=e?.maxSessions??100}getOrCreate(e){this.evictStale();const t=this.sessions.get(e);if(t)return t.lastActivityTs=Date.now(),t;this.sessions.size>=this.maxSessions&&this.evictOldest();const r={msgId:e,startSeq:null,lastDispatchedSeq:-1,fullText:"",completed:!1,chunksBySeq:new Map,lastActivityTs:Date.now()};return this.sessions.set(e,r),r}get(e){return this.sessions.get(e)}addChunk(e,t){const r=this.getOrCreate(e),s=t.stream.seq;return r.chunksBySeq.has(s)?{duplicate:!0,session:r}:(r.chunksBySeq.set(s,t),r.lastActivityTs=Date.now(),t.stream.status!==rt.START&&t.stream.status!==rt.START_COMPLETED||null!==r.startSeq||(r.startSeq=s),{duplicate:!1,session:r})}getSequentialChunks(e){const t=this.sessions.get(e);if(!t||t.completed||null===t.startSeq)return[];let r=t.lastDispatchedSeq<t.startSeq?t.startSeq:t.lastDispatchedSeq+1;const s=[];for(;t.chunksBySeq.has(r);){const e=t.chunksBySeq.get(r);if(!e)break;s.push(e),r+=1}return s}markDispatched(e,t,r){const s=this.sessions.get(e);if(!s)return;const n=t.stream.seq;s.lastDispatchedSeq=Math.max(s.lastDispatchedSeq,n),s.fullText=r,s.chunksBySeq.delete(n)}markCompleted(e,t,r){const s=this.getOrCreate(e);s.completed=!0,s.completedReason=t,s.fullText=r}clear(e){this.sessions.delete(e)}clearAll(){this.sessions.clear()}evictStale(){const e=Date.now();for(const[t,r]of this.sessions)e-r.lastActivityTs>this.ttlMs&&this.sessions.delete(t)}evictOldest(){let e=null,t=1/0;for(const[r,s]of this.sessions)s.lastActivityTs<t&&(t=s.lastActivityTs,e=r);e&&this.sessions.delete(e)}}class bm{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new vm}handle(e){const t=this.resolveMessageId(e);if(!t)return void To("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void So("stream message already completed, ignore",{msgId:t});if(e.stream.status===rt.FULL)return void this.handleFullChunk(t,e);const r=this.cache.get(t);if(r?.completed)return void So("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:s}=this.cache.addChunk(t,e);s?So("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const r of t){const t=this.cache.get(e);if(!t)return;const s=t.fullText,n=r.stream.deltaText,o=`${s}${n}`,i=r.stream.errorType>0?rt.ERROR:r.stream.status,a=this.buildDispatchMessage(r,{status:i,fullText:o,deltaText:n});if(this.eventHub.dispatch(N,a),this.cache.markDispatched(e,r,o),i===rt.START_COMPLETED||i===rt.COMPLETED||i===rt.ERROR){const t=i===rt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,o),this.cache.clear(e),void this.markCompleted(e)}}else So("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),o=this.resolveDeltaText(s,n,t.stream.deltaText),i=!r||-1===r.lastDispatchedSeq&&0===r.chunksBySeq.size,a=t.stream.errorType>0?rt.ERROR:i?rt.START_COMPLETED:rt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:n,deltaText:o});this.eventHub.dispatch(N,c);const d=a===rt.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,d,n),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),o=this.resolveDeltaText(s,n,t.stream.deltaText),i=this.buildDispatchMessage(t,{status:rt.ERROR,fullText:n,deltaText:o});this.eventHub.dispatch(N,i),this.cache.markCompleted(e,"timeout_error",n),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const r=e.stream.fullText;if(r&&r.length>=t.length)return r;const s=e.body.content;return s&&s.length>=t.length?s:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,r){return t.startsWith(e)?t.slice(e.length):r}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class Im{constructor(e=100){this.seenIds=new Set,this.orderedIds=[],this.limit=Math.max(1,Math.floor(e))}checkAndRecord(e){if(!e)return!1;if(this.seenIds.has(e))return!0;for(this.seenIds.add(e),this.orderedIds.push(e);this.orderedIds.length>this.limit;){const e=this.orderedIds.shift();e&&this.seenIds.delete(e)}return!1}clear(){this.seenIds.clear(),this.orderedIds.length=0}size(){return this.seenIds.size}}const wm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Cm{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new bm(r),this.messageContexts=new Map,this.recentMessageIds=new Im(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(e){try{So("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);So("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:r,messages:s}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),r&&(So("Decoded sync ACK",{ok:r.ok,protocolId:r.protocolId,serverId:r.serverId??null,statusCode:r.statusCode??null,reason:r.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(r,t.replacedMessage));for(const e of s)this.dispatchMessage(e);return t}catch(t){_o("Failed to decode sync payload",t)}return null}handleAck(e,t){if(e.ok)return So("ACK accepted",{protocolId:e.protocolId,serverId:e.serverId??null,hasReplacedMessage:Boolean(t)}),void(e.chatRoomInfo?this.messageSender.handleAck(e.protocolId,e.serverId,t,e.chatRoomInfo):this.messageSender.handleAck(e.protocolId,e.serverId,t));To("ACK rejected",{protocolId:e.protocolId,statusCode:e.statusCode,reason:e.reason,hasReplacedMessage:Boolean(t)});const r=((e,t)=>{const r=Nn(e,t),s=r.code===Fr?_t:r.code;return{code:s,message:On[s]??(t?`Message send failed: ${t}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(e.statusCode,e.reason),s=new Qr(r.message,{code:r.code,details:{protocolId:e.protocolId,serverCode:e.statusCode,reason:e.reason,retryable:!1}});this.messageSender.handleAckFailure(e.protocolId,e.statusCode,e.reason,s)}dispatchMessage(e){if(st(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?So("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(k,e),So("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const t=this.msyncCodec.getContext().userId;t&&e.from!==t&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{To("Failed to send delivery ack",e)})}handleNotifies(e){const t=[];for(const r of e)if("presence"===r.type)this.handlePresenceNotify(r);else if("contact"===r.type)this.handleContactNotify(r);else if("group"===r.type)this.handleGroupNotify(r);else if("thread"===r.type)this.handleChatThreadNotify(r);else if("chatroom"===r.type)this.handleChatRoomNotify(r);else if("reaction"===r.type)this.handleReactionNotify(r);else if("conv"===r.type)this.handleConversationNotify(r);else if("multiDevice"===r.type)this.handleMultiDeviceNotify(r);else if("message_receipts"===r.type){const e=this.toMessageReceiptPayload(r);e&&t.push(e)}else"message_recalled"===r.type?this.handleMessageRecalledNotify(r):"message_updated"===r.type?this.handleMessageUpdatedNotify(r):"message_delivered"===r.type?this.handleMessageDeliveredNotify(r):this.handleUserInfoNotify(r);t.length>0&&this.eventHub.dispatch(x,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const r=e.data;if(!r||"object"!=typeof r)return;const s=r,n="string"==typeof s.username?s.username:"string"==typeof s.userId?s.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",o=s.metadata&&"object"==typeof s.metadata&&!Array.isArray(s.metadata)?s.metadata:null,i="number"==typeof s.lastModified?s.lastModified:"string"==typeof s.lastModified?Number(s.lastModified):Number.NaN;if(!n||!o||!Number.isFinite(i))return;const a={notifyType:t,userId:n,metadata:o,lastModified:i};this.eventHub.dispatch(v,a)}handleContactNotify(e){if(So("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==K&&e.eventName!==H&&e.eventName!==V&&e.eventName!==W&&e.eventName!==J)return;const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.from&&r.from&&"string"==typeof r.to&&r.to&&"string"==typeof r.message&&this.eventHub.dispatch(e.eventName,r)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t,s=Array.isArray(r.values)?r.values:[];if(0===s.length)return;const n=[];for(const o of s){if(!o||"object"!=typeof o)continue;const e=o,t=this.normalizePresenceStatus(e.status),r="string"==typeof e.uid?e.uid:"";r&&n.push({userId:r,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==n.length&&this.eventHub.dispatch(z,n)}handleGroupNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(f,r)}handleChatRoomNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(g,r)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const r of t){if(!wm(r)||"string"!=typeof r.messageId)continue;const e=this.resolveReactionConversationContext(r);e&&this.eventHub.dispatch($,{messageId:r.messageId,conversationId:e.conversationId,conversationType:e.conversationType,from:e.from,to:e.to,reactions:this.normalizeReactionList(r.reactions),timestamp:this.normalizeTimestamp(r.ts)})}}handleConversationNotify(e){if(!wm(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const r=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===r.clientResource&&"string"==typeof t.from&&t.from===r.userId)return;const s="string"==typeof t.ext?t.ext:"",n="string"==typeof t.type?t.type:"",o="string"==typeof t.from?t.from:"",i="string"==typeof t.id?t.id:"";s&&o&&i&&this.eventHub.dispatch(q,{messageId:s,conversationId:"chat"===n?o:i,conversationType:"chat"===n?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:o,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!wm(e.data)||"string"!=typeof e.eventName)return;const t=e.data;switch(e.eventName){case"onMultiDeviceContact":case"onMultiDeviceGroup":case"onMultiDeviceThread":case"onMultiDeviceConversation":case"onMultiDeviceMessageRemoved":return void this.eventHub.dispatch(e.eventName,t);default:return}}toMessageReceiptPayload(e){if(!wm(e.data))return null;const t=e.data;if(!Array.isArray(t.messageIds)||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||"number"!=typeof t.timestamp)return null;const r=t.messageIds.filter(e=>"string"==typeof e&&e.length>0);if(0===r.length)return null;const s=r[0];if(!s)return null;const n=this.resolveMessageReceiptContext(s,t.conversationId,t.conversationType);if("groupChat"===n.conversationType){const e=new Set(r),s=Array.isArray(t.receiptDetails)?t.receiptDetails.flatMap(t=>{if(!wm(t))return[];const r=t.messageId,s=t.count;return"string"==typeof r&&e.has(r)&&"number"==typeof s&&Number.isInteger(s)&&s>=0?[{messageId:r,count:s}]:[]}):[];return{messageIds:r,conversationId:n.conversationId,conversationType:"groupChat",timestamp:t.timestamp,receiptDetails:s}}return{messageIds:r,conversationId:n.conversationId,conversationType:"singleChat",timestamp:t.timestamp}}handleMessageDeliveredNotify(e){if(!wm(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(L,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!wm(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(P,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}handleMessageUpdatedNotify(e){if(!wm(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!wm(t.message)||"string"!=typeof t.message.type||!wm(t.message.body)||!wm(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...wm(t.message.modifiedInfo)?{modifiedInfo:{operatorId:"string"==typeof t.message.modifiedInfo.operatorId?t.message.modifiedInfo.operatorId:"",operationCount:"number"==typeof t.message.modifiedInfo.operationCount?t.message.modifiedInfo.operationCount:0,operationTime:"number"==typeof t.message.modifiedInfo.operationTime?t.message.modifiedInfo.operationTime:0}}:{}};this.eventHub.dispatch(D,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",message:r,timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}normalizeUpdatedMessageBody(e,t){if("text"!==e)return t;const r="string"==typeof t.content?t.content:"string"==typeof t.message?t.message:void 0;if(void 0===r)return t;const{message:s,...n}=t;return{...n,content:r}}handleChatThreadNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"onChatThreadChange"===r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(y,r)}normalizePresenceStatus(e){if(!e||"object"!=typeof e)return[];return Object.entries(e).map(([e,t])=>({device:e,status:Number(t)||0}))}destroy(){this.streamMessageHandler.destroy(),this.recentMessageIds.clear(),this.messageContexts.clear()}rememberMessageContext(e){const t=this.resolveMessageContextId(e),r=this.resolveMessageConversationContext(e);if(t&&r)for(this.messageContexts.delete(t),this.messageContexts.set(t,r);this.messageContexts.size>500;){const e=this.messageContexts.keys().next().value;if(!e)break;this.messageContexts.delete(e)}}resolveMessageReceiptContext(e,t,r){const s=this.messageContexts.get(e);return s||("groupChat"===r?{conversationId:t,conversationType:"groupChat"}:{conversationId:t,conversationType:"singleChat"})}resolveMessageContextId(e){return"string"==typeof e.msgServerId&&e.msgServerId.length>0?e.msgServerId:"string"==typeof e.msgLocalId&&e.msgLocalId.length>0?e.msgLocalId:""}resolveMessageConversationContext(e){if("string"!=typeof e.conversationId||!e.conversationId)return null;if("groupChat"===e.conversationType)return{conversationId:e.conversationId,conversationType:"groupChat"};if("chatRoom"===e.conversationType)return{conversationId:e.conversationId,conversationType:"chatRoom"};if("singleChat"!==e.conversationType)return null;const t=this.msyncCodec.getContext().userId,r="SEND"===e.direct||e.sender.userId===t?e.conversationId:e.sender.userId;return r?{conversationId:r,conversationType:"singleChat"}:null}resolveReactionConversationContext(e){const t="string"==typeof e.from?e.from:"",r="string"==typeof e.to?e.to:"",s="string"==typeof e.channel_type?e.channel_type:"";if(!t||!r)return null;if("groupChat"===s||"groupchat"===s||"group"===s)return{conversationId:r,conversationType:"groupChat",from:t,to:r};if(""!==s&&"chat"!==s&&"singleChat"!==s)return null;return{conversationId:t===this.msyncCodec.getContext().userId?r:t,conversationType:"singleChat",from:t,to:r}}normalizeReactionList(e){if(!Array.isArray(e))return[];const t=[];for(const r of e)wm(r)&&"string"==typeof r.reaction&&t.push({reaction:r.reaction,count:"number"==typeof r.count&&Number.isFinite(r.count)?r.count:0,userList:Array.isArray(r.userList)?r.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof r.isAddedBySelf?r.isAddedBySelf:void 0,op:this.normalizeReactionOperations(r.op)});return t}normalizeReactionOperations(e){if(!Array.isArray(e))return;const t=[];for(const r of e)!wm(r)||"string"!=typeof r.operator||"create"!==r.reactionType&&"delete"!==r.reactionType||t.push({operator:r.operator,reactionType:r.reactionType});return t.length>0?t:void 0}normalizeTimestamp(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){const t=Number(e);return Number.isFinite(t)?t:0}return 0}}const Sm=e=>e instanceof Error?e.message:String(e);class Tm{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Md({fetchImpl:fetch}):void 0))(e)}async downloadAndParse(e){const t=e.url.trim();if(!t)throw new Zr("Combine message url is required",{code:ir,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof e.maxItems?e.maxItems:300;hm(1,r);const s=this.requestAdapter;if(!s)throw new Yr("Request adapter is required for combine message download",{code:ur});const n=ro(t,e.secret);try{const t=await s.request({url:n,method:"GET",responseType:"arraybuffer",timeoutMs:e.timeoutMs??15e3,headers:{[ml]:pl()}});if(401===t.status||403===t.status)throw new Jr(401===t.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===t.status?dt:ut,details:{url:n,httpStatus:t.status}});if(t.status>=400)throw new Yr("Combine payload download failed",{code:ur,details:{status:t.status,url:n}});const o=(e=>{if(e.length<Jp.length+1)throw new Yr("Combine payload is too short",{code:lr});const t=e.subarray(0,Jp.length);if(t[0]!==Jp[0]||t[1]!==Jp[1])throw new Yr("Combine payload header is invalid",{code:lr});const r=e.subarray(0,e.length-1),s=rm(r),n=e[e.length-1]??0;if(n!==s)throw new Yr("Combine payload checksum failed",{code:lr,details:{expectedChecksum:s,actualChecksum:n}});const o=[];let i=Jp.length;const a=e.length-1;for(;i<a;){if(i+4>a)throw new Yr("Combine payload length header is incomplete",{code:lr});const t=tm(e,i);if(i+=4,t<=0||i+t>a)throw new Yr("Combine payload item length is invalid",{code:lr,details:{itemLength:t}});const r=e.subarray(i,i+t);i+=t;const s=am(r,o.length);o.push(s)}if(i!==a)throw new Yr("Combine payload has unexpected trailing bytes",{code:lr,details:{offset:i,expected:a}});return o})((e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if("string"==typeof e)return Ro(e);throw new Yr("Combine payload response type is invalid",{code:ur})})(t.data));return hm(o.length,r),pm(o),o.map(e=>({msgServerId:e.msgServerId??"",msgLocalId:e.msgLocalId??"",from:e.sender.userId,to:e.conversationId,sender:e.sender,conversationId:e.conversationId,conversationType:e.conversationType,type:e.type,sendStatus:"sent",ext:e.ext??{},timestamp:e.timestamp,body:e.body,direct:"RECEIVE"}))}catch(o){if(o instanceof Zr||o instanceof Jr||o instanceof Yr)throw o;throw new Yr("Combine payload download or parse failed",{code:ur,details:{cause:Sm(o),url:n}})}}}const _m=e=>{switch(e.type){case"image":return e.body.filename??"image";case"video":return e.body.filename??"video";case"voice":return e.body.filename??"voice";case"file":return e.body.filename??"file";default:return"attachment"}},Rm=e=>{switch(e.type){case"image":case"video":case"voice":case"file":return e.body.filetype??"application/octet-stream";default:return"application/octet-stream"}};class Am{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Md({fetchImpl:fetch}):void 0))(e)}async download(e,t=15e3){if("image"!==e.type&&"video"!==e.type&&"voice"!==e.type&&"file"!==e.type)throw new Zr("message does not contain downloadable attachment",{code:Ot,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:r,secret:s}=(e=>{switch(e.type){case"image":{const t=e.body;return{url:t.originalImageUrl??t.bigImageUrl??t.thumbnailUrl??"",secret:t.secret}}case"video":case"voice":case"file":{const t=e.body;return{url:t.url??"",secret:t.secret}}default:return{url:""}}})(e);if(!r)throw new Zr("attachment url is required",{code:Ot,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});if(!this.requestAdapter)throw new Vr("request adapter is required for attachment download");const n=await this.requestAdapter.request({url:ro(r,s),method:"GET",responseType:"arraybuffer",timeoutMs:t,headers:{[ml]:pl()}});if(401===n.status)throw new Jr("attachment download unauthorized",{code:dt,details:{url:r,httpStatus:n.status}});if(403===n.status)throw new Jr("attachment download forbidden",{code:ut,details:{url:r,httpStatus:n.status}});if(404===n.status){const e=("string"==typeof n.data?n.data:"").includes("expired");throw new Hr(e?"attachment file is expired":"attachment not found",e?xt:Nt)}if(429===n.status)throw new Hr("attachment download rate limited",Br);if(n.status>=400)throw new Hr("attachment download failed",er,{details:{status:n.status,url:r}});return{filename:_m(e),mimeType:Rm(e),size:(()=>{switch(e.type){case"image":case"video":case"voice":return e.body.fileLength;case"file":return e.body.fileLength??e.body.fileSize;default:return}})(),data:new Uint8Array(n.data),downloadUrl:r}}}const Mm=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[ml]:pl(),...r??{}}),Em=async e=>{const t=Mm(e.token,"application/json",e.headers),r=Date.now(),s="upload.multipart.init"===e.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===e.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",n=e.dataReportOperation?.startRequest({requestName:s,method:e.method,url:e.url});let o=0;if(So("Upload request start",{operation:e.operation,method:e.method}),e.requestAdapter)try{const s=await e.requestAdapter.request({url:e.url,method:e.method,headers:t,responseType:"json",timeoutMs:xn});o=s.status;const a=Date.now()-r;if(s.status<200||s.status>=300)throw To("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:a}),new rs("Upload request failed",{code:$r,details:{url:e.url,status:s.status}});So("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:a});const c="string"==typeof(i=s.data)?JSON.parse(i):i;return n?.finish({code:s.status,success:!0}),c}catch(d){if(n?.finish({code:0!==o?o:d instanceof rs?d.code:$r,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof rs)throw d;throw To("Upload request failed",{operation:e.operation,method:e.method}),new rs("Upload request failed",{code:$r,details:{url:e.url}})}var i;const a=new AbortController,c=setTimeout(()=>a.abort(),xn);try{const s=await fetch(e.url,{method:e.method,headers:t,signal:a.signal});o=s.status;const i=Date.now()-r;if(!s.ok)throw To("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:i}),new rs("Upload request failed",{code:$r,details:{url:e.url,status:s.status}});return So("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:i}),n?.finish({code:s.status,success:!0}),await s.json()}catch(d){if(n?.finish({code:0!==o?o:d instanceof rs?d.code:$r,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof rs)throw d;if(d instanceof Error&&"AbortError"===d.name)throw To("Upload request timeout",{operation:e.operation,method:e.method,timeout:xn}),new rs("Upload timeout",{code:qr,details:{url:e.url,timeout:xn}});throw To("Upload request failed",{operation:e.operation,method:e.method}),new rs("Upload request failed",{code:$r,details:{url:e.url}})}finally{clearTimeout(c)}},Um=(e,t,r,s,n,o)=>new Promise((i,a)=>{const c=new XMLHttpRequest,d=Date.now(),u=o?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:e});So("Upload part start",{operation:"upload.multipart.part",partNumber:r}),c.upload&&n&&c.upload.addEventListener("progress",e=>{n(e.loaded)},!1),c.addEventListener("abort",()=>{u?.finish({code:Gr,success:!1,description:"Upload aborted"}),To("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload aborted",{code:Gr,details:{url:e,partNumber:r}}))},!1),c.addEventListener("error",()=>{u?.finish({code:$r,success:!1,description:"Upload part failed"}),To("Upload part failed",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload part failed",{code:$r,details:{url:e,partNumber:r}}))},!1),c.addEventListener("timeout",()=>{u?.finish({code:qr,success:!1,description:"Upload timeout"}),To("Upload part timeout",{operation:"upload.multipart.part",partNumber:r,timeout:xn}),a(new rs("Upload timeout",{code:qr,details:{url:e,partNumber:r}}))},!1),c.addEventListener("load",()=>{const t=Date.now()-d;if(200!==c.status)return u?.finish({code:c.status,success:!1,description:"Upload part failed"}),To("Upload part error",{operation:"upload.multipart.part",partNumber:r,status:c.status,duration:t}),void a(new rs("Upload part failed",{code:$r,details:{url:e,partNumber:r,status:c.status}}));So("Upload part success",{operation:"upload.multipart.part",partNumber:r,duration:t}),u?.finish({code:c.status,success:!0}),i()},!1);const l=new FormData;l.append("part_file",s),l.append("part_number",r),c.timeout=xn,c.open("PUT",e),Object.entries(Mm(t,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{c.setRequestHeader(e,t)}),c.send(l)}),km=async e=>{if(e.fileSize<=jn)throw new rs("Multipart not required",{code:$r,details:{reason:"file size below threshold"}});const{config:t,file:r,conversationId:s,conversationType:n,fileName:o,fileType:i,fileSize:a,messageType:c,imageType:d,md5:u,width:l,height:h}=e,{orgName:p,appName:m}=Qn(t.appKey),f=`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload`;let g;try{g=await Em({url:f,method:"POST",token:t.token,operation:"upload.multipart.init",requestAdapter:t.requestAdapter,dataReportOperation:e.dataReportOperation})}catch(M){throw new rs("Multipart init failed",{code:$r,details:{stage:"init",cause:M,url:f}})}const y=(e=>{const t=e.entities?.[0],r="number"==typeof t?.file_upper_limit?t.file_upper_limit:0,s="number"==typeof t?.part_lower_limit?t.part_lower_limit:zn,n="string"==typeof t?.uuid?t.uuid:"";if(!n)throw new rs("Multipart init failed",{code:$r,details:{response:e}});return{fileMaxSize:r,partMinSize:s,uuid:n}})(g);if(y.fileMaxSize&&a>y.fileMaxSize)throw new rs("File size exceeds limit",{code:Dr,details:{fileSize:a,maxSize:y.fileMaxSize}});const v=y.partMinSize||zn,b=Math.ceil(a/v),I=Array.from({length:b},()=>0),w=`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload/${y.uuid}`,C=[],S=(t,r)=>{I[t]=r;const s=I.reduce((e,t)=>e+t,0),n=a?s/a*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:s,total:a,percent:n})};for(let E=0;E<b;E+=1){const s=E*v,n=Math.min(a,s+v),o=r.slice(s,n),i=String(E+1),c=Um(w,t.token,i,o,e=>S(E,e),e.dataReportOperation).finally(()=>{const e=C.indexOf(c);e>=0&&C.splice(e,1)});C.push(c),C.length>=4&&await Promise.race(C)}await Promise.all(C);const T=Yn(n),_=to(`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload/${y.uuid}`,{"restrict-access":"true","chat-type":T,"chat-target":s,"thumbnail-width":e.thumbnailWidth,"thumbnail-height":e.thumbnailHeight,md5:u??"",..."image"===c?{imageType:oo(d),width:l,height:h}:{}}),R=await Em({url:_,method:"POST",token:t.token,operation:"upload.multipart.complete",requestAdapter:t.requestAdapter,dataReportOperation:e.dataReportOperation}),A=ao({response:R,restBaseUrl:t.restBaseUrl,orgName:p,appName:m,fileType:i,fileName:o,fallbackSize:a,messageType:c,imageType:d,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(A),A},Nm=e=>new Promise((t,r)=>{const{config:s,file:n,conversationId:o,conversationType:i,messageType:a,imageType:c,md5:d,width:u,height:l,fileName:h,fileType:p,fileSize:m}=e,{orgName:f,appName:g}=Qn(s.appKey),y=Yn(i),v=to(`${s.restBaseUrl}/${f}/${g}/chatfiles`,{"chat-type":y,"chat-target":o,md5:d??"",..."image"===a?{imageType:oo(c),width:u,height:l}:{}}),b=Date.now(),I=e.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:v});So("Upload request start",{operation:"upload.simple",method:"POST",fileSize:m,messageType:a});const w=new XMLHttpRequest;w.upload&&e.callbacks?.onFileUploadProgress&&w.upload.addEventListener("progress",t=>{if(!t.lengthComputable)return void e.callbacks?.onFileUploadProgress?.({loaded:t.loaded});const r=t.total?t.loaded/t.total*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:t.loaded,total:t.total,percent:r})},!1),w.addEventListener("abort",()=>{I?.finish({code:Gr,success:!1,description:"Upload canceled"}),To("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.(),r(new rs("Upload canceled",{code:Gr,details:{url:v}}))},!1),w.addEventListener("error",()=>{I?.finish({code:$r,success:!1,description:"Upload failed"}),To("Upload request failed",{operation:"upload.simple"}),r(new rs("Upload failed",{code:$r,details:{url:v}}))},!1),w.addEventListener("timeout",()=>{I?.finish({code:qr,success:!1,description:"Upload timeout"}),To("Upload request timeout",{operation:"upload.simple",timeout:xn}),r(new rs("Upload timeout",{code:qr,details:{url:v,timeout:xn}}))},!1),w.addEventListener("load",()=>{try{const r=Date.now()-b,n=JSON.parse(w.responseText);if(w.status>=400)throw I?.finish({code:w.status,success:!1,description:"Upload failed"}),To("Upload response error",{operation:"upload.simple",status:w.status,duration:r}),new rs("Upload failed",{code:$r,details:{status:w.status,response:n}});So("Upload response success",{operation:"upload.simple",status:w.status,duration:r});const o=ao({response:n,restBaseUrl:s.restBaseUrl,orgName:f,appName:g,fileType:p,fileName:h,fallbackSize:m,messageType:a,imageType:c,useCustomAttachmentUpload:s.useCustomAttachmentUpload});e.callbacks?.onFileUploadComplete?.(o),I?.finish({code:w.status||200,success:!0}),t(o)}catch(n){I?.finish({code:n instanceof rs?n.code:$r,success:!1,description:n instanceof Error?n.message:String(n)}),r(n instanceof Error?n:new Error(String(n)))}},!1),w.timeout=xn,w.open("POST",v),w.setRequestHeader("restrict-access","true"),w.setRequestHeader("Accept","*/*"),w.setRequestHeader("Authorization",`Bearer ${s.token}`),w.setRequestHeader(ml,pl());const C=new FormData;C.append("file",n,h),void 0!==e.thumbnailWidth&&C.append("thumbnail-width",String(e.thumbnailWidth)),void 0!==e.thumbnailHeight&&C.append("thumbnail-height",String(e.thumbnailHeight)),w.send(C)}),Om=ru(),xm=e=>Object.prototype.toString.call(e),Lm=e=>{const t=e&&"object"==typeof e?e:null,r="string"==typeof t?.path?t.path:void 0,s="string"==typeof t?.uri?t.uri:void 0,n="string"==typeof t?.name?t.name:void 0,o="string"==typeof t?.type?t.type:void 0,i="number"==typeof t?.size?t.size:void 0;return{kind:xm(e),isFile:"undefined"!=typeof File&&e instanceof File,isBlob:"undefined"!=typeof Blob&&e instanceof Blob,hasPath:"string"==typeof r&&r.length>0,pathPrefix:r?r.slice(0,48):void 0,hasUri:"string"==typeof s&&s.length>0,uriPrefix:s?s.slice(0,48):void 0,name:n,type:o,size:i}},Pm=e=>({sourceType:e.source.sourceType,fileName:e.fileName,fileType:e.fileType,fileSize:e.fileSize,hasWebFile:Boolean(e.webFile),sourceName:e.source.name,sourceMimeType:e.source.mimeType,sourceSize:e.source.size}),Dm=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,$m=e=>"object"==typeof e&&null!==e,qm=(e,t)=>{const r=$m(t)?t:void 0,s=r?.code===Do&&r.stage===Lo;return"miniapp-path"===e&&(e=>{if(!$m(e))return!1;const t=$m(e.details)?e.details:void 0;return e.code===Do&&e.stage===Lo&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&s};class Gm{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(e,t){if(!Dm(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=Hp.get(e.msgLocalId),o=Boolean(n);if(To("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:e.msgLocalId,messageType:e.type,conversationType:e.conversationType,hasFile:o,uploadUrl:s,cachedFile:Lm(n),adapter:{hasRequestAdapter:Boolean(this.config?.requestAdapter),hasUploadAdapter:Boolean(this.config?.uploadAdapter),hasImageProcessor:Boolean(this.config?.imageProcessor),restBaseUrl:Boolean(this.config?.restBaseUrl),useCustomAttachmentUpload:this.config?.useCustomAttachmentUpload}}),!((e,t)=>!!t||!e||!Zn(e))(s,o))return e;if(!n)throw new rs("Attachment file is required",{code:Lr,details:{msgLocalId:e.msgLocalId,url:s}});if(!this.config?.restBaseUrl)throw new rs("REST base url is required for upload",{code:Lr,details:{reason:"restBaseUrl missing"}});let i,a,c;try{i=await this.prepareAttachmentUpload(e,r,n),i.precheck?.hit||(c=jp({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:e.msgLocalId,messageType:e.type})),a=i.precheck?.hit?this.buildPrecheckedUploadResult(e,i,t):await this.uploadAttachment(e,i,t,c),c?.finish({code:0,success:!0})}catch(d){const e=Qu(d);throw c?.finish({code:e.code,success:!1,description:e.message}),e.code===Gr&&t?.onFileUploadCanceled?.(),t?.onFileUploadError?.(e),e}return this.buildPreparedMessage(e,i,a)}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&Zn(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&Zn(t.url)}async prepareAttachmentUpload(e,t,r){const s=((e,t)=>{if(!e)throw new rs("Attachment file is required",{code:Lr,details:{reason:"file missing"}});const r=("number"==typeof t.fileLength?t.fileLength:void 0)??("fileSize"in t&&"number"==typeof t.fileSize?t.fileSize:void 0),s=Fn({file:e,fallbackName:t.filename,fallbackMimeType:t.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new rs("Attachment file is required",{code:Lr,details:{reason:"web file missing"}});return s})(r,t);if(To("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Pm(s)}),"image"!==e.type){return{body:t,fileInfo:s,md5FileInfo:s,precheck:await this.maybePrecheck(e,s,s,void 0)}}const n=t,o=await this.resolveImageCandidate(n,s),i={...n,width:o.width,height:o.height,isOriginalImage:o.imagePolicy.resolvedImageType===Wn},a=await this.maybePrecheck(e,o.fileInfo,s,o.imagePolicy.resolvedImageType);return{body:i,fileInfo:o.fileInfo,md5FileInfo:s,imageType:o.imagePolicy.resolvedImageType,precheck:a,originalWidth:n.width,originalHeight:n.height}}async resolveImageCandidate(e,t){const r=(e=>e.isGif?{resolvedImageType:Wn,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:Wn,reason:"explicit-original"}:{resolvedImageType:Jn,reason:"default-large"})(e);if(To("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:e.isGif,source:Pm(t)}),r.resolvedImageType===Wn){let s=e.width,n=e.height;if(!s||!n){const e=this.resolveImageProcessor(t.source.sourceType);To("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Pm(t)});const r=await e.getImageInfo(t.source);s=r.width,n=r.height}return{imagePolicy:r,sourceKind:"origin",fileInfo:t,width:s,height:n}}try{const e=this.resolveImageProcessor(t.source.sourceType);To("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Pm(t)});const s=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:r,sourceKind:"big",fileInfo:{source:s.source,fileName:s.fileName??t.fileName,fileType:s.fileType??t.fileType,fileSize:s.fileSize??t.fileSize,webFile:s.webFile},width:s.width,height:s.height}}catch(s){return To("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:s instanceof Error?s.message:String(s),source:Pm(t)}),{imagePolicy:{resolvedImageType:Wn,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,r,s){if(!Dm(e.type))return;if(!0!==this.config?.enableMd5Check)return void So("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:s,fileSize:t.fileSize});const n=so({messageType:e.type,fileSize:t.fileSize,imageType:s});if(!n.shouldPrecheck)return void So("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:s,fileSize:t.fileSize,thresholdBytes:n.thresholdBytes});let o;try{o=await this.computeMd5(r)}catch(a){if(qm(r.source.sourceType,a))return void To("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:s,thresholdType:n.thresholdType,source:Pm(r),error:a instanceof Error?a.message:String(a)});throw a}const i=await this.requestPrecheck(e,n.thresholdType,o,s);return So(i.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:i.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:s,exists:i.exists,existsType:i.existsType,uuid:i.uuid,hasShareSecret:"string"==typeof i.shareSecret&&i.shareSecret.length>0}),{...i,md5:o}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return To("Attachment md5 compute start",{operation:"upload.md5.start",source:Pm(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return To("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return To("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),Om;throw To("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),Fo("Image processor capability is missing for current platform",{code:Do,stage:Lo,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(e,t,r,s){if(!this.config)throw new rs("Upload config is required",{code:Lr});const{orgName:n,appName:o}=Qn(this.config.appKey),i=to(`${this.config.restBaseUrl}/${n}/${o}/chatfiles/exists`,{md5:r,..."image"===e.type?{imageType:oo(s)}:{}}),a=await this.requestJson({url:i,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(n=>{To("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:e.type,imageType:s,thresholdType:t,md5:r,error:n instanceof Error?n.message:String(n)})});return a?(e=>{const t=e.entities?.[0],r=!0===t?.exists,s="string"==typeof t?.uuid&&t.uuid.length>0?t.uuid:void 0,n=t,o=n?.["exists-type"]??n?.existsType,i="origin"===o?Wn:o===Jn||o===Wn?o:void 0,a="string"==typeof t?.["share-secret"]?t["share-secret"]:void 0;if(r&&!s)throw new rs("Upload precheck response missing uuid",{code:$r,details:{response:e}});return{uuid:s,exists:r,existsType:i,shareSecret:a,hit:(c={exists:r,uuid:s},c.exists&&"string"==typeof c.uuid&&c.uuid.length>0)};var c})(a):{exists:!1,hit:!1}}async requestJson(e){return this.config?.requestAdapter?this.requestByAdapter(this.config.requestAdapter,e):this.requestByFetch(e)}async requestByAdapter(e,t){const r=await e.request({url:t.url,method:t.method,headers:t.headers,responseType:"json",timeoutMs:xn});if(r.status>=400)throw new rs("Upload precheck request failed",{code:$r,details:{url:t.url,status:r.status,operation:t.operation}});return r.data}async requestByFetch(e){if("function"!=typeof fetch)throw Fo("Request capability is missing for current platform",{code:Do,stage:ko,retryable:!1,details:{operation:e.operation}});const t=new AbortController,r=setTimeout(()=>t.abort(),xn);try{const r=await fetch(e.url,{method:e.method,headers:e.headers,signal:t.signal});if(!r.ok)throw new rs("Upload precheck request failed",{code:$r,details:{url:e.url,status:r.status,operation:e.operation}});return await r.json()}finally{clearTimeout(r)}}buildPrecheckedUploadResult(e,t,r){if(!this.config||!t.precheck)throw new rs("Precheck result is required",{code:$r});if(!t.precheck.uuid)throw new rs("Precheck hit missing uuid",{code:$r,details:{precheck:t.precheck}});if(!Dm(e.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:e.type}});const{orgName:s,appName:n}=Qn(this.config.appKey),o="image"===e.type?t.precheck.existsType??t.imageType:void 0,i="image"===e.type&&o===Wn?t.md5FileInfo:t.fileInfo,a="image"===e.type&&o===Wn?t.originalWidth:"image"===e.type?t.body.width:void 0,c="image"===e.type&&o===Wn?t.originalHeight:"image"===e.type?t.body.height:void 0,d={entities:[{uuid:t.precheck.uuid,...t.precheck.shareSecret?{"share-secret":t.precheck.shareSecret}:{}}]},u=ao({response:d,restBaseUrl:this.config.restBaseUrl,orgName:s,appName:n,fileType:i.fileType,fileName:i.fileName,fallbackSize:i.fileSize,messageType:e.type,imageType:o,width:a,height:c,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return r?.onFileUploadComplete?.(u),u}async uploadAttachment(e,t,r,s){if(!this.config)throw new rs("Upload config is required",{code:Lr});if(!Dm(e.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:e.type}});const n=e.type,o=await this.resolveUploadMetadata(n,t);if(this.config.uploadAdapter)return To("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:n,source:Pm(t.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,e,t,o,r);if(!t.fileInfo.webFile)throw new rs("Upload adapter is required for non-web file source",{code:Lr,details:{sourceType:t.fileInfo.source.sourceType}});const i={message:e,file:t.fileInfo.webFile,conversationId:e.conversationId,conversationType:e.conversationType,messageType:n,imageType:t.imageType,md5:o.md5,width:o.width,height:o.height,fileName:t.fileInfo.fileName,fileType:t.fileInfo.fileType,fileSize:t.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(n,t.body),thumbnailHeight:this.resolveThumbnailHeight(n,t.body),callbacks:r,config:this.config,dataReportOperation:s},a=!1!==this.config?.enableMultipartUpload,c=a&&t.fileInfo.fileSize>jn;if(To("Attachment web upload selected",{operation:"upload.web.selected",messageType:n,source:Pm(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await km(i)}catch(d){const e=d instanceof rs?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return Nm(i);throw d}return Nm(i)}async uploadByAdapter(e,t,r,s,n){if(!this.config)throw new rs("Upload config is required",{code:Lr});const{orgName:o,appName:i}=Qn(this.config.appKey),a=Yn(t.conversationType);if(!Dm(t.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:t.type}});const c=t.type,d=to(`${this.config.restBaseUrl}/${o}/${i}/chatfiles`,{"chat-type":a,"chat-target":t.conversationId,md5:s.md5,..."image"===c?{imageType:oo(r.imageType),width:s.width,height:s.height}:{}}),u={},l={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[ml]:pl()},h=this.resolveThumbnailWidth(c,r.body),p=this.resolveThumbnailHeight(c,r.body);void 0!==h&&(u["thumbnail-width"]=String(h)),void 0!==p&&(u["thumbnail-height"]=String(p)),To("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:c,source:Pm(r.fileInfo),uploadUrl:d,fields:u});const m=await e.upload({url:d,headers:l,source:r.fileInfo.source,fields:u,onProgress:e=>{n?.onFileUploadProgress?.(e)}});if(m.status>=400){const e=m.body??"",t=413===m.status?tr:"string"==typeof e&&e.includes("content improper")?rr:$r;throw new rs("Upload failed",{code:t,details:{status:m.status,response:m.body}})}let f;try{f=JSON.parse(m.body)}catch(y){throw new rs("Upload response parse failed",{code:$r,details:{response:m.body,cause:y instanceof Error?y.message:String(y)}})}const g=ao({response:f,restBaseUrl:this.config.restBaseUrl,orgName:o,appName:i,fileType:r.fileInfo.fileType,fileName:r.fileInfo.fileName,fallbackSize:r.fileInfo.fileSize,messageType:c,imageType:r.imageType,width:s.width,height:s.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(g),g}buildPreparedMessage(e,t,r){if("image"===e.type){const s=t.body,n={...e,body:{...s,isOriginalImage:r.isOriginalImage??s.isOriginalImage,originalImageUrl:r.originalImageUrl??s.originalImageUrl,bigImageUrl:r.bigImageUrl??s.bigImageUrl,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl,width:r.width??s.width,height:r.height??s.height}};return ah(e,n),hh(e,n),n}if("video"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl}};return ah(e,n),n}if("voice"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return ah(e,n),n}if("combine"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return ah(e,n),n}const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return ah(e,n),n}resolveThumbnailWidth(e,t){if("video"===e){const e="width"in t?t.width:void 0;return"number"==typeof e&&e>0?e:void 0}}resolveThumbnailHeight(e,t){if("video"===e){const e="height"in t?t.height:void 0;return"number"==typeof e&&e>0?e:void 0}}async resolveUploadMetadata(e,t){let r=t.precheck?.md5??"";if(!t.precheck)try{r=await this.computeMd5(t.md5FileInfo)}catch(n){if(!qm(t.md5FileInfo.source.sourceType,n))throw n;To("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Pm(t.md5FileInfo),error:n instanceof Error?n.message:String(n)})}const s=t.body;return{md5:r,width:"image"===e&&"number"==typeof s.width&&s.width>0?s.width:void 0,height:"image"===e&&"number"==typeof s.height&&s.height>0?s.height:void 0}}}class Bm{constructor(e,t){this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null,this.runtime=e,this.handlers=t}start(){this.unsubscribeNetwork||this.unsubscribeVisibility||(this.unsubscribeNetwork=this.runtime.onNetworkChange(e=>{this.handleNetworkChange(e)}),this.unsubscribeVisibility=this.runtime.onAppVisibilityChange(e=>{this.handleVisibilityChange(e)}))}stop(){this.unsubscribeNetwork?.(),this.unsubscribeVisibility?.(),this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null}handleNetworkChange(e){this.lastOnline!==e&&(this.lastOnline=e,e?this.handlers.onOnline():this.handlers.onOffline())}handleVisibilityChange(e){this.lastForeground!==e&&(this.lastForeground=e,e?this.handlers.onForeground():this.handlers.onBackground())}}const Fm="__internal:core";class jm{constructor(e,t){this.runtimeEventBridge=null,this.handleOnline=()=>{this.connectionManager.handleOnline()},this.handleOffline=()=>{this.connectionManager.handleOffline()},this.handleForegroundChange=e=>{e&&this.connectionManager.handleForeground()},this.eventHub=t,this.connectionManager=new Kp({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new Gm({restBaseUrl:e.restBaseUrl,token:e.token,appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,enableMultipartUpload:e.enableMultipartUpload,requestAdapter:e.platformAdapter?.request,uploadAdapter:e.platformAdapter?.upload,imageProcessor:e.platformAdapter?.imageProcessor}):void 0;this.messageSender=new ym(r,null,this.eventHub,s),this.messageReceiver=new Cm(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Tm(e.platformAdapter?.request),this.attachmentDownloader=new Am(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(Fm,{[a]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[c]:e=>{this.messageSender.setWebSocket(null)},[d]:e=>{this.messageSender.setWebSocket(null)},[b]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new Bm(e,{onOnline:this.handleOnline,onOffline:this.handleOffline,onForeground:()=>{this.handleForegroundChange(!0)},onBackground:()=>{this.handleForegroundChange(!1)}}),this.runtimeEventBridge.start()}unregisterNetworkListeners(){this.runtimeEventBridge?.stop(),this.runtimeEventBridge=null}resolveRuntimeAdapter(){return this.platformAdapter?this.platformAdapter.runtime:this.createBrowserRuntimeAdapter()}createBrowserRuntimeAdapter(){return{getPlatform:()=>"web",onNetworkChange(e){if("undefined"==typeof window)return()=>{};const t=()=>{e(!0)},r=()=>{e(!1)};return window.addEventListener("online",t),window.addEventListener("offline",r),"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine&&e(navigator.onLine),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}},onAppVisibilityChange(e){if("undefined"==typeof document)return()=>{};const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),t(),()=>{document.removeEventListener("visibilitychange",t)}}}}async connect(){return this.connectionManager.connect()}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}getClientResource(){return this.connectionManager.getClientResource()}renewToken(e,t){const r=this.connectionManager.renewToken(e,t);return this.messageSender.updateAuthToken(e),r}async sendMessage(e,t){return this.messageSender.sendMessage(e,t)}async sendMessageAction(e,t){return this.messageSender.sendAction(e,t)}async sendChatRoomOperation(e,t){return this.messageSender.sendChatRoomOperation(e,t)}async downloadAndParseCombineMessage(e){return this.combineMessageDownloader.downloadAndParse(e)}async downloadAttachment(e,t){return this.attachmentDownloader.download(e,t)}decodeServerMessageMeta(e){return this.connectionManager.getMsyncCodec().decodeServerMessageMeta(e)}destroy(){this.unregisterNetworkListeners(),this.connectionManager.destroy(),this.messageSender.destroy(),this.messageReceiver.destroy(),this.eventHub.removeEventHandler(Fm),Hp.clear()}}const zm=e=>{if(e.length>=1048576){const t=[],r=32768;for(let s=0;s<e.length;s+=r)t.push(String.fromCharCode(...e.subarray(s,s+r)));return btoa(t.join(""))}let t="";for(let r=0;r<e.length;r+=1){const s=e[r];void 0!==s&&(t+=String.fromCharCode(s))}return btoa(t)},Km=e=>{const t=atob(e),r=new Uint8Array(new ArrayBuffer(t.length));for(let s=0;s<t.length;s+=1)r[s]=t.charCodeAt(s);return r};class Hm{getCrypto(){return Wo().crypto}constructor(e,t){if(this.enabled=(()=>{const e=Wo();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const t=di(e);if("web"!==t.framework&&"worker"!==t.framework&&t.platform!==Eo.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const r=`${e}:${t}`;this.keyPromise=this.deriveKey(r)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,r=new TextEncoder,s=this.getCrypto().getRandomValues(new Uint8Array(12)),n=r.encode(e),o=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:s},t,n),i={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:zm(s),ct:zm(new Uint8Array(o))};return JSON.stringify(i)}async decrypt(e){if(!this.enabled||!this.keyPromise)return e;let t;try{t=JSON.parse(e)}catch{return e}if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return!0===t.__enc&&1===t.v&&"AES-GCM"===t.alg&&"SHA-256"===t.kdf&&"string"==typeof t.iv&&"string"==typeof t.ct})(t))return e;try{const e=await this.keyPromise,r=Km(t.iv),s=Km(t.ct),n=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:r},e,s);return(new TextDecoder).decode(n)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),r=this.getCrypto(),s=await r.subtle.digest("SHA-256",t);return r.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const Vm="conversationMap",Wm="userInfoMap",Jm="groupNamecardMap",Zm="contactRelationMap",Qm="contactVersion",Ym="contactMeta",Xm="sessionListMap",ef="sessionListCheckpoint",tf="joinedGroupPreview",rf="metadata",sf=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class nf{constructor(e,t,r){this.store=e,this.key=t,this.schemaVersion=r}async load(){const e={schemaVersion:this.schemaVersion,lastFlush:0},t=await this.store.readAsync(this.key,e);return t.schemaVersion!==this.schemaVersion?e:t}async save(e){await this.store.writeAsync(this.key,e)}async touchLastFlush(){const e={schemaVersion:this.schemaVersion,lastFlush:Date.now()};return await this.save(e),e}}const of=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=Wo().localStorage;return t&&"function"==typeof t.getItem?t:null};class af{constructor(e,t){this.storage=t??af.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!af.checkAvailable())return null;const e=of();return e?{getItem:t=>Promise.resolve(e.getItem(t)),setItem:(t,r)=>(e.setItem(t,r),Promise.resolve()),removeItem:t=>(e.removeItem(t),Promise.resolve())}:null}static checkAvailable(){const e=of();if(!e)return!1;try{const t="__im_sdk_cache_test__";return e.setItem(t,"1"),e.removeItem(t),!0}catch{return!1}}async readAsync(e,t){if(!this.storage)return t;try{const r=await this.storage.getItem(e);if(!r)return t;let s=r;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(r);if(null===e)return t;s=e}return Rl(s,t)}catch(r){return To("CacheStore read failed",r),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,r){if(!this.storage)return;const s=(e=>{try{return JSON.stringify(e)}catch{return null}})(t);if(null!==s)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(s):s;await this.storage.setItem(e,t)}catch(n){if(mu(n))throw n;if(r)throw n;To("CacheStore write failed",n)}else if(r)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){To("CacheStore remove failed",t)}}}const cf={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},df={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class uf{constructor(){this.items=new Map,this.versionState=cf,this.meta=df}load(e,t,r){this.items.clear();for(const s of e){const e=this.normalizeRecord(s);e&&this.items.set(e.userId,e)}this.versionState=this.normalizeVersionState(t),this.meta=this.normalizeMeta(r)}getAll(){return Array.from(this.items.values()).sort((e,t)=>e.addTs!==t.addTs?e.addTs-t.addTs:e.userId.localeCompare(t.userId))}getVersionState(){return this.versionState}getMeta(){return this.meta}getUserIds(){return Array.from(this.items.keys())}replaceAll(e){this.items.clear(),this.upsert(e)}upsert(e){for(const t of e){const e=this.normalizeRecord(t);e&&this.items.set(e.userId,e)}}addByNotice(e,t){const r=e.trim();return!!r&&(!this.items.has(r)&&(this.items.set(r,{userId:r,remark:"",sign:"",addTs:t,updatedAt:t,metadataUpdatedAt:t}),!0))}remove(e){return this.items.delete(e)}updateRemark(e,t,r){const s=this.items.get(e);return!(!s||s.remark===t)&&(this.items.set(e,{...s,remark:t,updatedAt:r}),!0)}setVersionState(e){this.versionState=this.normalizeVersionState(e)}updateVersionFromNotice(e,t){const r=e.trim();return!!r&&((this.versionState.version!==r||"roster_notice"!==this.versionState.lastVersionSource)&&(this.versionState={version:r,lastVersionCheckAt:t,lastVersionSource:"roster_notice"},!0))}setMeta(e){this.meta=this.normalizeMeta(e)}updateMeta(e){this.meta={cacheIntegrity:e.cacheIntegrity,reason:"complete"===e.cacheIntegrity?void 0:e.reason,lastSyncTs:e.lastSyncTs??this.meta.lastSyncTs,lastSuccessfulVersion:e.lastSuccessfulVersion??this.meta.lastSuccessfulVersion,lastSyncMode:e.lastSyncMode??this.meta.lastSyncMode}}computeIntegrity(e){if(0===this.items.size&&!this.meta.lastSuccessfulVersion)return{...this.meta,cacheIntegrity:"incomplete",reason:"first_sync_pending"};const t=new Set(e.map(e=>e.userId));return this.getUserIds().some(e=>!t.has(e))?{...this.meta,cacheIntegrity:"incomplete",reason:"user_info_missing"}:{...this.meta,cacheIntegrity:"complete",reason:void 0}}buildSnapshot(e,t){const r=new Map(e.map(e=>[e.userId,e])),s=this.getAll().map(e=>{const t=r.get(e.userId);return{userId:e.userId,userInfo:{userId:e.userId,nickname:t?.nickname,avatarUrl:t?.avatarUrl,sign:t?.sign??e.sign,ext:t?.ext},remark:e.remark,addTs:e.addTs}}),n="complete"===this.computeIntegrity(e).cacheIntegrity;return{items:s,source:t,version:this.versionState.version||this.meta.lastSuccessfulVersion,complete:n}}normalizeRecord(e){if(!_l(e))return null;const t="string"==typeof e.userId?e.userId:"";return t?{userId:t,remark:"string"==typeof e.remark?e.remark:"",sign:"string"==typeof e.sign?e.sign:"",addTs:"number"==typeof e.addTs?e.addTs:0,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:0,metadataUpdatedAt:"number"==typeof e.metadataUpdatedAt?e.metadataUpdatedAt:0}:null}normalizeVersionState(e){return _l(e)?{version:"string"==typeof e.version?e.version:"",lastVersionCheckAt:"number"==typeof e.lastVersionCheckAt?e.lastVersionCheckAt:0,lastVersionSource:"metadata"===e.lastVersionSource||"sync_page"===e.lastVersionSource||"roster_notice"===e.lastVersionSource?e.lastVersionSource:"metadata"}:cf}normalizeMeta(e){return _l(e)?{cacheIntegrity:"complete"===e.cacheIntegrity?"complete":"incomplete",reason:"quota_exceeded"===e.reason||"user_info_missing"===e.reason||"corrupted"===e.reason||"manual_reset"===e.reason||"first_sync_pending"===e.reason?e.reason:void 0,lastSyncTs:"number"==typeof e.lastSyncTs?e.lastSyncTs:0,lastSuccessfulVersion:"string"==typeof e.lastSuccessfulVersion?e.lastSuccessfulVersion:"",lastSyncMode:"full"===e.lastSyncMode||"incremental"===e.lastSyncMode||"skipped"===e.lastSyncMode?e.lastSyncMode:"skipped"}:df}}const lf=(e,t,r)=>{if(t<=0)return{kept:e,removed:[]};const s=[],n=[];for(const o of e)r-o.lastUpdate>t?n.push(o):s.push(o);return{kept:s,removed:n}},hf=(e,t)=>{if(t<=0||0===e.length)return{kept:e,removed:[]};const r=[...e].sort((e,t)=>e.lastAccess-t.lastAccess).slice(0,t),s=new Set(r);return{kept:e.filter(e=>!s.has(e)),removed:r}},pf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const o=s;t.has(o)||(t.add(o),r.push(o))}return r};class mf{constructor(){this.items=[]}load(e,t){const r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r}getAll(){return this.items}setAll(e){this.items=[...e]}updateLastAccess(e,t){if(0===e.length)return!1;let r=!1;for(const s of e){const e=this.findIndex(s.conversationId,s.type);if(e<0)continue;const n=this.items[e];n&&(n.lastAccess!==t&&(this.items[e]={...n,lastAccess:t},r=!0))}return r}removeExpired(e,t){const r=lf(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=hf(this.items,e);return this.items=[...t.kept],t.removed.length>0}trimMax(e){if(!e||this.items.length<=e)return!1;const t=[...this.items].sort((e,t)=>e.lastAccess-t.lastAccess),r=Math.max(this.items.length-e,0),s=t.slice(0,r),n=new Set(s);return this.items=this.items.filter(e=>!n.has(e)),s.length>0}findIndex(e,t){return this.items.findIndex(r=>r.conversationId===e&&r.type===t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;const r=e;if("string"!=typeof r.conversationId||0===r.conversationId.length)return null;const s="single"===(n=r.type)||"chat"===n||"singleChat"===n?"singleChat":"group"===n||"groupchat"===n||"groupChat"===n?"groupChat":"room"===n||"chatroom"===n||"chatRoom"===n?"chatRoom":null;var n;if(!s)return null;const o=this.normalizeMessage(r.lastMessage);return{conversationId:r.conversationId,type:s,lastMessage:o,unreadCount:"number"==typeof r.unreadCount?r.unreadCount:0,isPinned:"boolean"==typeof r.isPinned?r.isPinned:void 0,pinnedTime:"number"==typeof r.pinnedTime?r.pinnedTime:void 0,marks:pf(r.marks),lastAccess:"number"==typeof r.lastAccess?r.lastAccess:0,lastUpdate:"number"==typeof r.lastUpdate?r.lastUpdate:t}}normalizeMessage(e){if(!e||"object"!=typeof e)return null;if(!_l(e))return null;const t="string"==typeof e.msgId?e.msgId:"",r="string"==typeof e.type?e.type:"",s="number"==typeof e.timestamp?e.timestamp:0,n=_l(e.body)?e.body:{},o="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,i="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:r,body:n,timestamp:s,userInfoUpdateTime:o,namecardUpdateTime:i}:null}}const ff=(e,t)=>`${e}:${t}`;class gf{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(ff(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=ff(e,t),o=this.items.get(n);return o?(s&&this.items.set(n,{...o,lastAccess:r}),o):null}getByGroupId(e,t,r){const s=[];for(const n of this.items.values())n.groupId===e&&(s.push(n),r&&this.items.set(ff(n.groupId,n.userId),{...n,lastAccess:t}));return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=ff(e.groupId,e.userId),n=this.items.get(s);this.items.set(s,{...e,lastAccess:n?.lastAccess??e.lastAccess,lastUpdate:t})}}remove(e){for(const t of e)this.items.delete(ff(t.groupId,t.userId))}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),o=lf(n,e,t),i=new Set(o.removed.map(e=>ff(e.groupId,e.userId)));this.items.clear();for(const a of s)i.has(ff(a.groupId,a.userId))||this.items.set(ff(a.groupId,a.userId),a);return o.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=hf(s,Math.min(e,s.length)),o=new Set(n.removed.map(e=>ff(e.groupId,e.userId)));this.items.clear();for(const i of r)o.has(ff(i.groupId,i.userId))||this.items.set(ff(i.groupId,i.userId),i);return n.removed.length>0}trimMax(e,t=new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!_l(e))return null;const r="string"==typeof e.groupId?e.groupId:"",s="string"==typeof e.userId?e.userId:"";if(!r||!s)return null;return{groupId:r,userId:s,namecard:"string"==typeof e.namecard?e.namecard:"",namecardUpdateTime:"number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const yf=100,vf=3e3,bf=e=>({...e}),If=e=>"object"==typeof e&&null!==e,wf=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 Cf{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:yf,serverLimit:vf,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:yf,serverLimit:vf,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return If(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:wf(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,yf),this.meta=(e=>{const t=If(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:yf,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:vf,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=>bf(e)).slice(0,yf),this.meta={...e.meta,source:"localPreview",storageLimit:yf,serverLimit:vf,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>bf(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>bf(e)),meta:{...this.meta,source:"localPreview"}}}}const Sf=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Tf=e=>{const t={...e};return delete t.type,t},_f=e=>{if(!_l(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!_l(e.body))return null;const r=((e,t)=>{if(_l(e)&&"string"==typeof e.userId){const t={userId:e.userId};return"string"==typeof e.nickname&&(t.nickname=e.nickname),"string"==typeof e.avatarUrl&&(t.avatarUrl=e.avatarUrl),t}return t?{userId:t}:null})(e.sender,e.from);if(!r)return null;const s=Sf(e.conversationType),n=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),o=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),i=(e=>{if(_l(e)&&"string"==typeof e.operatorId&&"number"==typeof e.operationCount&&"number"==typeof e.operationTime)return{operatorId:e.operatorId,operationCount:e.operationCount,operationTime:e.operationTime}})(e.modifiedInfo),a="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,c="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return{msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:r,body:Tf(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...s?{conversationType:s}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...n?{sendStatus:n}:{},...o?{direct:o}:{},...i?{modifiedInfo:i}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},Rf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const o=s;t.has(o)||(t.add(o),r.push(o))}return r},Af=(e,t)=>{const r="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,s="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(r!==s)return s-r;const n=e.lastMessageAt??e.updatedAt,o=t.lastMessageAt??t.updatedAt;return n!==o?o-n:e.conversationId.localeCompare(t.conversationId)};class Mf{constructor(){this.items=[]}load(e,t){const r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r.sort(Af)}getAll(){return this.items}setAll(e){const t=Date.now(),r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r.sort(Af)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!_l(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=Sf(r.conversationType);if(!n)return null;const o="string"==typeof r.conversationName&&r.conversationName.length>0?r.conversationName:s,i="string"==typeof r.conversationAvatar?r.conversationAvatar:void 0;return{conversationId:s,conversationType:n,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:_f(e.lastMessage),lastMessageAt:"number"==typeof e.lastMessageAt?e.lastMessageAt:void 0,isPinned:"boolean"==typeof e.isPinned?e.isPinned:void 0,pinnedTimestamp:"number"==typeof r.pinnedTimestamp?r.pinnedTimestamp:void 0,marks:Rf(e.marks),readAt:"number"==typeof r.readAt?r.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:o,conversationAvatar:i,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class Ef{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,r){const s=[];for(const n of e){const e=this.items.get(n);e&&(s.push(e),r&&this.items.set(n,{...e,lastAccess:t}))}return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=this.items.get(e.userId),n=s?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:n,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),o=lf(n,e,t),i=new Set(o.removed.map(e=>e.userId));this.items.clear();for(const a of s)i.has(a.userId)||this.items.set(a.userId,a);return o.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=hf(s,Math.min(e,s.length)),o=new Set(n.removed.map(e=>e.userId));this.items.clear();for(const i of r)o.has(i.userId)||this.items.set(i.userId,i);return n.removed.length>0}trimMax(e,t=new Set){if(e<=0||this.items.size<=e)return!1;const r=Array.from(this.items.values()),s=Math.max(r.length-e,0);return this.evictByLru(s,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!_l(e))return null;const r="string"==typeof e.userId?e.userId:"";if(!r)return null;return{userId:r,nickname:"string"==typeof e.nickname?e.nickname:void 0,avatarUrl:"string"==typeof e.avatarUrl?e.avatarUrl:void 0,sign:"string"==typeof e.sign?e.sign:void 0,ext:"string"==typeof e.ext?e.ext:void 0,userInfoUpdateTime:"number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const Uf=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,kf=e=>e.lastMessageAt??e.updatedAt,Nf=e=>[...e].sort((e,t)=>{const r=Uf(t)-Uf(e);if(0!==r)return r;const s=kf(t)-kf(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),Of=e=>`${e.conversationType}:${e.conversationId}`,xf=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Lf=(e,t)=>((e,t)=>kf(t)>kf(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:xf(e,t),lastMessageAt:Math.max(e.lastMessageAt??0,t.lastMessageAt??0),isPinned:t.isPinned??e.isPinned,pinnedTimestamp:"number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:e.pinnedTimestamp,marks:t.marks.length>0?t.marks:e.marks,readAt:t.readAt??e.readAt,remindType:t.remindType??e.remindType,conversationName:t.conversationName===t.conversationId?e.conversationName:t.conversationName,conversationAvatar:t.conversationAvatar??e.conversationAvatar,updatedAt:Math.max(e.updatedAt,t.updatedAt)}:e,Pf=e=>{const t=new Map,r=new Set;for(const o of e.snapshot)r.add(Of(o));for(const o of e.existing)t.set(Of(o),o);const s=e.snapshot.map(e=>{const r=t.get(Of(e));return r?Lf(e,r):e}),n=e.existing.filter(t=>!r.has(Of(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Nf([...s,...n])},Df=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],$f=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),qf=e=>({userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,lastAccess:e.lastAccess,lastUpdate:e.lastModified});class Gf{constructor(){this.records=new Map}clear(){this.records.clear()}get(e,t=!1,r=Date.now()){const s=this.records.get(e)??null;if(!s||!t)return s;const n={...s,lastAccess:r};return this.records.set(e,n),n}setAll(e,t=Date.now()){for(const r of e){const e=r.lastModified??t,s=this.records.get(r.profile.userId),n=s?.lastAccess??t;this.records.set(r.profile.userId,{profile:r.profile,lastModified:e,lastAccess:n,source:r.source})}}applyPatch(e,t,r=Date.now()){const s=this.records.get(e.userId),n={userId:e.userId,...t??{},...s?.profile??{}};if(s&&e.lastModified<s.lastModified)return{applied:!1,reason:"stale",record:s};const o={...n,...e.attributes,userId:e.userId};if(s&&e.lastModified===s.lastModified&&(i=s.profile,a=o,Df.every(e=>i[e]===a[e])))return{applied:!1,reason:"duplicate",record:s};var i,a;const c={profile:o,lastModified:e.lastModified,lastAccess:s?.lastAccess??r,source:"subscription"===e.source?"subscription_notify":"contact"===e.source?"contact_notify":"own_notify"};return this.records.set(e.userId,c),{applied:!0,reason:"applied",record:c}}}const Bf=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class Ff{constructor(e){this.conversationDeletionTimestamps=new Map,this.currentConversation=null,this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.flushTimer=null,this.flushIdleHandle=null,this.activeFlushPromise=null,this.sessionListCommitInProgress=!1,this.mutationRevision=0,this.domainRevisions=new Map,this.pendingDirtyRevisions=new Map,this.userId=e.userId,this.config={schemaVersion:1,ttlSeconds:86400,flushIntervalMs:1e3,maxUserInfoCount:1e3,maxGroupNamecardCount:1e3,maxConversations:e.config?.maxConversations,...e.config};const t="off"===e.cacheEncryptionMode?null:new Hm(e.appKey,e.userId);this.store=new af(t??void 0,e.storageAdapter);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=sf(r,Vm),this.userInfoKey=sf(r,Wm),this.groupNamecardKey=sf(r,Jm),this.sessionListKey=sf(r,Xm),this.sessionListCheckpointKey=sf(r,ef),this.joinedGroupPreviewKey=sf(r,tf),this.contactRelationKey=sf(r,Zm),this.contactVersionKey=sf(r,Qm),this.contactMetaKey=sf(r,Ym),this.metadataKey=sf(r,rf),this.metadataStore=new nf(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new mf,this.userInfoCache=new Ef,this.groupNamecardCache=new gf,this.sessionListCache=new Mf,this.joinedGroupPreviewCache=new Cf,this.contactCache=new uf,this.userInfoRuntimeStore=new Gf,this.loadPromise=this.loadFromStorage()}getConfig(){return this.config}async prepare(){await this.loadPromise}loadConversationSummaries(){return this.conversationCache.getAll()}loadSessionList(){return this.sessionListCache.exportItems()}loadJoinedGroupPreviewSnapshot(){return this.joinedGroupPreviewCache.getSnapshot()}applyJoinedGroupPreviewSnapshot(e){this.joinedGroupPreviewCache.setSnapshot(e),this.scheduleFlush(["joinedGroupPreview"])}async commitJoinedGroupPreviewSnapshot(e){this.activeFlushPromise&&await this.activeFlushPromise;const t=this.getDomainRevision("joinedGroupPreview"),r=new Cf;if(r.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,r.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const s=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==s&&s<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),r=t.items.filter(t=>t.groupId!==e);return r.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:r,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let r=!1,s=!1;const n=this.conversationCache.getAll().map(n=>n.conversationId!==e.conversationId||n.type!==e.type?n:(r=!0,0===n.unreadCount?n:(s=!0,{...n,unreadCount:0,lastUpdate:t})));let o=!1;const i=this.sessionListCache.getAll().map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:(r=!0,0===s.unreadCount&&s.readAt===t?s:(o=!0,{...s,unreadCount:0,readAt:t,updatedAt:t})));return s||o?(s&&this.conversationCache.setAll(n),o&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:r}):{items:this.sessionListCache.exportItems(),changed:!1,matched:r}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),r=this.conversationCache.getAll(),s=r.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),n=this.sessionListCache.getAll(),o=n.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),i=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,o);return i||a?(i&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),r=this.conversationCache.getAll(),s=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:{...r,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),n=this.sessionListCache.getAll(),o=n.map(r=>r.conversationId!==e.conversationId||r.conversationType!==e.type?r:{...r,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),i=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,o);return i||a?(i&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),r=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,r,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),r=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(r,e.deletedAt))}const s=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),n=r.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),o=s.length!==t.length,i=n.length!==r.length;return o||i?(o&&this.conversationCache.setAll(s),i&&this.sessionListCache.setAll(n),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),n=this.conversationCache.getAll(),o=n.map(e=>{const n=`${e.type}:${e.conversationId}`;if(!t.has(n))return e;const o=s(e.marks);return this.areConversationMarksEqual(o,e.marks)?e:{...e,marks:o,lastUpdate:r}}),i=this.sessionListCache.getAll(),a=i.map(e=>{const n=`${e.conversationType}:${e.conversationId}`;if(!t.has(n))return e;const o=s(e.marks);return this.areConversationMarksEqual(o,e.marks)?e:{...e,marks:o,updatedAt:r}}),c=!this.isConversationListEqual(n,o),d=!this.isSessionListEqual(i,a);return c||d?(c&&this.conversationCache.setAll(o),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,r){const s=Date.now(),n=e.map(e=>({...e,updatedAt:e.lastMessageAt??s})),o=Pf({snapshot:n,existing:this.sessionListCache.getAll(),syncStartedAt:r?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(o,s)),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}mergeSessionListIncremental(e,t){this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e))),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}async commitSessionListSync(e){this.activeFlushPromise&&await this.activeFlushPromise,this.sessionListCommitInProgress=!0;let t=[],r=this.getDomainRevision("sessionList");try{let s=!1;for(;!s;){const n=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),r=this.getDomainRevision("sessionList"),r===n&&(s=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const n=this.pendingDirtyRevisions.get("sessionList");return void 0!==n&&n<=r&&this.pendingDirtyRevisions.delete("sessionList"),await this.metadataStore.touchLastFlush(),{items:this.sessionListCache.exportItems(),checkpoint:this.sessionListCheckpoint}}finally{this.sessionListCommitInProgress=!1,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}setUserInfoSummaries(e){const t=Date.now();this.userInfoCache.setAll(e,t),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}upsertRuntimeUserInfos(e){0!==e.length&&this.userInfoRuntimeStore.setAll(e)}getRuntimeUserInfo(e,t=!1){return this.userInfoRuntimeStore.get(e,t)?.profile??null}applyUserInfoNotifyPatch(e){const t=this.userInfoCache.getByIds([e.userId],Date.now(),!1)[0],r=t?$f(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([qf(t)])}getUserInfoSummaries(e,t){const r=Date.now(),s=this.userInfoCache.getByIds(e,r,t);return t&&this.scheduleFlush(["userInfo"]),s}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,r){const s=this.groupNamecardCache.get(e,t,Date.now(),r);return r&&s&&this.scheduleFlush(["groupNamecard"]),s}setGroupNamecards(e){const t=Date.now();this.groupNamecardCache.setAll(e,t),"number"==typeof this.config.maxGroupNamecardCount&&this.groupNamecardCache.trimMax(this.config.maxGroupNamecardCount),this.scheduleFlush(["groupNamecard"])}removeGroupNamecards(e){this.groupNamecardCache.remove(e),this.scheduleFlush(["groupNamecard"])}setContactVersionState(e){this.contactCache.setVersionState(e),this.scheduleFlush(["contactVersion"])}markContactCacheIncomplete(e){this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:e}),this.scheduleFlush(["contactMeta"])}applyContactSync(e){const t=this.loadContactSnapshot("cache"),r=Date.now();this.userInfoCache.setAll(e.userInfos.map(e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext,lastAccess:r,lastUpdate:r})),r),"full"===e.mode?this.contactCache.replaceAll(e.relations):this.contactCache.upsert(e.relations),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.contactCache.setVersionState({version:e.version,lastVersionCheckAt:r,lastVersionSource:"sync_page"}),this.contactCache.updateMeta({cacheIntegrity:"complete",lastSyncTs:e.lastSyncTs,lastSuccessfulVersion:e.version,lastSyncMode:e.mode}),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactRelation","contactVersion","contactMeta"]);const s=this.loadContactSnapshot("sync");return{snapshot:s,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(s)}}refreshSessionListDisplayFromUserInfos(e){const t=new Map;for(const d of e){if(!d.userId)continue;const e=t.get(d.userId);"number"==typeof e&&"number"==typeof d.lastModified&&e>=d.lastModified||t.set(d.userId,d.lastModified)}if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=this.loadContactSnapshot("cache").items,n=new Map(s.map(e=>[e.userId,e])),o=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),i=this.sessionListCache.getAll().map(e=>{let s=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,o)){const t=n.get(e.conversationId),i=this.resolveSessionDisplayUserInfo(e.conversationId,o),a=this.buildSingleSessionDisplayFields(e.conversationId,t,i,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(s={...s,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:r})}const i=s.lastMessage;if(i&&!this.shouldSkipSessionUserDisplayRefresh(i.sender.userId,t,o)){const e=n.get(i.sender.userId),t=this.resolveSessionDisplayUserInfo(i.sender.userId,o),a=this.buildSessionMessageSender(i.sender.userId,i.sender,e,t);this.isSenderEqual(i.sender,a)||(s={...s,lastMessage:{...i,sender:a},updatedAt:r})}return s}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,i);return c&&(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const r=new Map;for(const a of e){const e=a.groupId.trim();e&&r.set(e,a)}if(0===r.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const n=r.get(e.conversationId);if(!n)return e;const o=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&o)return e;const i=n.name?.trim(),a=i||e.conversationName,c=n.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(n.remindType),u=void 0!==d&&d!==e.remindType;return a!==e.conversationName||c!==e.conversationAvatar||u?{...e,conversationName:a,conversationAvatar:c,remindType:u?d:e.remindType,updatedAt:s}:e}),o=this.sessionListCache.getAll(),i=!this.isSessionListEqual(o,n);return i&&(this.sessionListCache.setAll(n),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:i}}removeContact(e){return this.applyContactLocalPatch(()=>this.contactCache.remove(e))}updateContactRemark(e,t){return this.applyContactLocalPatch(()=>this.contactCache.updateRemark(e,t,Date.now()))}applyContactRosterNotice(e){const t=this.loadContactSnapshot("cache"),r=Date.now(),s="add"===e.action?this.contactCache.addByNotice(e.userId,r):this.contactCache.remove(e.userId),n="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,r);(s||n)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const o=this.loadContactSnapshot("cache");return{snapshot:o,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(o)}}updateConversationsFromServer(e,t){const r=Date.now(),s=this.conversationCache.getAll(),n=this.mergeConversationLists(s,e,r,t?.syncStartedAt),o=!this.isConversationListEqual(s,n);return this.conversationCache.setAll(n),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:n,changed:o}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const r=Date.now(),s=this.conversationCache.getAll(),n=s.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),o=n>=0?s[n]:void 0,i=this.buildConversationFromMessage(e,o,r);if(!i)return{items:s,changed:!1};const a=[i,...s.filter((e,t)=>t!==n)];return this.isConversationListEqual(s,a)?{items:s,changed:!1}:(this.conversationCache.setAll(a),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:this.conversationCache.getAll(),changed:!0})}applyIncomingMessageToSessionList(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.sessionListCache.exportItems(),changed:!1};const r=this.sessionListCache.getAll(),s=r.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),n=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!n)return{items:this.sessionListCache.exportItems(),changed:!1};const o=(e=>{const t=Of(e.nextRecord),r=e.existing.filter(e=>Of(e)!==t);return Nf([e.nextRecord,...r])})({existing:r,nextRecord:this.buildSessionListRecordFromConversation(n,e,s,Date.now())});return this.isSessionListEqual(r,o)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(o),this.scheduleFlush(["sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0})}async loadFromStorage(){const e=Date.now(),t=await this.readDump(this.conversationKey);this.conversationCache.load(t,e);const r=await this.readDump(this.userInfoKey);this.userInfoCache.load(r,e);const s=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(s,e);const n=await this.readValue(this.sessionListKey,null),o=n&&_l(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(o,e);const i=(n&&_l(n)&&_l(n.checkpoint)?n.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(i);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),d=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,d,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&_l(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&_l(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=new Map,e}restoreDirtyBatch(e){for(const[t,r]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(r,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const s=6;for(let n=0;n<=s;n+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!mu(t))return this.restoreDirtyBatch(e),void To("Cache flush failed",t);const s=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,s),"none"===s)return void To("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(s)}catch(r){if(!mu(r))return this.restoreDirtyBatch(e),void To("Cache quota cleanup persistence failed",r)}}To("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of Bf)e.has(t)&&await this.writeDomain(t)}async writeDomain(e){switch(e){case"conversation":return void(await this.store.writeAsync(this.conversationKey,{items:this.conversationCache.getAll()}));case"userInfo":return void(await this.store.writeAsync(this.userInfoKey,{items:this.userInfoCache.getAll()}));case"groupNamecard":return void(await this.store.writeAsync(this.groupNamecardKey,{items:this.groupNamecardCache.getAll()}));case"sessionList":return void(await this.writeSessionListStorageRecord());case"joinedGroupPreview":return void(await this.store.writeAsync(this.joinedGroupPreviewKey,this.joinedGroupPreviewCache.exportRecord()));case"contactRelation":return void(await this.store.writeAsync(this.contactRelationKey,{items:this.contactCache.getAll()}));case"contactVersion":return void(await this.store.writeAsync(this.contactVersionKey,this.contactCache.getVersionState()));case"contactMeta":await this.store.writeAsync(this.contactMetaKey,this.contactCache.getMeta())}}async writeSessionListStorageRecord(e=this.sessionListCache.getAll(),t=this.sessionListCheckpoint,r=!1){const s={items:e,checkpoint:t};r?await this.store.writeStrictAsync(this.sessionListKey,s):await this.store.writeAsync(this.sessionListKey,s),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),r=new Map;for(const n of t)r.set(`${n.conversationType}:${n.conversationId}`,n);const s=Date.now();return(e=>{const t=e.incoming.filter(e=>Uf(e)>0),r=new Map;for(const n of e.incoming)r.set(Of(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(Of(e))&&0===Uf(e)):e.existing.filter(e=>!r.has(Of(e)));return Nf([...s,...e.incoming])})({existing:t,incoming:this.filterItemsAgainstConversationDeletions(e).map(e=>{const t=`${e.conversationType}:${e.conversationId}`;return{...e,updatedAt:e.lastMessageAt??r.get(t)?.updatedAt??s}})})}buildSessionListSyncCandidate(e){const t=Date.now();if("incremental"===e.mode)return this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e.items),t);const r=this.filterItemsAgainstConversationDeletions(e.items).map(e=>({...e,updatedAt:e.lastMessageAt??t}));return this.hydrateSessionListRecordsFromLocalProfiles(Pf({snapshot:r,existing:this.sessionListCache.getAll(),syncStartedAt:e.syncStartedAt}),t)}filterItemsAgainstConversationDeletions(e){return e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.conversationType),r=this.conversationDeletionTimestamps.get(t);if(void 0===r)return!0;return Math.max(e.lastMessageAt??0,e.lastMessage?.timestamp??0)>r})}getConversationLatestUpdate(e,t,r,s){const n=e.find(e=>e.conversationId===r&&e.type===s),o=t.find(e=>e.conversationId===r&&e.conversationType===s);return Math.max(n?.lastUpdate??0,n?.lastMessage?.timestamp??0,o?.updatedAt??0,o?.lastMessageAt??0,o?.lastMessage?.timestamp??0)}handleQuotaExceeded(){const e=Date.now(),t=1e3*this.config.ttlSeconds;if(this.groupNamecardCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard";const r=this.groupNamecardCache.getAll().length;if(r>0){const e=this.calculateEvictCount(r,.2);if(this.groupNamecardCache.evictByLru(e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard"}if(this.userInfoCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"userInfo";const s=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),s}evictByPolicy(){const e=this.userInfoCache.getAll().length;if(e>0){const t=this.calculateEvictCount(e,.2);return t>0?(this.userInfoCache.evictByLru(t),"userInfo"):"none"}const t=this.conversationCache.getAll().length,r=this.calculateEvictCount(t,.05);return r>0?(this.conversationCache.evictByLru(r),"conversation"):"none"}calculateEvictCount(e,t){if(e<=0)return 0;const r=Math.floor(e*t);return Math.max(r,1)}mergeConversationLists(e,t,r,s){const n=new Map,o=new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);n.set(e,d.lastAccess),o.set(e,d)}const i=[],a=new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=n.get(e)??r;i.push({...d,marks:Array.isArray(d.marks)?d.marks:[],lastAccess:t,lastUpdate:r})}const c=e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.type);return!a.has(t)&&("number"==typeof s&&e.lastUpdate>s)});return[...i,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildConversationSignature(s)!==this.buildConversationSignature(n))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,r=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",s=e.isPinned?"1":"0",n="number"==typeof e.pinnedTime?e.pinnedTime:0,o=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${s}:${n}:${o}:${r}`}buildConversationKey(e,t){return`${t}:${e}`}areConversationMarksEqual(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}buildConversationFromMessage(e,t,r=Date.now()){const s=this.resolveConversationFromMessage(e);if(!s)return null;const n=e.msgServerId||e.msgLocalId,o=t?.lastMessage?.msgId!==n&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,i="SEND"===e.direct?r:t?.lastAccess??r;return{conversationId:s.conversationId,type:s.type,lastMessage:this.buildMessageSnippet(e),unreadCount:o,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:i,lastUpdate:r}}resolveConversationFromMessage(e){if(e.isChatThread||"cmd"===e.type)return null;if("string"!=typeof e.conversationId||!e.conversationId)return null;if("singleChat"===e.conversationType){const t="RECEIVE"===e.direct&&e.from.startsWith(`${this.userId}/`)&&e.sender.userId===this.userId,r="SEND"===e.direct||t?e.conversationId:"string"==typeof e.sender.userId?e.sender.userId:"";return r?{conversationId:r,type:"singleChat"}:null}return"groupChat"===e.conversationType?{conversationId:e.conversationId,type:"groupChat"}:"chatRoom"===e.conversationType?{conversationId:e.conversationId,type:"chatRoom"}:null}buildMessageSnippet(e){const t=(e=>{const t=ih(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{msgId:e.msgServerId||e.msgLocalId,type:e.type,body:this.normalizeMessageBody(e.body),timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}buildSessionListRecordFromConversation(e,t,r,s=Date.now()){const n=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),o=n.get(e.conversationId),i=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],s,!1)[0],c=i??(a?{userId:a.userId,nickname:a.nickname,avatarUrl:a.avatarUrl,sign:a.sign,ext:a.ext}:null),d=e.lastMessage,u=r?.conversationName,l=r?.conversationAvatar,h="string"==typeof t.sender.userId?t.sender.userId:"",p=this.resolveSessionDisplayUserInfo(h),m=this.buildSessionMessageSender(h,t.sender,n.get(h),p),f="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,g="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,o,c,u,l):"chatRoom"===e.type?this.buildChatRoomSessionDisplayFields(e.conversationId,u,l):this.buildGroupSessionDisplayFields(e.conversationId,u,l);return{conversationId:e.conversationId,conversationType:e.type,unreadCount:this.resolveSessionListUnreadCount(e,t,r),lastMessage:d?{msgServerId:d.msgId,from:h,to:f,sender:m,conversationId:e.conversationId,conversationType:e.type,type:t.type,sendStatus:t.sendStatus,timestamp:d.timestamp,direct:t.direct,body:d.body}:null,lastMessageAt:d?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:r?.readAt,remindType:r?.remindType??"DEFAULT",conversationName:g.conversationName,conversationAvatar:g.conversationAvatar,updatedAt:s}}resolveSessionListUnreadCount(e,t,r){const s=r?.unreadCount,n=t.msgServerId||t.msgLocalId;return r?.lastMessage?.msgServerId!==n&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof s?Math.max(e.unreadCount,s+1):e.unreadCount:"number"==typeof s?Math.max(e.unreadCount,s):e.unreadCount}shouldIncreaseUnreadForMessage(e){if("RECEIVE"!==e.direct||!1===e.isOnline)return!1;const t=this.resolveConversationFromMessage(e);return!t||!this.currentConversation||(this.currentConversation.conversationId!==t.conversationId||this.currentConversation.type!==t.type)}buildSingleSessionDisplayFields(e,t,r,s,n){const o=t?.remark?.trim(),i=t?.userInfo.avatarUrl??r?.avatarUrl??n;if(o)return{conversationName:o,conversationAvatar:i};const a=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return a?{conversationName:a,conversationAvatar:i}:s?{conversationName:s,conversationAvatar:i}:{conversationName:e,conversationAvatar:i}}shouldSkipSessionUserDisplayRefresh(e,t,r){if(!t.has(e))return!0;const s=t.get(e),n=r.get(e);return"number"==typeof s&&"number"==typeof n?.lastUpdate&&n.lastUpdate>s}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const r=this.loadContactSnapshot("cache").items,s=new Map(r.map(e=>[e.userId,e])),n=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const r=e.lastMessage;if(!r)return e;const o=r.sender.userId,i=s.get(o),a=this.resolveSessionDisplayUserInfo(o,n),c="singleChat"===e.conversationType&&o===e.conversationId?this.buildSingleChatPeerMessageSender(o,r.sender,i,a):this.buildSessionMessageSender(o,r.sender,i,a);return this.isSenderEqual(r.sender,c)?e:{...e,lastMessage:{...r,sender:c},updatedAt:t}})}resolveSessionDisplayUserInfo(e,t){const r=this.userInfoRuntimeStore.get(e,!1)?.profile;if(r)return r;const s=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return s?$f(s):null}buildSessionMessageSender(e,t,r,s){const n=r?.remark?.trim();return{userId:e,nickname:n||r?.userInfo.nickname?.trim()||s?.nickname?.trim()||t?.nickname?.trim()||void 0,avatarUrl:r?.userInfo.avatarUrl??s?.avatarUrl??t?.avatarUrl}}buildSingleChatPeerMessageSender(e,t,r,s){const n=this.buildSessionMessageSender(e,void 0,r,s);return{userId:e,nickname:t?.nickname?.trim()||n.nickname,avatarUrl:t?.avatarUrl||n.avatarUrl}}isSenderEqual(e,t){return e.userId===t.userId&&e.nickname===t.nickname&&e.avatarUrl===t.avatarUrl}buildGroupSessionDisplayFields(e,t,r){return t?{conversationName:t,conversationAvatar:r}:{conversationName:e}}mapJoinedGroupRemindTypeToSession(e){if("DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e)return e}buildChatRoomSessionDisplayFields(e,t,r){return t?{conversationName:t,conversationAvatar:r}:{conversationName:e}}isSessionListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildSessionListSignature(s)!==this.buildSessionListSignature(n))return!1}return!0}buildSessionListSignature(e){const t=e.lastMessage,r=t?`${t.msgServerId}:${t.from}:${t.to}:${t.conversationId}:${t.conversationType}:${t.type}:${t.sendStatus??""}:${t.direct??""}:${t.sender.userId}:${t.sender.nickname??""}:${t.sender.avatarUrl??""}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",s=`${e.conversationName}:${e.conversationAvatar??""}`;return[e.conversationType,e.conversationId,e.unreadCount,e.isPinned?"1":"0",e.pinnedTimestamp??0,e.marks.join(","),e.readAt??0,e.remindType,e.lastMessageAt??0,s,r].join(":")}refreshContactCacheIntegrity(e=!0){const t=this.contactCache.computeIntegrity(this.userInfoCache.getAll());this.contactCache.setMeta(t),e&&this.scheduleFlush(["contactMeta"])}buildContactSnapshotSignature(e){const t=e.items.map(e=>`${e.userId}:${e.userInfo.nickname??""}:${e.userInfo.avatarUrl??""}:${e.userInfo.sign??""}:${e.userInfo.ext??""}:${e.remark}:${e.addTs}`).join("|");return`${e.version}:${e.complete?"1":"0"}:${t}`}applyContactLocalPatch(e){const t=this.loadContactSnapshot("cache"),r=e();return r&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactMeta"])),{snapshot:this.loadContactSnapshot("cache"),changed:r&&this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(this.loadContactSnapshot("cache"))}}}class jf{constructor(){this.handlers=new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const r=[],s=[];for(const o of this.handlers.entries()){const[e]=o;e.startsWith("__internal")?r.push(o):s.push(o)}const n=this.dispatchToHandlers(e,t,r);n?n.then(()=>{this.dispatchToHandlers(e,t,s)}):this.dispatchToHandlers(e,t,s)}dispatchToHandlers(e,t,r){let s=null;for(const[,n]of r){const r=n[e];r&&(s=s?s.then(async()=>{await this.invokeHandler(e,t,r)}):this.invokeHandler(e,t,r))}return s}invokeHandler(e,t,r){try{const s=r(t);return this.isPromiseLike(s)?Promise.resolve(s).then(()=>{}).catch(t=>{_o(`Event handler error for ${e}`,t)}):null}catch(s){return _o(`Event handler error for ${e}`,s),null}}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const zf={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function Kf(e,t){const r=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),s=Math.min(r,t.maxDelay);if(t.jitter){const e=.2*s,t=(2*Math.random()-1)*e;return Math.max(0,s+t)}return s}function Hf(e){return new Promise(t=>setTimeout(t,e))}const Vf=e=>{const t={...e};return delete t.type,t},Wf=(e,t)=>{const r=e.lastMessage;if(!r)return null;const s=((e,t)=>{const r=t.getCurrentUserId?.()??"",s="singleChat"===e.type?e.conversationId:"";return{from:s,to:"singleChat"===e.type?r:e.conversationId,sender:{userId:s}}})(e,t);return{msgServerId:r.msgId,from:s.from,to:s.to,sender:s.sender,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof r.type&&r.type.length>0?r.type:"text",timestamp:r.timestamp,body:Vf(r.body),modifiedInfo:r.modifiedInfo,userInfoUpdateTime:r.userInfoUpdateTime,namecardUpdateTime:r.namecardUpdateTime}},Jf=async(e,t)=>{const r=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!r)return new Map;const s=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===s.length)return new Map;const n=[];for(let a=0;a<s.length;a+=50)n.push(s.slice(a,a+50));const o=new Map;let i=0;return await Promise.all(Array.from({length:Math.min(3,n.length)},async()=>await(async()=>{for(;i<n.length;){const e=i;i+=1;const t=n[e];if(t)try{const e=await r.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&o.set(t.groupId,t)}catch{}}})())),o},Zf=async(e,t)=>{const r=await Jf(e,t);return e.map(e=>((e,t,r)=>{const s=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),n=((e,t)=>{const r=e.getCacheManager();if(!r)return null;const s=r.getRuntimeUserInfo(t,!1);if(s)return s;const n=r.getUserInfoSummaries([t],!1)[0];return n?{userId:n.userId,nickname:n.nickname,avatarUrl:n.avatarUrl,sign:n.sign,ext:n.ext}:null})(t,e.conversationId),o="singleChat"===e.type?((e,t,r)=>{const s=t?.remark?.trim();if(s)return{conversationName:s,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl};const n=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return n?{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}})(e.conversationId,s,n):"groupChat"===e.type?(i=e.conversationId,a=r.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:i}):(e=>({conversationName:e}))(e.conversationId);var i,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:Wf(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:o.conversationName,conversationAvatar:o.conversationAvatar}})(e,t,r))};class Qf{constructor(e=`session-list-${Wp()}`){this.status="idle",this.seenBatchKeys=new Set,this.itemsByConversation=new Map,this.batchCount=0,this.requestId=e,this.startedAt=Date.now()}getRequestId(){return this.requestId}getStartedAt(){return this.startedAt}start(){"idle"===this.status&&(this.status="connecting")}markSyncing(){if("completed"===this.status||"failed"===this.status||"cancelled"===this.status)throw new Hr("Session-list sync session cannot re-enter syncing state after completion",Sr);this.status="syncing"}pushBatch(e){if(e.requestId!==this.requestId)throw new Hr("Session-list sync requestId mismatch",Sr,{details:{expected:this.requestId,received:e.requestId}});if(this.isTerminal())throw new Hr("Session-list sync batch received after terminal state",Sr,{details:{requestId:e.requestId,status:this.status}});const t=(r=e.requestId,s=e.batchSequence,`${r}:${s}`);var r,s;if(this.seenBatchKeys.has(t))return{accepted:!1,done:e.isLastBatch};this.markSyncing(),this.seenBatchKeys.add(t);for(const n of e.sessions)this.itemsByConversation.set(`${n.conversationType}:${n.conversationId}`,n);return this.batchCount+=1,e.isLastBatch&&(this.status="completed",this.finishedAt=Date.now()),{accepted:!0,done:e.isLastBatch}}fail(){this.status="failed",this.finishedAt=Date.now()}cancel(){this.status="cancelled",this.finishedAt=Date.now()}getItems(){return[...this.itemsByConversation.values()]}getBatchCount(){return this.batchCount}getStatus(){return this.status}buildSnapshot(){return{requestId:this.requestId,status:this.status,pageCount:this.batchCount,startedAt:this.startedAt,finishedAt:this.finishedAt,seenBatchKeys:[...this.seenBatchKeys]}}isTerminal(){return"completed"===this.status||"failed"===this.status||"cancelled"===this.status}}const Yf=0,Xf=5,eg=10,tg=11,rg=1,sg=2,ng=1,og=2,ig=3,ag=e=>e===rg?"groupChat":e===sg?"chatRoom":"singleChat",cg=()=>nl().lookupType("easemob.pb.MessageBody"),dg=e=>{const t=cg().toObject(cg().decode(e),{longs:Number,bytes:Uint8Array}),r=Array.isArray(t.contents)?t.contents:[],s=(n=r[0])&&"object"==typeof n&&!Array.isArray(n)?n:{};var n;const o="number"==typeof s.type?s.type:0;return 0===o?{type:"text",content:"string"==typeof s.text?s.text:""}:1===o?{type:"image",filename:"string"==typeof s.displayName?s.displayName:"image",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:2===o?{type:"video",filename:"string"==typeof s.displayName?s.displayName:"video",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:3===o?{type:"location",latitude:"number"==typeof s.latitude?s.latitude:0,longitude:"number"==typeof s.longitude?s.longitude:0,address:"string"==typeof s.address?s.address:void 0}:4===o?{type:"voice",filename:"string"==typeof s.displayName?s.displayName:"voice",remotePath:"string"==typeof s.remotePath?s.remotePath:"",duration:"number"==typeof s.duration?s.duration:0}:5===o?{type:"file",filename:"string"==typeof s.displayName?s.displayName:"file",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:6===o?{type:"cmd",action:"string"==typeof s.action?s.action:""}:7===o?{type:"custom",event:"string"==typeof s.customEvent?s.customEvent:""}:8===o?{type:"combine",title:"string"==typeof s.title?s.title:"",summary:"string"==typeof s.summary?s.summary:""}:{}},ug=e=>{const t=e.session_id??"",r=(e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{return null}return null})(e.metadata),s="string"==typeof r?.nickname?r.nickname:void 0,n="string"==typeof r?.remark?r.remark:void 0,o="string"==typeof r?.avatarurl?r.avatarurl:"string"==typeof r?.avatarUrl?r.avatarUrl:void 0;return n?{conversationName:n,conversationAvatar:o}:s?{conversationName:s,conversationAvatar:o}:{conversationName:t,conversationAvatar:o}},lg=e=>{const t={...e};return delete t.type,t},hg=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,pg=(e,t,r)=>{if(!e)return null;const s=(e=>{if(!e)return"";const t=e.lastIndexOf("_");return t>=0?e.slice(t+1):e})(e.from?.name),n={userId:s};return"singleChat"===r.conversationType&&s===r.conversationId&&r.singleChatPeerDisplay&&(r.singleChatPeerDisplay.conversationName!==s&&(n.nickname=r.singleChatPeerDisplay.conversationName),r.singleChatPeerDisplay.conversationAvatar&&(n.avatarUrl=r.singleChatPeerDisplay.conversationAvatar)),{msgServerId:e.id??"",from:s,to:hg({conversationId:r.conversationId,conversationType:r.conversationType,from:s,currentUserId:r.currentUserId}),sender:n,conversationId:r.conversationId,conversationType:r.conversationType,type:(o=t.type,"text"===o||"image"===o||"file"===o||"voice"===o||"video"===o||"location"===o||"custom"===o||"cmd"===o||"combine"===o?o:"text"),timestamp:e.timestamp??0,body:lg(t)};var o},mg=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const o=s;t.has(o)||(t.add(o),r.push(o))}return r},fg=(e,t)=>e.sessions.map(e=>{const r=(e=>{if(!e||0===e.byteLength)return{};try{return dg(e)}catch{return{}}})(e.last_message?.payload),s=e.session_id??"",n=ag(e.session_type),o=(e=>{const t=e.session_id??"",r=ag(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:ug(e)})(e);return{conversationId:s,conversationType:n,unreadCount:e.unread_count??0,lastMessage:pg(e.last_message,r,{conversationId:s,conversationType:n,currentUserId:t,singleChatPeerDisplay:"singleChat"===n?o:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:mg(e.marks),readAt:e.read_receipt,remindType:(i=e.remind_type,i===ng?"ALL":i===og?"AT":i===ig?"NONE":"DEFAULT"),conversationName:o.conversationName,conversationAvatar:o.conversationAvatar};var i}),gg={nested:{easemob:{nested:{sessionlist:{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}}},JID:{fields:{app_key:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},client_resource:{type:"string",id:4}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},timestamp:{type:"uint64",id:4},payload:{type:"bytes",id:6}}},SessionItem:{fields:{session_id:{type:"string",id:1},session_type:{type:"int32",id:2},last_message:{type:"Meta",id:3},updated_at:{type:"int64",id:6},pinned_time:{type:"int64",id:7},unread_count:{type:"uint32",id:8},marks:{rule:"repeated",type:"string",id:9},read_receipt:{type:"int64",id:10},remind_type:{type:"int32",id:11},group_name:{type:"string",id:12},group_avatar:{type:"string",id:13},metadata:{type:"string",id:14}}},GetSessionListRequest:{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},need_empty_session:{type:"bool",id:7},need_session_mark:{type:"bool",id:8}}},GetSessionListResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},sessions:{rule:"repeated",type:"SessionItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let yg=null,vg=!1;const bg=()=>yg||(vg||(Dc.util.Long=mi,Dc.configure(),vg=!0),pd(),yg=Dc.Root.fromJSON(gg),hd(yg),yg),Ig=e=>bg().lookupType(e),wg=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("bigint"==typeof e)return Number(e);if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},Cg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:wg(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:wg(t.protocol_version)??wg(t.protocolVersion)??0}},Sg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{appKey:"string"==typeof t.app_key?t.app_key:"string"==typeof t.appKey?t.appKey:void 0,name:"string"==typeof t.name?t.name:void 0,domain:"string"==typeof t.domain?t.domain:void 0,clientResource:"string"==typeof t.client_resource?t.client_resource:"string"==typeof t.clientResource?t.clientResource:void 0}},Tg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==wg(t.id)?String(wg(t.id)):void 0,from:Sg(t.from),timestamp:wg(t.timestamp),payload:t.payload instanceof Uint8Array?t.payload:Array.isArray(t.payload)?Uint8Array.from(t.payload.filter(e=>"number"==typeof e)):void 0}};class _g{constructor(){this.requestType=Ig("easemob.sessionlist.GetSessionListRequest"),this.responseType=Ig("easemob.sessionlist.GetSessionListResponse"),this.errorType=Ig("easemob.sessionlist.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,need_empty_session:e.includeEmpty??!1,need_session_mark:e.includeMark??!0});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 s=this.tryDecodeRequest(e);return s||{type:Yf}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=wg(t.type);return r!==eg?null:{type:r,header:Cg(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:wg(t.last_sync_time)??0,includeEmpty:!0===t.need_empty_session,includeMark:!0===t.need_session_mark}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=wg(t.type);return r!==tg?null:{type:r,header:Cg(t.header),sessions:Array.isArray(t.sessions)?t.sessions.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{session_id:"string"==typeof t.session_id?t.session_id:void 0,session_type:wg(t.session_type),last_message:Tg(t.last_message),updated_at:wg(t.updated_at),pinned_time:wg(t.pinned_time),unread_count:wg(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:wg(t.read_receipt),remind_type:wg(t.remind_type),group_name:"string"==typeof t.group_name?t.group_name:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:void 0,metadata:"string"==typeof t.metadata?t.metadata:void 0}})(e)):[],isLastBatch:!0===t.is_last_batch,lastSyncFinishedTs:wg(t.last_sync_finished_ts)}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=wg(t.type);return r!==Xf?null:{type:r,header:Cg(t.header),code:wg(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Rg=async e=>{const t=e.client.getCacheManager(),r=e.client.getRestContext(),s=e.client.getSessionListSyncWsUrls();if(!t||0===s.length)throw new Wr("session-list sync websocket is unavailable",{code:gt,details:{protocol:"session-list",stage:"socket_connect"}});const[n,o]=r.appKey.split("#");if(!n||!o)throw new Zr("session-list appKey is invalid",{code:ot,details:{appKey:r.appKey}});const i=t.loadSessionListCheckpoint(),a=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:e.session.getRequestId(),resource:r.clientResource,org:n,app:o,username:r.userId,lastSyncTime:(c=i.sessionsLastSyncTs,Math.max(0,c-2e4)),params:e.params});var c;const d=new _g;let u=0,l=i.sessionsLastSyncTs;return await e.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:e.session.getRequestId(),encode:()=>d.encodeRequest(a),decode:e=>{const t=d.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:t=>{if(5===t.type&&"code"in t&&"message"in t)throw 1002===(s=t).code?new Jr(s.message,{code:lt,details:{protocol:"session-list",responseCode:s.code}}):1003===s.code?new Hr(s.message,kt,{details:{protocol:"session-list",responseCode:s.code}}):1501===s.code||1001===s.code?new Zr(s.message,{code:ot,details:{protocol:"session-list",responseCode:s.code}}):1503===s.code?new Hr(s.message,Ut,{details:{protocol:"session-list",responseCode:s.code}}):(s.code,new Hr(s.message,fr,{details:{protocol:"session-list",responseCode:s.code}}));var s;if(11!==t.type)throw new Hr("session-list response type is invalid",Mt,{details:{responseType:t.type}});const n=t,o=n.header?.requestId;if(o&&o!==e.session.getRequestId())return;u+=1,So("Decoded session-list sync raw response",{requestId:e.session.getRequestId(),batchSequence:u,response:n});const i=fg(n,r.userId),a=e.session.pushBatch({requestId:e.session.getRequestId(),batchSequence:u,sessions:i,isLastBatch:!0===n.isLastBatch,lastSyncFinishedTs:n.lastSyncFinishedTs});if("number"==typeof n.lastSyncFinishedTs&&(l=n.lastSyncFinishedTs),!a.done)return;return{done:!0,result:{items:e.session.getItems(),lastSyncFinishedTs:l}}}})},Ag=e=>new Zr(`${e} must be a local paging cursor returned by SDK`,{code:ot,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),Mg=(e,t,r)=>{const s=e+t;return s<r?String(s):""},Eg=e=>({...e}),Ug=e=>{const t=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),r=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:r,lastUpdate:r}},kg=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,Ng=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new Zr("pageSize must be a positive integer",{code:ot,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const t=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw Ag(t);const r=Number.parseInt(e,10);if(!Number.isSafeInteger(r)||r<0)throw Ag(t);return r})(e.cursor,"cursor"),r=[];for(const s of e.items){if("chatRoom"===s.conversationType)continue;const e=kg(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:Mg(t,e.pageSize,r.length)}},Og=()=>Date.now(),xg={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Lg=(e,t)=>({status:e,determinedAt:Og(),reason:t}),Pg=e=>e instanceof Hr&&(e.code===kt||1103===e.code),Dg=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Pg(e)});class $g{constructor(e){this.running=null,this.currentSession=null,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}refresh(e){return this.running||(this.currentSession=new Qf,this.currentSession.start(),this.running=this.runRefresh(this.currentSession,{includeEmpty:e.includeEmpty,includeMark:!0}),this.running.finally(()=>{this.running=null,this.currentSession=null})),this.running}async runRefresh(e,t){const r=this.client.getCacheManager();if(!r)return[];this.client.emitSyncDataStart("conversation");const s=await this.tryDirectFallback(r);if(s)return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),s;try{const s=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let o=0;const i=await async function(e,t,r={}){const s={...zf,...r};let n;for(let i=1;i<=s.maxAttempts;i++)try{return await e()}catch(o){if(n=o,!t(o))throw o;if(i>=s.maxAttempts)throw o;const e=Kf(i,s);await Hf(e)}throw n}(async()=>{o+=1;const r=1===o?e:this.createRetrySession();r.start();try{return await Rg({client:this.client,session:r,params:t})}catch(s){throw r.fail(),s}},Pg,xg),a={result:i,syncStartedAt:e.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:Og()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:Og()};try{await r.commitSessionListSync({items:c,mode:s,checkpoint:d,syncStartedAt:a.syncStartedAt})}catch(n){e.fail();const t=new Xr("Session-list final persistence failed",{details:{cause:n instanceof Error?n.message:String(n)}});return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Dg(t)}),r.loadSessionList()}const u=r.loadSessionList();return r.updateConversationsFromServer(u.map(Ug),{syncStartedAt:a.syncStartedAt}),await r.flushPending(),this.client.emitConversationListUpdate("conversation","full"===s),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),u}catch(n){const t=n instanceof Hr?n:new Hr(n instanceof Error?n.message:String(n));e.fail();const s=(e=>e.code===Ut||e.code===dt?{capabilityState:Lg("unsupported",e.message),shouldUseFallback:!0}:e.code===lt||e.code===ht?{shouldUseFallback:!0}:e.code===kt||1103===e.code?{shouldUseFallback:!0,shouldRetry:!0}:e.code===Sr?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(t);s.capabilityState&&(this.capabilityState=s.capabilityState),s.shouldResetCheckpoint&&r.resetSessionListCheckpoint();const o=await this.buildFallbackSessionList(r);return s.shouldUseFallback&&r.replaceSessionList(o),this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Dg(t)}),o}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}var t;const r=Boolean(this.client.getServerUrlsConfig()?.syncWsUrl),s=this.client.isSessionListDnsProbeAvailable();if(!r&&!s){this.capabilityState=Lg("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new Qf}async buildFallbackSessionList(e){return await(async(e,t)=>await Zf(e,t))(e.loadConversationSummaries(),this.client)}}const qg=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Gg=async e=>{if("string"==typeof e||qg(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):qg(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength))(e);if((e=>"undefined"!=typeof Blob&&e instanceof Blob&&"function"==typeof e.arrayBuffer||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e))return new Uint8Array(await e.arrayBuffer());throw new Hr("sync websocket frame payload type is invalid",Tr,{details:{stage:"response_decode",payloadType:typeof e}})},Bg=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},Fg=async e=>{await new Promise(t=>{setTimeout(t,e)})},jg=e=>e instanceof Error?e:new Error(String(e));class zg{constructor(e){this.pending=new Map,this.socket=null,this.state="idle",this.connectPromise=null,this.activeUrl="",this.urlIndex=0,this.attempt=0,this.connectTimer=null,this.idleTimer=null,this.retryTimer=null,this.completeCloseTimer=null,this.cancelled=!1,this.getUrls=e.getUrls,this.socketAdapter=e.socketAdapter}async request(e){if(this.cancelled)throw new Hr("sync websocket session is cancelled",_r,{details:{stage:"cancelled",requestId:e.requestId}});if(this.pending.has(e.requestId))throw new Hr("sync websocket requestId is duplicated",ot,{details:{stage:"request_send",requestId:e.requestId}});this.clearCompleteCloseTimer();const t=new Promise((t,r)=>{this.pending.set(e.requestId,{...e,resolve:t,reject:r})});t.catch(()=>{});try{await this.ensureConnected(),this.sendPendingRequest(this.pending.get(e.requestId))}catch(r){this.rejectPending(e.requestId,jg(r))}return await t}cancel(e="sync-websocket-cancelled"){this.cancelled=!0;const t=new Hr("sync websocket cancelled",_r,{details:{stage:"cancelled",reason:e}});this.rejectAll(t),this.closeSocket(4001,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}close(e="sync-websocket-closed"){this.closeSocket(1e3,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}async ensureConnected(){if("open"!==this.state||this.socket?.readyState!==zo){if(this.connectPromise)return await this.connectPromise;this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let e=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&To("sync websocket retry started",this.buildLogContext({reason:e?.message}));try{return void(await this.openSocket())}catch(t){if(e=jg(t),this.cancelled||0===this.pending.size)throw e;if(this.attempt>=3)throw To("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),e;const r=Bg(this.attempt);To("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await Fg(r)}}throw new Wr("sync websocket retry exhausted",{code:Cr,details:{stage:"socket_connect",reason:e?.message??"unknown"}})}async openSocket(){const e=await this.getUrls();if(0===e.length)throw new Wr("sync websocket urls are unavailable",{code:Cr,details:{stage:"socket_connect"}});const t=e[this.urlIndex%e.length];if(this.urlIndex+=1,!t)throw new Wr("sync websocket url is invalid",{code:Cr,details:{stage:"socket_connect"}});this.activeUrl=t,this.state="connecting",To("sync websocket connect started",this.buildLogContext());const r=Wo(),s=this.socketAdapter??Ld({webSocketCtor:r.WebSocket});if(!s)throw this.state="idle",this.buildConnectionError("sync websocket adapter is unavailable","socket_connect");let n=null;try{const e=await Promise.race([s.connect({url:t}),new Promise((e,t)=>{n=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},5e3)})]);n&&clearTimeout(n),this.socket=e,e.onMessage(t=>{this.socket===e&&this.handleMessage(t)}),e.onError(()=>{this.socket===e&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),e.onClose(t=>{if(this.socket===e)return"closing"===this.state||0===this.pending.size?(this.clearTimers(),this.socket=null,void(this.state="idle")):void this.handleSocketFailure(this.buildConnectionError("sync websocket socket closed","sync_page",{closeCode:t.code,closeReason:t.reason}))}),this.state="open",this.resetIdleTimer(),To("sync websocket connected",this.buildLogContext())}catch(o){if(n&&clearTimeout(n),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),o instanceof Wr)throw o;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:o instanceof Error?o.message:String(o)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await Gg(e);if(!(await this.routeFrame(t)))return}catch(t){const e=jg(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(e){const t=[];let r=null;for(const n of this.pending.values())try{const t=n.decode(e);if(t.requestId&&t.requestId===n.requestId){try{const e=await n.onFrame(t.frame,this.socket);e?.done&&(this.pending.delete(n.requestId),n.resolve(e.result),this.closeIfComplete())}catch(s){this.pending.delete(n.requestId),n.reject(jg(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(jg(s))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&t.length===this.pending.size)throw new Hr("sync websocket frame decode failed",Tr,{details:{stage:"response_decode",cause:t[0]?.message}});return To("sync websocket frame ignored",this.buildLogContext({reason:t[0]?.message??"requestId not matched"})),!1}handleSocketFailure(e){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(To("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),void this.rejectAll(e)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(jg(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(e){if(e&&this.socket&&this.socket.readyState===zo)try{this.socket.send(e.encode()).catch(t=>{this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}),To("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(t){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}}rejectPending(e,t){const r=this.pending.get(e);r&&(this.pending.delete(e),r.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(To("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},0))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},1e4))}clearTimers(){this.clearConnectTimer(),this.clearIdleTimer(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.clearCompleteCloseTimer()}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearCompleteCloseTimer(){this.completeCloseTimer&&(clearTimeout(this.completeCloseTimer),this.completeCloseTimer=null)}closeSocket(e,t){const r=this.socket;this.socket=null,!r||r.readyState>=Ko||(this.state="closing",r.close(e,t))}buildConnectionError(e,t,r={}){return new Wr(e,{code:Cr,details:{stage:t,url:this.activeUrl,...r}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:zr(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const Kg=(e,t)=>{if(!e.matchField)return!1;const r=t[e.matchField];return void 0!==e.matchPattern?"string"==typeof r&&r.includes(e.matchPattern):void 0===e.matchValue?void 0!==r:r===e.matchValue||!("string"!=typeof r&&"number"!=typeof r||"string"!=typeof e.matchValue&&"number"!=typeof e.matchValue)&&String(r)===String(e.matchValue)};function Hg(e){const t=e.entry?.code??fr,r=e.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:e.apiName,entry:e.entry,mapped:e.mapped,reasonKey:e.reasonKey});return new ts(r,{code:t,details:{api:e.apiName,serverCode:e.serverCode,serverMessage:e.serverMessage,httpStatus:e.httpStatus,mapped:e.mapped??Boolean(e.entry),reasonKey:e.reasonKey,matchedBy:e.matchedBy,retryable:e.entry?.retryable,canonicalCode:e.entry?.canonicalCode??e.entry?.code}})}const Vg={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"}},Wg=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),Jg=e=>{if(Array.isArray(e))return e.length;if(!e||"object"!=typeof e)return;const t=e;for(const r of["entities","data","items","messages","conversations","results"]){const e=t[r];if(Array.isArray(e))return e.length}};class Zg{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=t?.requestAdapter,this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),r=t.searchParams;for(const e of r.keys())r.set(e,"***");const s=r.toString(),n=s?`?${s}`:"";return`${t.origin}${t.pathname}${n}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(e,t,r,s){const n={...t.operation?{api:t.operation}:{},url:t.url,method:t.method,httpStatus:e,serverCode:r,serverMessage:s,mapped:!1};if(400===e)return new Zr("Invalid request parameters",{code:it,details:{...n,canonicalCode:it}});if(401===e){const e=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),t=e?lt:dt;return new Jr(e?"Authentication token expired":"Authentication failed",{code:t,details:{...n,reasonKey:e?"token_expired":"unauthorized",canonicalCode:t}})}return 403===e?new Jr("Access forbidden",{code:ut,details:{...n,canonicalCode:ut}}):429===e?new ts("REST rate limit exceeded",{code:Br,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:Br}}):e>=500?new ts("REST business error: request failed",{code:fr,details:{...n,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:fr}}):void 0}async request(e,t={}){const r=`${this.baseUrl}${e}`,s=t.method??"GET",n=Date.now(),o=this.sanitizeUrl(r);So("REST request",{method:s,url:o,operation:t.operation});const i=t.operation?(e=>{const t=Vg[e];if(t)return t;const r=(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_${Wg(e)}`,operationType:r}})(t.operation):void 0,a=i?jp(i):void 0,c=a?.startRequest({requestName:i?.operationName,method:s,url:r});let d=0;const u={...this.defaultHeaders,...t.headers};this.includeRequestId&&(u[ml]=pl());const l={method:s,headers:u};if(t.body&&"GET"!==s){const e=Object.keys(u).some(e=>"content-type"===e.toLowerCase());"string"==typeof t.body?(e||(u["Content-Type"]="application/x-www-form-urlencoded"),l.body=t.body):(e||(u["Content-Type"]="application/json"),l.body=JSON.stringify(t.body))}else if("GET"===s)for(const p of Object.keys(u))"content-type"===p.toLowerCase()&&delete u[p];try{if(this.requestAdapter){const e=await this.requestAdapter.request({url:r,method:s,headers:u,body:t.body,timeoutMs:t.timeout??this.timeout});d=e.status;const i=((e,t)=>{if("string"!=typeof e)return e;const r=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),s=e.trim();if(!(r?.[1].includes("application/json")||s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]")))return e;try{return JSON.parse(s)}catch{return e}})(e.data,e.headers),l=Date.now()-n;(e.status<200||e.status>=300)&&(To("REST response error",{method:s,url:o,status:e.status,duration:l}),this.handleErrorPayload(e.status,"",i,{operation:t.operation,url:r,method:s})),So("REST response",{method:s,url:o,status:e.status,duration:l});const h=Jg(i);return c?.finish({code:e.status,success:!0,resultCount:h}),a?.finish({code:0,success:!0,resultCount:h}),i}const e=new AbortController,i=setTimeout(()=>e.abort(),t.timeout??this.timeout),h=await fetch(r,{...l,signal:e.signal});d=h.status,clearTimeout(i);const p=Date.now()-n;h.ok||(To("REST response error",{method:s,url:o,status:h.status,duration:p}),await this.handleErrorResponse(h,{operation:t.operation,url:r,method:s})),So("REST response",{method:s,url:o,status:h.status,duration:p});const m=h.headers.get("content-type");if(m?.includes("application/json")){const e=await h.json(),t=Jg(e);return c?.finish({code:h.status,success:!0,resultCount:t}),a?.finish({code:0,success:!0,resultCount:t}),e}const f=await h.text();return c?.finish({code:h.status,success:!0}),a?.finish({code:0,success:!0}),f}catch(h){const e=0!==d?d:h instanceof Hr?h.code:-1,n=h instanceof Error?h.message:String(h);if(c?.finish({code:e,success:!1,description:n}),a?.finish({code:e,success:!1,description:n}),h instanceof Hr)throw h;if(h instanceof Error&&"AbortError"===h.name)throw To("REST request timeout",{method:s,url:o,timeout:t.timeout??this.timeout}),new es(`Request timeout: ${r}`,{code:pr,details:{url:r,method:s,timeout:t.timeout??this.timeout}});throw To("REST request failed",{method:s,url:o}),new es(`Request failed: ${r}`,{code:hr,details:{url:r,method:s}})}}async handleErrorResponse(e,t){let r;try{r=await e.json()}catch{r=await e.text()}this.handleErrorPayload(e.status,e.statusText,r,t)}handleErrorPayload(e,t,r,s){const n=r&&"object"==typeof r?r:{},o=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const r=e.error,s=r.code;if("number"!=typeof s&&"string"!=typeof s)return;const n=String(s);return/^\d{7}$/.test(n)&&Number(n.slice(0,3))===t?r:void 0})(n,e),i=o?{...n,code:o.code,message:o.message}:r,a=function(e,t,r){if(!e)return;const s=r&&"object"==typeof r?r:{},n="string"==typeof s.error?s.error:void 0,o=(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)(s),i="string"==typeof s.error_description?s.error_description:"string"==typeof s.message?s.message:void 0,a=(e,t=!1)=>{const r=(e,r,s)=>({reasonKey:e,entry:r,matchedBy:t?"common":s});if(n&&e[n])return r(n,e[n],"key");for(const[n,o]of Object.entries(e))if(Kg(o,s))return r(n,o,"field");if(void 0!==o)for(const[s,n]of Object.entries(e)){if(n.code===o||n.canonicalCode===o)return r(s,n,"code");if(Array.isArray(n.aliases)&&n.aliases.includes(String(o)))return r(s,n,"alias")}if(i)for(const[s,n]of Object.entries(e))if(Array.isArray(n.aliases)&&n.aliases.includes(i))return r(s,n,"alias")},c=t?e.apis[t]:void 0,d=c?a(c.errors):void 0;if(d)return d;for(const u of Object.values(e.common)){const e=a(u.errors,!0);if(e)return e}}(this.errorMap,s.operation,i),c="string"==typeof n.error?n.error:void 0,d="number"==typeof n.error_code||"string"==typeof n.error_code?n.error_code:"number"==typeof n.errorCode||"string"==typeof n.errorCode?n.errorCode:"number"==typeof n.code||"string"==typeof n.code?n.code:"string"==typeof n.error?n.error:"number"==typeof o?.code||"string"==typeof o?.code?o.code:void 0,u="string"==typeof n.message?n.message:"string"==typeof n.error_description?n.error_description:"string"==typeof o?.message?o.message:void 0,l=!!(401!==e&&403!==e||void 0!==c&&"unauthorized"!==c&&"auth_failed"!==c&&"forbidden"!==c)&&(void 0!==c||"string"==typeof n.error_description||"string"==typeof n.message);if(s.operation&&a)throw Hg({apiName:s.operation,entry:a.entry,serverCode:d,serverMessage:u,httpStatus:e,mapped:!0,reasonKey:a.reasonKey,matchedBy:a.matchedBy});const h=this.buildHttpStatusFallbackError(e,s,d,u);if(h)throw h;if(s.operation&&l)throw Hg({apiName:s.operation,serverCode:d,serverMessage:u,httpStatus:e,mapped:!1,reasonKey:c});throw new es(`HTTP ${e}: ${t}`,{code:mr,details:{url:s.url,method:s.method,httpStatus:e}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}}const Qg=async(e,t,r)=>{const{orgName:s,appName:n}=Qn(e.appKey),o=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,i=new Zg(e.restBaseUrl,{requestAdapter:r,includeRequestId:!0});i.setAuthToken(e.token);try{return((e,t)=>{const r=Date.now(),s=e=>{const s="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:s,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??s!==t,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:r}};if(_l(e))return _l(e.data)?s(e.data):s(e);throw new Zr("Invalid contact metadata response",{code:ot,details:{payload:e}})})(await i.get(o),t)}catch(a){if(a instanceof Zr)throw a;const e=a instanceof Hr&&a.details?a.details:{};throw new es("Contact metadata request failed",{code:wr,details:{stage:"metadata",cause:a instanceof Error?a.message:String(a),httpStatus:"number"==typeof e.httpStatus?e.httpStatus:void 0,sourceCode:a instanceof Hr?a.code:void 0}})}};var Yg,Xg,ey;(Xg=Yg||(Yg={})).assertEqual=e=>{},Xg.assertIs=function(e){},Xg.assertNever=function(e){throw new Error},Xg.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},Xg.getValidEnumValues=e=>{const t=Xg.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return Xg.objectValues(r)},Xg.objectValues=e=>Xg.objectKeys(e).map(function(t){return e[t]}),Xg.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},Xg.find=(e,t)=>{for(const r of e)if(t(r))return r},Xg.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Xg.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},Xg.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(ey||(ey={})).mergeShapes=(e,t)=>({...e,...t});const ty=Yg.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ry=e=>{switch(typeof e){case"undefined":return ty.undefined;case"string":return ty.string;case"number":return Number.isNaN(e)?ty.nan:ty.number;case"boolean":return ty.boolean;case"function":return ty.function;case"bigint":return ty.bigint;case"symbol":return ty.symbol;case"object":return Array.isArray(e)?ty.array:null===e?ty.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?ty.promise:"undefined"!=typeof Map&&e instanceof Map?ty.map:"undefined"!=typeof Set&&e instanceof Set?ty.set:"undefined"!=typeof Date&&e instanceof Date?ty.date:ty.object;default:return ty.unknown}},sy=Yg.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ny extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof ny))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Yg.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}ny.create=e=>new ny(e);const oy=(e,t)=>{let r;switch(e.code){case sy.invalid_type:r=e.received===ty.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case sy.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Yg.jsonStringifyReplacer)}`;break;case sy.unrecognized_keys:r=`Unrecognized key(s) in object: ${Yg.joinValues(e.keys,", ")}`;break;case sy.invalid_union:r="Invalid input";break;case sy.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Yg.joinValues(e.options)}`;break;case sy.invalid_enum_value:r=`Invalid enum value. Expected ${Yg.joinValues(e.options)}, received '${e.received}'`;break;case sy.invalid_arguments:r="Invalid function arguments";break;case sy.invalid_return_type:r="Invalid function return type";break;case sy.invalid_date:r="Invalid date";break;case sy.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Yg.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case sy.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case sy.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case sy.custom:r="Invalid input";break;case sy.invalid_intersection_types:r="Intersection results could not be merged";break;case sy.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case sy.not_finite:r="Number must be finite";break;default:r=t.defaultError,Yg.assertNever(e)}return{message:r}};let iy=oy;function ay(e,t){const r=iy,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,o=[...r,...n.path||[]],i={...n,path:o};if(void 0!==n.message)return{...n,path:o,message:n.message};let a="";const c=s.filter(e=>!!e).slice().reverse();for(const d of c)a=d(i,{data:t,defaultError:a}).message;return{...n,path:o,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===oy?void 0:oy].filter(e=>!!e)});e.common.issues.push(s)}class cy{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return dy;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const e=await s.key,t=await s.value;r.push({key:e,value:t})}return cy.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return dy;if("aborted"===n.status)return dy;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const dy=Object.freeze({status:"aborted"}),uy=e=>({status:"dirty",value:e}),ly=e=>({status:"valid",value:e}),hy=e=>"aborted"===e.status,py=e=>"dirty"===e.status,fy=e=>"valid"===e.status,gy=e=>"undefined"!=typeof Promise&&e instanceof Promise;var yy,vy;(vy=yy||(yy={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},vy.toString=e=>"string"==typeof e?e:e?.message;class by{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Iy=(e,t)=>{if(fy(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ny(e.common.issues);return this._error=t,this._error}}};function wy(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??n.defaultError}:void 0===n.data?{message:o??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:o??r??n.defaultError}},description:n}}class Cy{get description(){return this._def.description}_getType(e){return ry(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ry(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new cy,ctx:{common:e.parent.common,data:e.data,parsedType:ry(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(gy(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ry(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Iy(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ry(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return fy(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>fy(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ry(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(gy(s)?s:Promise.resolve(s));return Iy(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),o=()=>s.addIssue({code:sy.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(o(),!1)):!!n||(o(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new wv({schema:this,typeName:Nv.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Cv.create(this,this._def)}nullable(){return Sv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ov.create(this)}promise(){return Iv.create(this,this._def)}or(e){return cv.create([this,e],this._def)}and(e){return uv.create(this,e,this._def)}transform(e){return new wv({...wy(this._def),schema:this,typeName:Nv.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Tv({...wy(this._def),innerType:this,defaultValue:t,typeName:Nv.ZodDefault})}brand(){return new Av({typeName:Nv.ZodBranded,type:this,...wy(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new _v({...wy(this._def),innerType:this,catchValue:t,typeName:Nv.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Mv.create(this,e)}readonly(){return Ev.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Sy=/^c[^\s-]{8,}$/i,Ty=/^[0-9a-z]+$/,_y=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ry=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ay=/^[a-z0-9_-]{21}$/i,My=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ey=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Uy=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let ky;const Ny=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Oy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,xy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ly=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Py=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Dy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$y="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",qy=new RegExp(`^${$y}$`);function Gy(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function By(e){return new RegExp(`^${Gy(e)}$`)}function Fy(e){let t=`${$y}T${Gy(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function jy(e,t){return!("v4"!==t&&t||!Ny.test(e))||!("v6"!==t&&t||!xy.test(e))}function zy(e,t){if(!My.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function Ky(e,t){return!("v4"!==t&&t||!Oy.test(e))||!("v6"!==t&&t||!Ly.test(e))}class Hy extends Cy{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==ty.string){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.string,received:t.parsedType}),dy}const t=new cy;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,o=e.data.length<s.value;(n||o)&&(r=this._getOrReturnCtx(e,r),n?ay(r,{code:sy.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&ay(r,{code:sy.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)Uy.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"email",code:sy.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)ky||(ky=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ky.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"emoji",code:sy.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)Ry.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"uuid",code:sy.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)Ay.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"nanoid",code:sy.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)Sy.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"cuid",code:sy.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)Ty.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"cuid2",code:sy.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)_y.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"ulid",code:sy.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),ay(r,{validation:"url",code:sy.invalid_string,message:s.message}),t.dirty()}else if("regex"===s.kind){s.regex.lastIndex=0;s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"regex",code:sy.invalid_string,message:s.message}),t.dirty())}else if("trim"===s.kind)e.data=e.data.trim();else if("includes"===s.kind)e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty());else if("toLowerCase"===s.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===s.kind)e.data=e.data.toUpperCase();else if("startsWith"===s.kind)e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty());else if("endsWith"===s.kind)e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){Fy(s).test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){qy.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){By(s).test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?Ey.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"duration",code:sy.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?jy(e.data,s.version)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"ip",code:sy.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?zy(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"jwt",code:sy.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?Ky(e.data,s.version)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"cidr",code:sy.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Py.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"base64",code:sy.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Dy.test(e.data)||(r=this._getOrReturnCtx(e,r),ay(r,{validation:"base64url",code:sy.invalid_string,message:s.message}),t.dirty()):Yg.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:sy.invalid_string,...yy.errToObj(r)})}_addCheck(e){return new Hy({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...yy.errToObj(e)})}url(e){return this._addCheck({kind:"url",...yy.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...yy.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...yy.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...yy.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...yy.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...yy.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...yy.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...yy.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...yy.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...yy.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...yy.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...yy.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...yy.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...yy.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...yy.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...yy.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...yy.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...yy.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...yy.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...yy.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...yy.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...yy.errToObj(t)})}nonempty(e){return this.min(1,yy.errToObj(e))}trim(){return new Hy({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Hy({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Hy({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Vy(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}Hy.create=e=>new Hy({checks:[],typeName:Nv.ZodString,coerce:e?.coerce??!1,...wy(e)});class Wy extends Cy{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==ty.number){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.number,received:t.parsedType}),dy}let t;const r=new cy;for(const s of this._def.checks)if("int"===s.kind)Yg.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),ay(t,{code:sy.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),ay(t,{code:sy.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),ay(t,{code:sy.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Vy(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),ay(t,{code:sy.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),ay(t,{code:sy.not_finite,message:s.message}),r.dirty()):Yg.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,yy.toString(t))}gt(e,t){return this.setLimit("min",e,!1,yy.toString(t))}lte(e,t){return this.setLimit("max",e,!0,yy.toString(t))}lt(e,t){return this.setLimit("max",e,!1,yy.toString(t))}setLimit(e,t,r,s){return new Wy({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:yy.toString(s)}]})}_addCheck(e){return new Wy({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:yy.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:yy.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:yy.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:yy.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:yy.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:yy.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:yy.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:yy.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:yy.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Yg.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Wy.create=e=>new Wy({checks:[],typeName:Nv.ZodNumber,coerce:e?.coerce||!1,...wy(e)});class Jy extends Cy{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ty.bigint)return this._getInvalidInput(e);let t;const r=new cy;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),ay(t,{code:sy.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),ay(t,{code:sy.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),ay(t,{code:sy.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Yg.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.bigint,received:t.parsedType}),dy}gte(e,t){return this.setLimit("min",e,!0,yy.toString(t))}gt(e,t){return this.setLimit("min",e,!1,yy.toString(t))}lte(e,t){return this.setLimit("max",e,!0,yy.toString(t))}lt(e,t){return this.setLimit("max",e,!1,yy.toString(t))}setLimit(e,t,r,s){return new Jy({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:yy.toString(s)}]})}_addCheck(e){return new Jy({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:yy.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:yy.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:yy.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:yy.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:yy.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Jy.create=e=>new Jy({checks:[],typeName:Nv.ZodBigInt,coerce:e?.coerce??!1,...wy(e)});class Zy extends Cy{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==ty.boolean){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.boolean,received:t.parsedType}),dy}return ly(e.data)}}Zy.create=e=>new Zy({typeName:Nv.ZodBoolean,coerce:e?.coerce||!1,...wy(e)});class Qy extends Cy{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==ty.date){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.date,received:t.parsedType}),dy}if(Number.isNaN(e.data.getTime())){return ay(this._getOrReturnCtx(e),{code:sy.invalid_date}),dy}const t=new cy;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),ay(r,{code:sy.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):Yg.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Qy({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:yy.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:yy.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Qy.create=e=>new Qy({checks:[],coerce:e?.coerce||!1,typeName:Nv.ZodDate,...wy(e)});class Yy extends Cy{_parse(e){if(this._getType(e)!==ty.symbol){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.symbol,received:t.parsedType}),dy}return ly(e.data)}}Yy.create=e=>new Yy({typeName:Nv.ZodSymbol,...wy(e)});class Xy extends Cy{_parse(e){if(this._getType(e)!==ty.undefined){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.undefined,received:t.parsedType}),dy}return ly(e.data)}}Xy.create=e=>new Xy({typeName:Nv.ZodUndefined,...wy(e)});class ev extends Cy{_parse(e){if(this._getType(e)!==ty.null){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.null,received:t.parsedType}),dy}return ly(e.data)}}ev.create=e=>new ev({typeName:Nv.ZodNull,...wy(e)});class tv extends Cy{constructor(){super(...arguments),this._any=!0}_parse(e){return ly(e.data)}}tv.create=e=>new tv({typeName:Nv.ZodAny,...wy(e)});class rv extends Cy{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ly(e.data)}}rv.create=e=>new rv({typeName:Nv.ZodUnknown,...wy(e)});class sv extends Cy{_parse(e){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.never,received:t.parsedType}),dy}}sv.create=e=>new sv({typeName:Nv.ZodNever,...wy(e)});class nv extends Cy{_parse(e){if(this._getType(e)!==ty.undefined){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.void,received:t.parsedType}),dy}return ly(e.data)}}nv.create=e=>new nv({typeName:Nv.ZodVoid,...wy(e)});class ov extends Cy{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==ty.array)return ay(t,{code:sy.invalid_type,expected:ty.array,received:t.parsedType}),dy;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(ay(t,{code:e?sy.too_big:sy.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(ay(t,{code:sy.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(ay(t,{code:sy.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new by(t,e,t.path,r)))).then(e=>cy.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new by(t,e,t.path,r)));return cy.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new ov({...this._def,minLength:{value:e,message:yy.toString(t)}})}max(e,t){return new ov({...this._def,maxLength:{value:e,message:yy.toString(t)}})}length(e,t){return new ov({...this._def,exactLength:{value:e,message:yy.toString(t)}})}nonempty(e){return this.min(1,e)}}function iv(e){if(e instanceof av){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Cv.create(iv(s))}return new av({...e._def,shape:()=>t})}return e instanceof ov?new ov({...e._def,type:iv(e.element)}):e instanceof Cv?Cv.create(iv(e.unwrap())):e instanceof Sv?Sv.create(iv(e.unwrap())):e instanceof lv?lv.create(e.items.map(e=>iv(e))):e}ov.create=(e,t)=>new ov({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Nv.ZodArray,...wy(t)});class av extends Cy{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Yg.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ty.object){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.object,received:t.parsedType}),dy}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),o=[];if(!(this._def.catchall instanceof sv&&"strip"===this._def.unknownKeys))for(const a in r.data)n.includes(a)||o.push(a);const i=[];for(const a of n){const e=s[a],t=r.data[a];i.push({key:{status:"valid",value:a},value:e._parse(new by(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof sv){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of o)i.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)o.length>0&&(ay(r,{code:sy.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const s=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new by(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of i){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>cy.mergeObjectSync(t,e)):cy.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return yy.errToObj,new av({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:yy.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new av({...this._def,unknownKeys:"strip"})}passthrough(){return new av({...this._def,unknownKeys:"passthrough"})}extend(e){return new av({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new av({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Nv.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new av({...this._def,catchall:e})}pick(e){const t={};for(const r of Yg.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new av({...this._def,shape:()=>t})}omit(e){const t={};for(const r of Yg.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new av({...this._def,shape:()=>t})}deepPartial(){return iv(this)}partial(e){const t={};for(const r of Yg.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new av({...this._def,shape:()=>t})}required(e){const t={};for(const r of Yg.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Cv;)e=e._def.innerType;t[r]=e}return new av({...this._def,shape:()=>t})}keyof(){return yv(Yg.objectKeys(this.shape))}}av.create=(e,t)=>new av({shape:()=>e,unknownKeys:"strip",catchall:sv.create(),typeName:Nv.ZodObject,...wy(t)}),av.strictCreate=(e,t)=>new av({shape:()=>e,unknownKeys:"strict",catchall:sv.create(),typeName:Nv.ZodObject,...wy(t)}),av.lazycreate=(e,t)=>new av({shape:e,unknownKeys:"strip",catchall:sv.create(),typeName:Nv.ZodObject,...wy(t)});class cv extends Cy{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const r=e.map(e=>new ny(e.ctx.common.issues));return ay(t,{code:sy.invalid_union,unionErrors:r}),dy});{let e;const s=[];for(const o of r){const r={...t,common:{...t.common,issues:[]},parent:null},n=o._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new ny(e));return ay(t,{code:sy.invalid_union,unionErrors:n}),dy}}get options(){return this._def.options}}function dv(e,t){const r=ry(e),s=ry(t);if(e===t)return{valid:!0,data:e};if(r===ty.object&&s===ty.object){const r=Yg.objectKeys(t),s=Yg.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const o of s){const r=dv(e[o],t[o]);if(!r.valid)return{valid:!1};n[o]=r.data}return{valid:!0,data:n}}if(r===ty.array&&s===ty.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=dv(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===ty.date&&s===ty.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}cv.create=(e,t)=>new cv({options:e,typeName:Nv.ZodUnion,...wy(t)});class uv extends Cy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(hy(e)||hy(s))return dy;const n=dv(e.value,s.value);return n.valid?((py(e)||py(s))&&t.dirty(),{status:t.value,value:n.data}):(ay(r,{code:sy.invalid_intersection_types}),dy)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}uv.create=(e,t,r)=>new uv({left:e,right:t,typeName:Nv.ZodIntersection,...wy(r)});class lv extends Cy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ty.array)return ay(r,{code:sy.invalid_type,expected:ty.array,received:r.parsedType}),dy;if(r.data.length<this._def.items.length)return ay(r,{code:sy.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),dy;!this._def.rest&&r.data.length>this._def.items.length&&(ay(r,{code:sy.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new by(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>cy.mergeArray(t,e)):cy.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new lv({...this._def,rest:e})}}lv.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new lv({items:e,typeName:Nv.ZodTuple,rest:null,...wy(t)})};class hv extends Cy{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ty.object)return ay(r,{code:sy.invalid_type,expected:ty.object,received:r.parsedType}),dy;const s=[],n=this._def.keyType,o=this._def.valueType;for(const i in r.data)s.push({key:n._parse(new by(r,i,r.path,i)),value:o._parse(new by(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?cy.mergeObjectAsync(t,s):cy.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new hv(t instanceof Cy?{keyType:e,valueType:t,typeName:Nv.ZodRecord,...wy(r)}:{keyType:Hy.create(),valueType:e,typeName:Nv.ZodRecord,...wy(t)})}}class pv extends Cy{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ty.map)return ay(r,{code:sy.invalid_type,expected:ty.map,received:r.parsedType}),dy;const s=this._def.keyType,n=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:s._parse(new by(r,e,r.path,[o,"key"])),value:n._parse(new by(r,t,r.path,[o,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of o){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return dy;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of o){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return dy;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}pv.create=(e,t,r)=>new pv({valueType:t,keyType:e,typeName:Nv.ZodMap,...wy(r)});class mv extends Cy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ty.set)return ay(r,{code:sy.invalid_type,expected:ty.set,received:r.parsedType}),dy;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(ay(r,{code:sy.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(ay(r,{code:sy.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function o(e){const r=new Set;for(const s of e){if("aborted"===s.status)return dy;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>n._parse(new by(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>o(e)):o(i)}min(e,t){return new mv({...this._def,minSize:{value:e,message:yy.toString(t)}})}max(e,t){return new mv({...this._def,maxSize:{value:e,message:yy.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}mv.create=(e,t)=>new mv({valueType:e,minSize:null,maxSize:null,typeName:Nv.ZodSet,...wy(t)});class fv extends Cy{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}fv.create=(e,t)=>new fv({getter:e,typeName:Nv.ZodLazy,...wy(t)});class gv extends Cy{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return ay(t,{received:t.data,code:sy.invalid_literal,expected:this._def.value}),dy}return{status:"valid",value:e.data}}get value(){return this._def.value}}function yv(e,t){return new vv({values:e,typeName:Nv.ZodEnum,...wy(t)})}gv.create=(e,t)=>new gv({value:e,typeName:Nv.ZodLiteral,...wy(t)});class vv extends Cy{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return ay(t,{expected:Yg.joinValues(r),received:t.parsedType,code:sy.invalid_type}),dy}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return ay(t,{received:t.data,code:sy.invalid_enum_value,options:r}),dy}return ly(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return vv.create(e,{...this._def,...t})}exclude(e,t=this._def){return vv.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}vv.create=yv;class bv extends Cy{_parse(e){const t=Yg.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ty.string&&r.parsedType!==ty.number){const e=Yg.objectValues(t);return ay(r,{expected:Yg.joinValues(e),received:r.parsedType,code:sy.invalid_type}),dy}if(this._cache||(this._cache=new Set(Yg.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Yg.objectValues(t);return ay(r,{received:r.data,code:sy.invalid_enum_value,options:e}),dy}return ly(e.data)}get enum(){return this._def.values}}bv.create=(e,t)=>new bv({values:e,typeName:Nv.ZodNativeEnum,...wy(t)});class Iv extends Cy{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ty.promise&&!1===t.common.async)return ay(t,{code:sy.invalid_type,expected:ty.promise,received:t.parsedType}),dy;const r=t.parsedType===ty.promise?t.data:Promise.resolve(t.data);return ly(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Iv.create=(e,t)=>new Iv({type:e,typeName:Nv.ZodPromise,...wy(t)});class wv extends Cy{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Nv.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{ay(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(r.data,n);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return dy;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?dy:"dirty"===s.status||"dirty"===t.value?uy(s.value):s});{if("aborted"===t.value)return dy;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?dy:"dirty"===s.status||"dirty"===t.value?uy(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?dy:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?dy:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!fy(e))return dy;const o=s.transform(e.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>fy(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):dy)}Yg.assertNever(s)}}wv.create=(e,t,r)=>new wv({schema:e,typeName:Nv.ZodEffects,effect:t,...wy(r)}),wv.createWithPreprocess=(e,t,r)=>new wv({schema:t,effect:{type:"preprocess",transform:e},typeName:Nv.ZodEffects,...wy(r)});class Cv extends Cy{_parse(e){return this._getType(e)===ty.undefined?ly(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Cv.create=(e,t)=>new Cv({innerType:e,typeName:Nv.ZodOptional,...wy(t)});class Sv extends Cy{_parse(e){return this._getType(e)===ty.null?ly(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Sv.create=(e,t)=>new Sv({innerType:e,typeName:Nv.ZodNullable,...wy(t)});class Tv extends Cy{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ty.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Tv.create=(e,t)=>new Tv({innerType:e,typeName:Nv.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...wy(t)});class _v extends Cy{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return gy(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ny(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new ny(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}_v.create=(e,t)=>new _v({innerType:e,typeName:Nv.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...wy(t)});class Rv extends Cy{_parse(e){if(this._getType(e)!==ty.nan){const t=this._getOrReturnCtx(e);return ay(t,{code:sy.invalid_type,expected:ty.nan,received:t.parsedType}),dy}return{status:"valid",value:e.data}}}Rv.create=e=>new Rv({typeName:Nv.ZodNaN,...wy(e)});class Av extends Cy{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Mv extends Cy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?dy:"dirty"===e.status?(t.dirty(),uy(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?dy:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Mv({in:e,out:t,typeName:Nv.ZodPipeline})}}class Ev extends Cy{_parse(e){const t=this._def.innerType._parse(e),r=e=>(fy(e)&&(e.value=Object.freeze(e.value)),e);return gy(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Uv(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function kv(e,t={},r){return e?tv.create().superRefine((s,n)=>{const o=e(s);if(o instanceof Promise)return o.then(e=>{if(!e){const e=Uv(t,s),o=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:o})}});if(!o){const e=Uv(t,s),o=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:o})}}):tv.create()}var Nv,Ov;Ev.create=(e,t)=>new Ev({innerType:e,typeName:Nv.ZodReadonly,...wy(t)}),(Ov=Nv||(Nv={})).ZodString="ZodString",Ov.ZodNumber="ZodNumber",Ov.ZodNaN="ZodNaN",Ov.ZodBigInt="ZodBigInt",Ov.ZodBoolean="ZodBoolean",Ov.ZodDate="ZodDate",Ov.ZodSymbol="ZodSymbol",Ov.ZodUndefined="ZodUndefined",Ov.ZodNull="ZodNull",Ov.ZodAny="ZodAny",Ov.ZodUnknown="ZodUnknown",Ov.ZodNever="ZodNever",Ov.ZodVoid="ZodVoid",Ov.ZodArray="ZodArray",Ov.ZodObject="ZodObject",Ov.ZodUnion="ZodUnion",Ov.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ov.ZodIntersection="ZodIntersection",Ov.ZodTuple="ZodTuple",Ov.ZodRecord="ZodRecord",Ov.ZodMap="ZodMap",Ov.ZodSet="ZodSet",Ov.ZodFunction="ZodFunction",Ov.ZodLazy="ZodLazy",Ov.ZodLiteral="ZodLiteral",Ov.ZodEnum="ZodEnum",Ov.ZodEffects="ZodEffects",Ov.ZodNativeEnum="ZodNativeEnum",Ov.ZodOptional="ZodOptional",Ov.ZodNullable="ZodNullable",Ov.ZodDefault="ZodDefault",Ov.ZodCatch="ZodCatch",Ov.ZodPromise="ZodPromise",Ov.ZodBranded="ZodBranded",Ov.ZodPipeline="ZodPipeline",Ov.ZodReadonly="ZodReadonly";const xv=Hy.create,Lv=Wy.create,Pv=Zy.create;tv.create;const Dv=rv.create,$v=sv.create,qv=ov.create,Gv=av.create,Bv=cv.create;uv.create,lv.create;const Fv=hv.create,jv=vv.create;Iv.create,Cv.create,Sv.create;class zv{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof ny){const e=r.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),t=`Validation failed: ${e.map(e=>`${e.path}: ${e.message}`).join("; ")}`,s=r.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received);return{success:!1,error:new Zr(t,{code:s?nt:ot,details:{fields:e}})}}return{success:!1,error:new Zr("Unknown validation error",{code:it,details:{fields:[]}})}}}static validateOrThrow(e,t){const r=this.validate(e,t);if(r.success&&void 0!==r.data)return r.data;if(r.error)throw r.error;throw new Zr("Unknown validation error",{code:it,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const Kv=e=>xv().regex(/^https?:\/\/\S+$/i,e),Hv=e=>xv().regex(/^wss?:\/\/\S+$/i,e),Vv=Gv({appKey:xv().min(1,"appKey is required"),enableUserInfoSync:Pv().optional(),enableSyncData:qv(jv(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Pv().optional(),deleteConversationOnGroupDestroyed:Pv().optional(),syncConversationListConfig:Gv({includeEmpty:Pv().optional()}).strict().optional(),useCustomAttachmentUpload:Pv().optional(),useFixedDeviceId:Pv().optional(),deviceId:xv().min(1,"deviceId is required").optional(),serviceConfig:Gv({dnsConfigUrls:qv(Kv("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:Gv({restApiUrl:Kv("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:Hv("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:Kv("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:Hv("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:Pv().optional(),customDeviceName:xv().min(1,"customDeviceName is required").optional(),customOSPlatform:Lv().int("customOSPlatform must be an integer").min(1,"customOSPlatform must be between 1 and 100").max(100,"customOSPlatform must be between 1 and 100").optional(),uiKitVersion:xv().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:xv().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:qv(Dv()).optional(),platformAdapterOptions:Gv({prefer:jv(["web","wechat-miniapp","qq-miniapp","toutiao-miniapp","baidu-miniapp","alipay-miniapp","dingtalk-miniapp","lark-miniapp","kuaishou-miniapp","jd-miniapp","360-miniapp","harmony-miniapp","quickapp","uniapp","react-native","electron-renderer","electron-main","unknown"]).optional(),runtimeInput:kv(e=>"object"==typeof e&&null!==e).optional(),overrides:kv(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{"enableMd5Check"in e&&t.addIssue({code:sy.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:sy.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:sy.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:sy.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:sy.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:sy.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:sy.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const r=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,s=r?.serverUrls&&"object"==typeof r.serverUrls?r.serverUrls:void 0;r?.dnsConfigUrls&&s&&t.addIssue({code:sy.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),s&&(s?.restApiUrl||t.addIssue({code:sy.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),s?.wsUrl||t.addIssue({code:sy.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),Wv=Gv({userId:xv().min(1,"userId is required"),token:xv().min(1,"token is required")}),Jv=xv().trim().min(1,"token is required"),Zv=Gv({channelName:xv().trim().min(1,"channelName is required").optional()}).optional(),Qv=qv(Lv({invalid_type_error:"rtcUid must be a number"}).int("rtcUid must be an integer").min(0,"rtcUid must be greater than or equal to 0").max(Number.MAX_SAFE_INTEGER,"rtcUid must be a safe integer")).nonempty("rtcUids is required").transform(e=>Array.from(new Set(e))),Yv=Gv({protocol:xv(),domain:xv().optional(),ip:xv().optional(),port:Bv([xv(),Lv()]).optional()}).passthrough(),Xv=Gv({rest:Gv({hosts:qv(Yv).nonempty()}),"msync-wx":Gv({hosts:qv(Yv).nonempty()}),"sync-ws":Gv({hosts:qv(Yv).nonempty()}).optional(),enableReportLogs:jv(["true","false"]).optional(),reportInterval:Lv().positive().finite().optional(),enableDataReport:jv(["true","false"]).optional(),enableMd5Check:jv(["true","false"]).optional(),uploadinparts_enable:jv(["true","false"]).optional()}).passthrough(),eb=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),tb=e=>"function"==typeof URLSearchParams?new URLSearchParams(e):(e=>{const t=new Map;if(e)for(const[r,s]of Object.entries(e))t.set(r,s);return{set(e,r){t.set(e,r)},toString:()=>Array.from(t,([e,t])=>`${eb(e)}=${eb(t)}`).join("&")}})(e),rb=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],sb=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],nb=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function ob(e){return"object"==typeof e&&null!==e}function ib(e){return Array.isArray(e)?{hosts:e}:function(e){return ob(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function ab(e,t,r){for(const s of t){const t=ib(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=ib(n);if(e)return{key:s,section:e}}}function cb(e){if(!ob(e))return zv.validateOrThrow(Xv,e);const t=ib(e.rest),r=ab(e,sb,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s=ab(e,nb,e=>{const t=e.toLowerCase();return!t.includes("msync")&&t.includes("sync")&&(t.includes("ws")||t.includes("socket"))}),n={...e,rest:t??e.rest,"msync-wx":r?.section};s?.section?n["sync-ws"]=s.section:"sync-ws"in n&&!ib(n["sync-ws"])&&delete n["sync-ws"];const o="true"===(i=e.enableReportLogs)||!0===i?"true":"false"===i||!1===i?"false":void 0;var i;o&&(n.enableReportLogs=o);const a=function(e){if("number"!=typeof e&&"string"!=typeof e)return;if("string"==typeof e&&""===e.trim())return;const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}(e.reportInterval);void 0!==a?n.reportInterval=a:delete n.reportInterval;const c=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);c?n.enableDataReport=c:delete n.enableDataReport;const d=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);d?n.enableMd5Check=d:delete n.enableMd5Check;const u=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return u?n.uploadinparts_enable=u:delete n.uploadinparts_enable,r&&"msync-wx"!==r.key&&To("DNS config websocket section normalized",{sourceKey:r.key}),s&&"sync-ws"!==s.key&&To("DNS config sync websocket section normalized",{sourceKey:s.key}),zv.validateOrThrow(Xv,n)}function db(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS host missing domain/ip",{code:nt,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${"https"===t?"wss":"ws"}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}/websocket`}function ub(e,t){return"https"===e?"https":"http"===e?"http":t}function lb(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS rest host missing domain/ip",{code:nt,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${t}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}`}function hb(e,t){const r=e.filter(e=>e.protocol===t);return r.length>0?r:"http"===t?e.filter(e=>"https"===e.protocol):[]}function pb(e){const t=function(e){return e.filter(e=>Boolean(e.domain))}(e);return t.length>0?t:e.filter(e=>Boolean(e.domain||e.ip))}async function mb(e,t,r){const s=new Zg(e,{requestAdapter:r,includeRequestId:!0});let n="/easemob/server.json",o=!0;try{const t=new URL(e),r=""!==t.pathname&&"/"!==t.pathname,s=""!==t.search;(r||s)&&(n="",o=!1)}catch{n="/easemob/server.json",o=!0}if(o){n=`${n}?${tb({app_key:t,_v:String(Date.now())}).toString()}`}return cb(await s.get(n))}function fb(e,t){const r=e["sync-ws"];return r&&Array.isArray(r.hosts)?r.hosts.map(e=>function(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS host missing domain/ip",{code:nt,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${"https"===t?"wss":"ws"}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}`}(e,ub(e.protocol,t))).filter(e=>"string"==typeof e&&e.length>0):[]}async function gb(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:rb;if(0===t.length)throw new Zr("DNS_CONFIG list is empty",{code:nt,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const r=e.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let s;for(const i of t)try{const t=await mb(i,e.appKey,e.requestAdapter),s=pb(hb(t["msync-wx"].hosts,r));if(0===s.length)throw new Zr("DNS msync-wx hosts resolution failed",{code:ot,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const n=s[0];if(!n)throw new Zr("DNS msync-wx hosts resolution failed",{code:ot,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const o=hb(t.rest.hosts,r);if(0===o.length)throw new Zr("DNS rest hosts resolution failed",{code:ot,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const a=o[0];if(!a)throw new Zr("DNS rest hosts resolution failed",{code:ot,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const c=s.map(e=>db(e,ub(e.protocol,r))),d=db(n,ub(n.protocol,r)),u=fb(t,r);return{websocketUrl:d,websocketUrls:c,syncWebsocketUrls:u,baseUrl:i,restBaseUrl:lb(a,ub(a.protocol,r)),dnsConfig:t}}catch(o){To("DNS config candidate failed",{baseUrl:i,reason:o instanceof Error?o.message:String(o),error:o instanceof Error&&"function"==typeof o.toJSON?o.toJSON():o}),s=o}const n={stage:"dns"};throw s&&(n.reason=s.message,"code"in s&&"number"==typeof s.code&&(n.causeCode=s.code)),new Wr("DNS_CONFIG exhausted",{code:wt,details:n})}const yb=e=>new Zr(e,{code:ot,details:{reason:"invalid_rest_response"}}),vb=e=>{if(!_l(e))throw yb("Invalid REST response");return _l(e.data)?e.data:e},bb=(e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&t.trim().length>0){const e=Number(t);if(Number.isFinite(e))return e}}},Ib=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},wb=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},Cb=async(e,t)=>{const r=await e.get((e=>`${wb(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=vb(e),r=bb(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw yb("Invalid token expires response");return r})(r)},Sb=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=tb({channelName:t?.channelName??"*"});return`${wb(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=vb(e);return{appId:Ib(t,["app_id","appId"])??"",rtcToken:Ib(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:Ib(t,["channel_name","channelName"])??"",rtcUid:bb(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:bb(t,["expires_in","expire","expireAt"])??0}})(s)},Tb=async(e,t,r)=>{const s=await e.post((e=>`${wb(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=vb(e),r={};for(const[s,n]of Object.entries(t)){const e=Number(s);!Number.isSafeInteger(e)||e<0||"string"!=typeof n||(r[e]=n)}return r})(s)},_b=async(e,t)=>{const r=await e.get((e=>`${wb(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=_l(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!_l(n))continue;const e=Ib(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},Rb=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},Ab={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},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:{}},Mb=e=>({userId:e}),Eb=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Ub=e=>e,kb=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const i of n)s.set(i.userId,Eb(i));const o=r.filter(e=>!s.has(e));if(o.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:o});for(const t of e)s.set(t.userId,Ub(t))}for(const i of r)s.has(i)||s.set(i,Mb(i));return s};class Nb{constructor(e){this.options=e,this.pendingGroups=new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,r){if(!e||!t)return;const s=this.pendingGroups.get(e)??new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,s),this.pendingOrder.push(e));const n=s.get(t);s.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(n?.namecardUpdateTime,r)}),this.schedule()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingGroups.clear(),this.pendingOrder.length=0,this.readyGroups.length=0,this.activeGroups.clear(),this.activeGroupCount=0}getOptions(){return{windowMs:this.options.windowMs,minWindowMs:this.options.minWindowMs,maxBatchSize:this.options.maxBatchSize,maxConcurrency:this.options.maxConcurrency}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushWindow()},this.resolveWindowDelay()))}flushWindow(){if(0!==this.pendingOrder.length){for(const e of this.pendingOrder){const t=this.pendingGroups.get(e);if(!t||0===t.size)continue;const r=Array.from(t.values()),s=Math.max(1,this.options.maxBatchSize);for(let n=0;n<r.length;n+=s)this.readyGroups.push({groupId:e,targets:r.slice(n,n+s)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const e=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(e<0)return;const t=this.readyGroups.splice(e,1)[0];if(!t)return;this.activeGroupCount+=1,this.activeGroups.add(t.groupId),Promise.resolve(this.options.onFlushGroup(t)).catch(e=>{To("Group namecard hydration queue flush failed",{groupId:t.groupId,userIds:t.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(t.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),r=t-e;return r<=0?t:e+Math.floor(Math.random()*(r+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class Ob{constructor(e){this.options=e,this.pendingTargets=new Map,this.readyBatches=[],this.timer=null,this.activeCount=0,this.generation=0}enqueue(e,t){e&&(this.mergeWaitingTarget({userId:e,userInfoUpdateTime:t,retryCount:0}),this.pendingTargets.size>=this.options.batchSize?this.flush():this.schedule())}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTargets.clear(),this.readyBatches.length=0,this.generation+=1}getOptions(){return{windowMs:this.options.windowMs,batchSize:this.options.batchSize,maxConcurrency:this.options.maxConcurrency,maxRetries:this.options.maxRetries}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.windowMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),0===this.pendingTargets.size)return;const e=Array.from(this.pendingTargets.values());this.pendingTargets.clear();const t=Math.max(1,this.options.batchSize);for(let r=0;r<e.length;r+=t)this.readyBatches.push(e.slice(r,r+t));this.runReadyBatches()}runReadyBatches(){const e=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<e&&this.readyBatches.length>0;){const e=this.readyBatches.shift();if(!e)return;const r=this.generation;this.activeCount+=1;const s=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let n;try{n=Promise.resolve(this.options.onFlush(s))}catch(t){n=Promise.reject(t instanceof Error?t:new Error(String(t)))}n.catch(t=>{const s=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(To("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:s.length>0,error:t instanceof Error?t.message:String(t)}),r===this.generation&&0!==s.length){for(const e of s)this.mergeWaitingTarget(e);this.flush()}}).finally(()=>{this.activeCount-=1,this.runReadyBatches()})}}mergeWaitingTarget(e){for(const r of this.readyBatches){const t=r.findIndex(t=>t.userId===e.userId);if(t>=0){const s=r[t];return void(s&&(r[t]=this.mergeTarget(s,e)))}}const t=this.pendingTargets.get(e.userId);this.pendingTargets.set(e.userId,t?this.mergeTarget(t,e):e)}mergeTarget(e,t){return{userId:e.userId,userInfoUpdateTime:this.resolveMaxVersion(e.userInfoUpdateTime,t.userInfoUpdateTime),retryCount:Math.max(e.retryCount,t.retryCount)}}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}const xb=0,Lb=1,Pb=2,Db=3,$b=4,qb=5,Gb=0,Bb=0,Fb=1,jb=1001,zb=1002,Kb=1003,Hb=1004,Vb=1005,Wb=1101,Jb=Rb(Ab,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Zb=class e{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=t,this.loginAttempt=0,this.currentUserId=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=new Set,this.config={appKey:e.appKey,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.config.platformAdapterOptions&&(this.platformAdapter=Zu(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new jf,this.managerEventContext={addEventHandler:(e,t)=>{this.eventHub.addEventHandler(e,t)},removeEventHandler:e=>{this.eventHub.removeEventHandler(e)},dispatch:(e,t)=>{this.eventHub.dispatch(e,t)}},this.userInfoHydrationQueue=new Ob({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Nb({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:1e3,maxBatchSize:50,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[i]:e=>{this.updateState(e.state)},[a]:e=>{this.updateState(e.state)},[c]:e=>{this.updateState(e.state)},[d]:e=>{this.updateState(e.state)},[k]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[N]:e=>{this.handleIncomingConversationStreamMessage(e)},[b]:e=>{this.handleOutgoingConversationMessage(e)},[G]:e=>{this.handleMultiDeviceContactEvent(e)},[B]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[V]:e=>this.handleIncomingContactRosterEvent("add",e),[J]:e=>this.handleIncomingContactRosterEvent("add",e),[K]:e=>this.handleIncomingContactRosterEvent("none",e),[W]:e=>this.handleIncomingContactRosterEvent("none",e),[H]:e=>this.handleIncomingContactRosterEvent("remove",e),[f]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===ne&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[g]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[y]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[v]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(t){const r=zv.validateOrThrow(Vv,t),s=r.customOSPlatform,n=e.normalizeServiceConfig(r.serviceConfig),o={appKey:r.appKey,enableUserInfoSync:r.enableUserInfoSync??!1,enableSyncData:e.normalizeSyncDataTypes(r.enableSyncData??["conversation"]),enableDeliveryReceipt:r.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:r.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:r.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:r.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:n,useFixedDeviceId:r.useFixedDeviceId??!0,deviceId:r.deviceId??"webim",useReplacedMessageContents:r.useReplacedMessageContents??!1,customDeviceName:void 0!==s?r.customDeviceName:void 0,customOSPlatform:s,uiKitVersion:r.uiKitVersion,loginExtensionInfo:r.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:7e3,userInfoBatchSize:20,groupNamecardWindowMs:7e3,groupNamecardMaxConcurrency:5},platformAdapterOptions:r.platformAdapterOptions},i=t.managers??[];if(e.instance){if(!e.isSameConfig(e.instance.config,o))throw new Zr("ChatClient already initialized with different config",{code:ot,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:e.instance.config,next:o}});return i.length>0&&e.instance.registerManagers(i),e.instance.validateOptionalCapabilityDependencies(),e.instance}return e.instance=new e(o),i.length>0&&e.instance.registerManagers(i),e.instance.validateOptionalCapabilityDependencies(),e.instance}async login(n){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const o=zv.validateOrThrow(Wv,n);if(this.state===r||this.state===s){const e=this.currentUserId&&this.currentUserId!==o.userId;throw new Wr(e?"Another user is already logged in":"ChatClient is already connecting or connected",{code:e?Jt:at,details:{stage:"auth",...e?{currentUserId:this.currentUserId,nextUserId:o.userId}:{}}})}const i=++this.loginAttempt;To("Login started",{userId:o.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const a=this.platformAdapter??Zu(this.config.platformAdapterOptions);var c;this.platformAdapter=a,c={requestAdapter:a.request,onDiagnostic:(e,t)=>{To(e,t)}},Gp?.reset(),Gp=new qp(c);const d=(e=>Gp?.startSession(e))({appKey:this.config.appKey,uid:o.userId,sdkVersion:"5.0.1",platform:a.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),u=a.runtime.getNetworkType?.();u&&u.then(e=>{Fp(e)}).catch(()=>{Fp("unknown")});const l=jp({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:o.userId});let h,p,m;this.updateState(r),this.logReportEnabled=!1,bo("unknown");let f,g=!1,y=!1,v=!0;if("dns"===this.config.serviceConfig.mode){const e=l?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await gb({appKey:this.config.appKey,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:a.request});To("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,syncWsCount:t.syncWebsocketUrls.length,restBaseUrl:t.restBaseUrl}),h=t.websocketUrl,p=t.websocketUrls,this.contactSyncWsUrls=t.syncWebsocketUrls,this.syncConversationListConfigWsUrls=t.syncWebsocketUrls,this.contactSyncDnsResolved=!0,m=t.restBaseUrl,g="true"===t.dnsConfig.enableReportLogs,f=t.dnsConfig.reportInterval,y="true"===t.dnsConfig.enableMd5Check,v="false"!==t.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),Bp(t.dnsConfig.enableDataReport),So("DNS report switch resolved",{enabled:g})}catch(w){const r=w instanceof Hr?w.code:-1,s=w instanceof Error?w.message:String(w);throw e?.finish({code:r,success:!1,description:s}),l?.finish({code:r,success:!1,description:s}),Bp(void 0),bo("disabled"),this.updateState(t),w}}else{const e=this.config.serviceConfig.serverUrls;if(!e?.wsUrl||!e.restApiUrl){const e=new Zr("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:nt,details:{fields:[{path:"serviceConfig.serverUrls.restApiUrl",message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured",rule:"required"},{path:"serviceConfig.serverUrls.wsUrl",message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured",rule:"required"}]}});throw l?.finish({code:e.code,success:!1,description:e.message}),Bp(void 0),this.updateState(t),e}h=e.wsUrl,m=e.restApiUrl,y=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=e.syncWsUrl?[e.syncWsUrl]:[],this.contactSyncDnsResolved=!1,Bp(void 0)}var b;if(Io({restBaseUrl:m,appKey:this.config.appKey,userId:o.userId,token:o.token,requestAdapter:a.request}),b=f,uo.updateReportInterval(b),this.logReportEnabled=g,bo(g?"enabled":"disabled"),this.resetCore(),i!==this.loginAttempt){const e=new Wr("Login cancelled",{code:yt,details:{stage:"auth"}});throw l?.finish({code:yt,success:!1,description:e.message}),this.updateState(t),zp(),e}this.core=new jm({serverUrl:h,serverUrls:p,userId:o.userId,token:o.token,appKey:this.config.appKey,restBaseUrl:m,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:y,enableMultipartUpload:v,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:d,platformAdapter:a,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),Io({resource:this.core.getClientResource()});const I=l?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:h});try{if(To("Connecting core websocket",{serverUrl:h,restBaseUrl:m,userId:o.userId}),await this.core.connect(),I?.finish({code:200,success:!0}),l?.finish({code:0,success:!0}),To("Core websocket connected",{userId:o.userId,resource:this.core.getClientResource()}),this.currentUserId=o.userId,(e=>{Gp?.updateSession(e)})({uid:o.userId}),this.restBaseUrl=m??null,this.authToken=o.token,this.clientResource=this.core.getClientResource(),await this.initCacheManager(o.userId),To("Cache initialized after login",{userId:o.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),await this.syncSelfUserInfoAfterLogin(),this.config.enableSyncData.includes("conversation")&&await this.refreshSessionList(this.config.syncConversationListConfig),this.triggerConfiguredSyncDataAfterLogin(o.userId),this.logReportEnabled)try{await wo()}catch(w){To("Report logs on login failed",w)}}catch(w){const e=w instanceof Hr?w.code:-1,r=w instanceof Error?w.message:String(w);throw I?.finish({code:e,success:!1,description:r}),l?.finish({code:e,success:!1,description:r}),this.resetCore(),this.updateState(t),zp(),w}}async logout(){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(this.loginAttempt+=1,!this.core)return this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.resetManagerSessionRuntimes(),this.updateState(t),this.logReportEnabled=!1,bo("disabled"),Co(),void zp();try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await wo()}catch(r){To("Report logs on logout failed",r)}await this.core.disconnect()}finally{this.resetCore(),this.updateState(t),this.logReportEnabled=!1,bo("disabled"),Co(),zp()}}getConnectionState(){return this.state}getCurrentUserId(){return this.currentUserId}getClientResource(){return this.clientResource??this.core?.getClientResource()??null}getMessageCreationOptions(){return{useCustomAttachmentUpload:this.config.useCustomAttachmentUpload}}getRestContext(){if(!this.restBaseUrl)throw new Zr("restBaseUrl is required",{code:nt,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new Zr("token is required",{code:nt,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new Zr("userId is required",{code:nt,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const e=this.clientResource??this.core?.getClientResource();if(!e)throw new Zr("clientResource is required",{code:nt,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.config.appKey,userId:this.currentUserId,token:this.authToken,clientResource:e}}async renewToken(e){const t=zv.validateOrThrow(Jv,e);if(!this.core||!this.currentUserId||this.state!==s)throw new Wr("ChatClient is not connected",{code:ct,details:{stage:"token",state:this.state}});const r=this.getRestContext(),n={...r},o=new Zg(n.restBaseUrl,{errorMap:Jb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});o.setAuthToken(t),To("Renew token started",{userId:r.userId});const i=await Cb(o,n);if(i<=Date.now())throw new Wr("Token is expired",{code:lt,details:{stage:"token"}});const a=this.core.renewToken(t,i);return this.authToken=t,Io({token:t}),To("Renew token succeeded",{userId:r.userId,expireAt:i}),a}async getRTCTokenInfo(e){const t=zv.validateOrThrow(Zv,e),r=this.getRestContext(),s=new Zg(r.restBaseUrl,{errorMap:Jb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),To("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),Sb(s,r,t)}async getUserIdsWithRTCUids(e){const t=zv.validateOrThrow(Qv,e),r=this.getRestContext(),s=new Zg(r.restBaseUrl,{errorMap:Jb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),To("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),Tb(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new Zg(e.restBaseUrl,{errorMap:Jb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),To("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),_b(t,e)}getCacheManager(){return this.cacheManager}getManagerByCapability(e){return this.managerCapabilities.get(e)}getUploadAdapter(){return this.platformAdapter?.upload??null}getRequestAdapter(){return this.platformAdapter?.request}addInternalEvent(e,t){this.eventHub.dispatch(e,t)}refreshSessionList(e){return this.cacheManager&&this.currentUserId?this.ensureSessionListSyncController().refresh({includeEmpty:e?.includeEmpty??this.config.syncConversationListConfig.includeEmpty,includeMark:!0}).then(e=>(this.enqueueMissingGroupSessionSenderUserInfos(e),e.map(e=>({...e})))):Promise.resolve([])}getServerUrlsConfig(){return this.config.serviceConfig.serverUrls}getSessionListSyncWsUrls(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;return e?this.buildAuthenticatedSessionListSyncUrls([e]):this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new zg({socketAdapter:this.platformAdapter?.socket,getUrls:async()=>{const e=this.getSessionListSyncWsUrls();return e.length>0?e:await this.resolveContactSyncUrls()}})),this.syncWebSocketSession}isSessionListDnsProbeAvailable(){return"dns"===this.config.serviceConfig.mode}getSessionListSyncCapabilityState(){return this.syncConversationListConfigController?.getCapabilityState()??null}markConversationAccess(e){this.cacheManager?.markConversationAccess(e)}handleIncomingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleIncomingConversationStreamMessage(e){if(!this.cacheManager)return;const t=e.msgServerId||e.msgLocalId,r=e.stream.status===rt.START_COMPLETED||e.stream.status===rt.FULL||e.stream.status===rt.COMPLETED||e.stream.status===rt.ERROR;if(!this.activeIncomingStreamMessageIds.has(t))return this.applyIncomingConversationMessagePatch(e),void(r||this.activeIncomingStreamMessageIds.add(t));if(!r)return;this.activeIncomingStreamMessageIds.delete(t);this.cacheManager.loadSessionList().some(e=>e.lastMessage?.msgServerId===t)&&this.applyIncomingConversationMessagePatch(e)}applyIncomingConversationMessagePatch(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleOutgoingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}async handleMultiDeviceConversationEvent(e){if("CONVERSATION_DELETED"!==e.operation||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e.conversationId,type:e.conversationType??"singleChat",deletedAt:e.timestamp??Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}async handleGroupDestroyedConversation(e){if(!this.config.deleteConversationOnGroupDestroyed||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e,type:"groupChat",deletedAt:Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}handleMultiDeviceContactEvent(e){if("CONTACT_REMOVE"!==e.operation||!this.cacheManager)return;this.cacheManager.applyContactRosterNotice({action:"remove",userId:e.targetUserId,rosterVersion:e.rosterVersion}).changed&&this.cacheManager.flushPending()}getContactSnapshot(){return this.cacheManager?this.cacheManager.loadContactSnapshot("cache"):null}handleIncomingContactRosterEvent(e,t){const r=this.resolveContactRosterTargetUserId(t);if(r)return this.cacheManager&&this.currentUserId&&"none"!==e&&this.cacheManager.applyContactRosterNotice({action:e,userId:r,rosterVersion:dh(t)}),this.hydrateContactRosterPayload(t,r,"remove"!==e)}resolveContactRosterTargetUserId(e){const t=this.currentUserId;return t?e.from===t&&e.to!==t?e.to:e.to===t&&e.from!==t||e.from&&e.from!==t?e.from:e.to&&e.to!==t?e.to:null:null}async hydrateContactRosterPayload(e,t,r){const s=await(async(e,t)=>((e,t,r)=>({userId:r,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 kb([e],t)).get(e),e))(t,{cacheManager:this.cacheManager,fetchUserInfos:r?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=s}async fetchContactEventUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoReadCapability();if(!t)return[];try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return To("Contact roster event user info fetch failed",{userIds:e,error:r}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const e=this.getUserInfoReadCapability();if(e)try{0===(await e.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&To("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){To("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=ih(e),r=e.sender.userId;if(!r||!this.cacheManager)return;const s=this.cacheManager.getUserInfoSummaries([r],!1)[0];if(s&&(e.sender={userId:r,nickname:s.nickname??e.sender.nickname,avatarUrl:s.avatarUrl??e.sender.avatarUrl}),"number"==typeof t?.userInfoUpdateTime?this.shouldHydrateUserInfo(s?.userInfoUpdateTime,t.userInfoUpdateTime)&&this.userInfoHydrationQueue.enqueue(r,t.userInfoUpdateTime):s||this.userInfoHydrationQueue.enqueue(r),"groupChat"!==e.conversationType)return;const n=this.cacheManager.getGroupNamecard(e.conversationId,r,!1);"number"==typeof t?.namecardUpdateTime?this.shouldHydrateGroupNamecard(n?.namecardUpdateTime,t.namecardUpdateTime)&&this.groupNamecardHydrationQueue.enqueue(e.conversationId,r,t.namecardUpdateTime):n||this.groupNamecardHydrationQueue.enqueue(e.conversationId,r)}attachOutgoingMessageProfileVersions(e){if(!this.isMessageProfileSyncEnabled())return void(e=>{nh.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};oh(e,t)}resolveCurrentUserInfoUpdateTime(){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getUserInfoSummaries([this.currentUserId],!1)[0]?.userInfoUpdateTime}resolveCurrentGroupNamecardUpdateTime(e){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getGroupNamecard(e,this.currentUserId,!1)?.namecardUpdateTime}shouldHydrateUserInfo(e,t){return"number"!=typeof e||e<t}shouldHydrateGroupNamecard(e,t){return"number"!=typeof e||e<t}async flushUserInfoHydrationTargets(e){const t=this.getUserInfoReadCapability();if(!t||0===e.length)return;const r=e.map(e=>e.userId);let s;try{s=await t.getUserInfoByUserId({userIds:r})}catch(d){throw To("User info hydration failed",{userIds:r,error:d}),d}const n=this.currentUserId,o=n?s.find(e=>e.userId===n):void 0,i=s.filter(e=>e.userId!==n);o&&this.dispatchOwnInfoUpdated(o),i.length>0&&this.dispatchUserInfoUpdated(i),s.length>0&&this.refreshConversationDisplayFromUserInfos(s.map(e=>({userId:e.userId})),"profile");const a=new Set(s.map(e=>e.userId)),c=r.filter(e=>!a.has(e));c.length>0&&To("User info hydration returned partial result",{requestedUserIds:r,missingUserIds:c})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(r){To("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:r})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(t),this}async sendMessage(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!t?.sender?.userId)throw new Zr("sender.userId is required",{code:nt,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&t.sender.userId!==this.currentUserId)throw new Zr("sender.userId does not match current user",{code:ot,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(st(t))throw new Qr("Stream message send is not supported",{code:or,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.core||this.state!==s)throw new Qr("ChatClient is not connected",{code:St,details:{msgLocalId:t.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(t),this.core.sendMessage(t,r)}dispatchOwnInfoUpdated(e){this.eventHub.dispatch("onOwnInfoUpdated",e)}dispatchUserInfoUpdated(e){0!==e.length&&this.eventHub.dispatch("onUserInfoUpdated",[...e])}refreshConversationDisplayFromUserInfos(e,t="profile"){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromUserInfos(e).changed&&this.emitConversationListUpdate(t)}refreshConversationDisplayFromJoinedGroups(e,t="profile",r){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromJoinedGroups(e.map(e=>({groupId:e.groupId,name:e.name,avatarUrl:e.avatarUrl,remindType:e.remindType})),r).changed&&this.emitConversationListUpdate(t)}enqueueMissingGroupSessionSenderUserInfos(e){if(!this.isMessageProfileSyncEnabled()||!this.cacheManager||0===e.length)return;const t=new Set;for(const n of e){const e="groupChat"===n.conversationType?n.lastMessage?.sender:null;!e?.userId||e.nickname&&e.avatarUrl||t.add(e.userId)}if(0===t.size)return;const r=this.cacheManager.getUserInfoSummaries([...t],!1),s=new Set(r.map(e=>e.userId));for(const n of t)s.has(n)||this.userInfoHydrationQueue.enqueue(n)}dispatchUserGroupNamecardUpdated(e,t,r){e&&t&&this.eventHub.dispatch(Ce,{groupId:e,userId:t,namecard:r})}async downloadAndParseCombinePayload(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(t)}async sendMessageAction(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.downloadAttachment(t)}decodeServerMessageMeta(e){if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.decodeServerMessageMeta(e)}registerManagers(e){if(0===e.length)return;const t=new Set;for(const r of e){const e=this.resolveManagerKey(r);if(t.has(e))throw this.buildManagerValidationError(`Manager key duplicated: ${e}`,ot,"managers.key","conflict",{managerKey:e});t.add(e)}for(const r of e)this.registerManagerInput(r)}registerManagerInput(t){return e.isManagerConstructor(t)?this.registerManagerConstructor(t):this.registerManagerInstance(t)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),r=this.managerRegistry.get(t);if(r){if(r.constructor===e)return r;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const s=new e;return s.bind(this,this.managerEventContext),this.managerRegistry.set(t,s),this.registerManagerCapabilities(s),this.attachManager(t,s),s}registerManagerInstance(e){const t=this.getManagerKeyFromInstance(e),r=this.managerRegistry.get(t);if(r){if(r===e)return e;if(r.constructor===e.constructor)throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"instance-conflict");throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"constructor-mismatch")}return e.bind(this,this.managerEventContext),this.managerRegistry.set(t,e),this.registerManagerCapabilities(e),this.attachManager(t,e),e}registerManagerCapabilities(e){for(const t of e.capabilities??[])this.managerCapabilities.set(t,e)}dispatchRawNotifyToCapability(e,t){const r=this.getManagerByCapability(e);return r?.handleRawNotify?.(t)}getUserInfoReadCapability(){const e=this.getManagerByCapability("userInfo:read");return e&&this.hasUserInfoReadCapability(e)?e:null}getGroupNamecardHydrationCapability(){const e=this.getManagerByCapability("group:namecard");return e&&this.hasGroupNamecardHydrationCapability(e)?e:null}validateOptionalCapabilityDependencies(){if(this.config.enableUserInfoSync&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","userInfo:read",["UserInfoManager"]);if(this.config.enableUserInfoSync&&!this.getGroupNamecardHydrationCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","group:namecard",["GroupManager"]);if(this.config.enableSyncData.includes("contact")&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableSyncData: ['contact']","userInfo:read",["UserInfoManager"]);if(this.config.enableSyncData.includes("group")&&!this.managerRegistry.has("groupManager"))throw this.buildMissingCapabilityError("enableSyncData: ['group']","rawNotify:group",["GroupManager"])}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}hasGroupNamecardHydrationCapability(e){return"function"==typeof e.hydrateMessageProfileGroupNamecards}buildMissingCapabilityError(e,t,r){return new Zr(`${e} requires explicit manager capability: ${t}`,{code:nt,details:{fields:[{path:e,message:`${e} requires explicit manager capability: ${t}`,rule:"dependency"}],capability:t,requiredManagers:r}})}resolveManagerKey(t){if(e.isManagerConstructor(t))return this.getManagerKeyFromConstructor(t);if("object"!=typeof t||null===t)throw this.buildManagerValidationError("Manager must be constructor or instance",ot,"managers","type",{receivedType:typeof t});return this.getManagerKeyFromInstance(t)}getManagerKeyFromConstructor(e){const t=e.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",nt,"managers.key","required",{managerType:"constructor",managerName:this.getManagerNameFromConstructor(e)});return t}getManagerKeyFromInstance(e){const t=e.constructor.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",nt,"managers.key","required",{managerType:"instance",managerName:this.getManagerNameFromInstance(e)});return t}attachManager(e,t){Object.prototype.hasOwnProperty.call(this,e)||Object.defineProperty(this,e,{value:t,writable:!1,enumerable:!0})}isValidManagerKey(e){return"string"==typeof e&&e.trim().length>0}getManagerNameFromConstructor(e){return"string"==typeof e.name&&e.name.length>0?e.name:"AnonymousManager"}getManagerNameFromInstance(e){const t=e.constructor;return"string"==typeof t.name&&t.name.length>0?t.name:"AnonymousManager"}buildManagerValidationError(e,t,r,s,n){return new Zr(e,{code:t,details:{fields:[{path:r,message:e,rule:s}],...n}})}buildManagerConflictError(e,t,r,s){return this.buildManagerValidationError("Manager key conflict",ot,"managers.key","conflict",{managerKey:e,existingName:t,incomingName:r,reason:s})}static isManagerConstructor(e){return"function"==typeof e}updateState(e){this.state!==e&&(this.state=e)}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new Ff({appKey:this.config.appKey,userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const r=this.cacheManager.loadSessionList().map(Eg),s=this.buildConversationListPatch(this.conversationListSnapshot,r,t);(s.reset||0!==s.upserted.length||0!==s.removed.length||s.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=r,this.eventHub.dispatch(O,{version:this.conversationListVersion,items:r,reason:e,patch:s}))}buildConversationListPatch(e,t,r){const s=new Map(e.map(e=>[this.buildConversationListKey(e),e])),n=new Map(t.map(e=>[this.buildConversationListKey(e),e])),o=new Set,i=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=s.get(e);t&&this.isConversationListItemEqual(t,d)||(i.push(d),o.add(e))}for(const d of e){const e=this.buildConversationListKey(d);n.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),o.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)o.add(this.buildConversationListKey(d));return{reset:r,upserted:i,removed:a,affectedKeys:[...o],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,r)=>e===t.marks[r])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}triggerConfiguredSyncDataAfterLogin(e){this.config.enableSyncData.includes("contact")&&(To("Triggering automatic contact sync after login",{userId:e}),this.triggerContactSync()),this.config.enableSyncData.includes("group")&&(To("Triggering automatic group sync after login",{userId:e}),this.triggerGroupSync())}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new $g(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const e=this.managerRegistry.get("contactManager");if(!e?.createSyncController)throw new Zr("ContactManager is required for contact sync",{code:nt,details:{fields:[{path:"contactManager",message:"ContactManager must be registered for enableSyncData: ['contact']",rule:"required"}]}});return this.contactSyncController=e.createSyncController({getContextState:()=>{const e=this.requireCacheManager();return{cacheMeta:e.loadContactCacheMeta(),versionState:e.loadContactVersionState(),cachedSnapshot:e.loadContactSnapshot("cache")}},queryMetadata:async e=>await Qg(this.getContactSyncRestContext(),e,this.platformAdapter?.request),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),buildRosterRequest:({version:e})=>this.buildContactRosterRequest(e),applySyncResult:e=>{const t=this.requireCacheManager().applyContactSync(e);return this.refreshConversationDisplayFromUserInfos(t.snapshot.items.map(e=>({userId:e.userId})),"profile"),t},onStart:()=>{this.emitSyncDataStart("contact")},onFinish:e=>{this.emitSyncDataFinished({dataType:"contact",status:e?.error?"failed":"success",error:e?.error?{dataType:"contact",code:e.error.code,stage:e.error.stage,message:e.error.message,retryable:e.error.retryable}:void 0})}}),this.contactSyncController}ensureGroupSyncController(){if(this.groupSyncController)return this.groupSyncController;const e=this.managerRegistry.get("groupManager");if(!e?.createSyncController)throw new Zr("GroupManager is required for group sync",{code:nt,details:{fields:[{path:"groupManager",message:"GroupManager must be registered for enableSyncData: ['group']",rule:"required"}]}});return this.groupSyncController=e.createSyncController({getRestContext:()=>this.getRestContext(),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),getCacheManager:()=>this.requireCacheManager(),applyRuntimeSnapshot:e=>{const t=this.managerRegistry.get("groupManager");t?.applyJoinedGroupSnapshot?.(e),this.refreshConversationDisplayFromJoinedGroups(e.items,"profile")},getRuntimeSnapshot:()=>{const e=this.managerRegistry.get("groupManager");return e?.getJoinedGroupSnapshotForSync?.()??null},onStart:()=>{this.emitSyncDataStart("group")},onFinish:e=>{this.emitSyncDataFinished({dataType:"group",status:e.status,error:e.error})}}),this.groupSyncController}emitSyncDataStart(e){this.eventHub.dispatch(F,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(j,e)}requireCacheManager(){if(!this.cacheManager)throw new Zr("cacheManager is required",{code:nt,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;if(e)return this.buildAuthenticatedContactSyncUrls([e]);if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw To("Automatic contact sync sync-ws is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw To("Automatic contact sync sync-ws is unavailable without dns service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});try{const e=await gb({appKey:this.config.appKey,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=e.syncWebsocketUrls,this.contactSyncDnsResolved=!0}catch(t){throw To("Automatic contact sync sync-ws DNS resolve failed",{userId:this.currentUserId,reason:t instanceof Error?t.message:String(t)}),new Hr("Contact sync websocket dns resolve failed",Cr,{details:{stage:"socket_connect",cause:t instanceof Error?t.message:String(t)}})}if(0===this.contactSyncWsUrls.length)throw To("Automatic contact sync sync-ws is unavailable after DNS resolve",{userId:this.currentUserId,serviceConnectionMode:"dns"}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls)}buildAuthenticatedContactSyncUrls(e){const t=this.requireContactSyncToken();return this.shuffleContactSyncUrls(e.map(e=>this.buildContactSyncSocketUrl(e,t)))}buildAuthenticatedSessionListSyncUrls(e){if(0===e.length)return[];const t=this.requireContactSyncToken();return e.map(e=>this.buildContactSyncSocketUrl(e,t))}requireContactSyncToken(){if(this.authToken)return this.authToken;throw new Zr("token is required",{code:nt,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const r=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new Zr("sync websocket URL must use ws or wss protocol");const s=r.indexOf("#"),n=s>=0?r.slice(s):"",o=s>=0?r.slice(0,s):r,i=o.indexOf("?"),a=i>=0?o.slice(0,i):o,c=i>=0?o.slice(i+1):"",d=a.indexOf("://")+3,u=a.indexOf("/",d),l=u<0||"/"===a.slice(u)?`${a}/ws`:a,h=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),p=encodeURIComponent(t).replace(/%20/g,"+");return h.push(`token=${p}`),`${l}?${h.join("&")}${n}`}shuffleContactSyncUrls(e){const t=[...e];for(let r=t.length-1;r>0;r-=1){const e=Math.floor(Math.random()*(r+1)),s=t[r],n=t[e];s&&n&&(t[r]=n,t[e]=s)}return t}buildContactRosterRequest(e){const t=this.getContactSyncRestContext(),{orgName:r,appName:s}=Qn(t.appKey);return{type:Db,header:{resource:t.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:r,app:s,username:t.userId,version:e,cursor:0}}resetCore(){this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core&&(this.core.destroy(),this.core=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.resetManagerSessionRuntimes())}resetManagerSessionRuntimes(){const e=this.managerRegistry.get("groupManager");e?.resetSessionRuntime?.()}getContactSyncRestContext(){const e=this.getRestContext(),t=this.config.serviceConfig.serverUrls?.syncRestApiUrl;return t?{...e,restBaseUrl:t}:e}static isSameConfig(t,r){return t.appKey===r.appKey&&(!!e.isSameStringArray(t.enableSyncData,r.enableSyncData)&&(t.useCustomAttachmentUpload===r.useCustomAttachmentUpload&&(t.enableMd5Check===r.enableMd5Check&&(!!e.isSameServiceConfig(t.serviceConfig,r.serviceConfig)&&(t.useFixedDeviceId===r.useFixedDeviceId&&(t.deviceId===r.deviceId&&(t.useReplacedMessageContents===r.useReplacedMessageContents&&(t.customDeviceName===r.customDeviceName&&(t.customOSPlatform===r.customOSPlatform&&(t.platformAdapterOptions?.prefer===r.platformAdapterOptions?.prefer&&(t.platformAdapterOptions?.runtimeInput===r.platformAdapterOptions?.runtimeInput&&(t.platformAdapterOptions?.overrides===r.platformAdapterOptions?.overrides&&(t.uiKitVersion===r.uiKitVersion&&(t.cacheEncryptionMode===r.cacheEncryptionMode&&(t.enableUserInfoSync===r.enableUserInfoSync&&(t.deleteConversationOnGroupDestroyed===r.deleteConversationOnGroupDestroyed&&(t.syncConversationListConfig.includeEmpty===r.syncConversationListConfig.includeEmpty&&(t.profileSync.userInfoWindowMs===r.profileSync.userInfoWindowMs&&t.profileSync.userInfoBatchSize===r.profileSync.userInfoBatchSize&&t.profileSync.groupNamecardWindowMs===r.profileSync.groupNamecardWindowMs&&t.profileSync.groupNamecardMaxConcurrency===r.profileSync.groupNamecardMaxConcurrency))))))))))))))))))}static normalizeServiceConfig(e){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??rb,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:e?.serverUrls}}static normalizeSyncDataTypes(e){const t=[];for(const r of e)t.includes(r)||t.push(r);return t}static isSameStringArray(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}static isSameServiceConfig(t,r){if(t.mode!==r.mode)return!1;if(t.dnsConfigUrls.length!==r.dnsConfigUrls.length)return!1;for(let e=0;e<t.dnsConfigUrls.length;e+=1)if(t.dnsConfigUrls[e]!==r.dnsConfigUrls[e])return!1;return e.isSameServerUrls(t.serverUrls,r.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl&&e.syncRestApiUrl===t.syncRestApiUrl&&e.syncWsUrl===t.syncWsUrl)}};Zb.instance=null;let Qb=Zb;const Yb=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Xb=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw(e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}))(t);return e.trim()},eI=e=>`mark_${String(e)}`,tI=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw Yb(t,`${t} must be one of singleChat, groupChat, chatRoom`)},rI=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",sI=e=>"string"==typeof e&&e.length>0?e:void 0,nI=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}},oI=e=>_l(e)?e:void 0,iI=(e,t)=>{const r=oI(e);if(!r)return;const s=(e=>"string"==typeof e?Rl(e,{}):oI(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],o=oI(n[0])??oI(s.body),i=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(o?.type??s.type);if(!o||!i)return;const a=((e,t)=>{if("text"===e)return{content:sI(t.msg)??sI(t.content)??""};if("custom"===e){const e=oI(t.customExts)??oI(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:sI(t.customEvent)??sI(t.event)??"",params:r}}if("cmd"===e)return{action:sI(t.action)??""};if("image"===e){const e=sI(t.url)??sI(t.remotePath)??"";return{localUrl:"",filename:sI(t.filename)??sI(t.displayName),filetype:sI(t.filetype)??"application/octet-stream",width:nI(t.width),height:nI(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:sI(t.bigImageUrl),thumbnailUrl:sI(t.thumbnailUrl)??sI(t.thumbnailRemotePath),secret:sI(t.secret)??sI(t.secretKey),fileLength:nI(t.fileLength)}}return"file"===e?{url:sI(t.url)??sI(t.remotePath),filename:sI(t.filename)??sI(t.displayName),filetype:sI(t.filetype)??"application/octet-stream",fileSize:nI(t.fileSize),fileLength:nI(t.fileLength),secret:sI(t.secret)??sI(t.secretKey)}:"voice"===e?{url:sI(t.url)??sI(t.remotePath),filename:sI(t.filename)??sI(t.displayName),filetype:sI(t.filetype)??"application/octet-stream",duration:nI(t.duration)??0,fileLength:nI(t.fileLength),secret:sI(t.secret)??sI(t.secretKey)}:"video"===e?{url:sI(t.url)??sI(t.remotePath),filename:sI(t.filename)??sI(t.displayName),filetype:sI(t.filetype)??"application/octet-stream",duration:nI(t.duration)??0,width:nI(t.width),height:nI(t.height),fileLength:nI(t.fileLength),secret:sI(t.secret)??sI(t.secretKey),thumbnailUrl:sI(t.thumbnailUrl)??sI(t.thumbnailRemotePath)}:"location"===e?{latitude:nI(t.latitude)??0,longitude:nI(t.longitude)??0,address:sI(t.address),buildingName:sI(t.buildingName)}:null})(i,o);if(!a)return;const c=sI(s.from)??sI(r.from)??"",d=sI(s.to)??t.conversationId,u=oI(s.sender),l={userId:sI(u?.userId)??c,nickname:sI(u?.nickname),avatarUrl:sI(u?.avatarUrl)},h=oI(s.ext)??{},p=(e=>{const t=oI(e);if(!t)return;const r=sI(t.operatorId)??sI(t.operator),s=nI(t.operationCount)??nI(t.count),n=nI(t.operationTime)??nI(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??oI(s.meta)?.edit_msg);return{msgServerId:sI(r.id)??t.messageId,msgLocalId:sI(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:i,sendStatus:"sent",ext:h,timestamp:nI(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},aI=e=>`${e.conversationType}:${e.conversationId}`,cI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},dI=async(e,t,r,s)=>{const n=cI(t),o=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw Yb("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!_l(e))throw Yb(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:Xb(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:tI(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:Xb(t.conversationId,"params.conversationId"),conversationType:tI(t.conversationType,"params.conversationType")}]})(r),i=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw Yb(t,`${t} must be an integer between 0 and 19`);return e})(r.mark,"params.mark"),a=await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channels/mark?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{mark:eI(i),targets:o.map(e=>({to:e.conversationId,type:rI(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!_l(e))return;const r="string"==typeof e.to?e.to.trim():"",s=(e=>"chat"===e||"singleChat"===e?"singleChat":"groupchat"===e||"groupChat"===e?"groupChat":"chatroom"===e||"chatRoom"===e?"chatRoom":null)(e.type);r&&s&&t.add(aI({conversationId:r,conversationType:s}))}),t})((_l(a)&&_l(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of o){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(aI(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:i,operation:s?"addMark":"removeMark"}},uI=async(e,t,r,s)=>{const n=cI(t),o=Xb(r.conversationId,"params.conversationId"),i=tI(r.conversationType,"params.conversationType"),a=Xb(r.messageId,"params.messageId");return await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channel/pin?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{to:o,type:rI(i),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:o,conversationType:i,messageId:a,operation:s?"pin":"unpin"}},lI=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],hI=(e,t)=>`${e}\0${t}`,pI=(e,t,r)=>{const s={userId:e};for(const n of lI){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},mI=e=>pI(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),fI=(e,t,r)=>{const s=new Map;if(!e?.getGroupNamecard||!r)return s;for(const n of t){const t=e.getGroupNamecard(n.groupId,n.user.userId,!1);t&&s.set(hI(n.groupId,n.user.userId),t.namecard)}return s},gI=async(e,t)=>{if(0===e.length||!t)return[];try{return await t({userIds:e})}catch(r){return To("Group user info hydration failed",{userIds:e,error:r}),[]}},yI=async(e,t)=>{t&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,r])=>{try{await t(e,r)}catch(s){To("Group namecard hydration failed",{groupId:e,userIds:r,error:s})}}))},vI=async e=>{const t=(e=>{const t=[],r=new Set;for(const s of e){const e=s.groupId.trim(),n=s.user.userId.trim();if(!e||!n)continue;const o=hI(e,n);r.has(o)||(r.add(o),t.push({groupId:e,user:{...s.user,userId:n}}))}return t})(e.contexts),r=(e=>{const t=[],r=new Set;for(const s of e)r.has(s.user.userId)||(r.add(s.user.userId),t.push(s.user.userId));return t})(t),s=((e,t)=>{const r=new Map;if(!e)return r;for(const n of t){const t=e.getRuntimeUserInfo?.(n,!1)??null;t&&r.set(n,t)}const s=t.filter(e=>!r.has(e));for(const n of e.getUserInfoSummaries?.(s,!1)??[])r.set(n.userId,mI(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),o=new Set(n),i=fI(e.cacheManager,t,e.includeNameCard),a=e.includeNameCard?((e,t,r)=>{const s=new Map;for(const n of e){const e=n.user.userId,o=hI(n.groupId,e);if(!t.has(e)||r.has(o))continue;const i=s.get(n.groupId)??[];i.includes(e)||i.push(e),s.set(n.groupId,i)}return s})(t,o,i):new Map,[c]=await Promise.all([gI(n,e.fetchUserInfos),yI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=fI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=hI(h.groupId,e),r=pI(e,h.user,d.get(e)??s.get(e)),n=u.get(t)??i.get(t);l.set(t,void 0!==n?{...r,nameCard:n}:r)}return{usersByContextKey:l,fetchedUserInfos:c,missingUserIds:n.filter(e=>!d.has(e))}},bI=async e=>{const t=await vI({...e,contexts:e.users.map(t=>({groupId:e.groupId,user:t}))}),r=new Map;for(const s of e.users){const n=s.userId.trim();if(!n||r.has(n))continue;const o=t.usersByContextKey.get(hI(e.groupId.trim(),n));o&&r.set(n,o)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},II=jv(["singleChat","groupChat","chatRoom"]),wI=Fv(Dv()).refine(e=>(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e),"ext must be an object").refine(e=>(e=>{try{return JSON.stringify(e),!0}catch{return!1}})(e),"ext must be JSON serializable"),CI=Gv({path:xv().min(1,"data.path is required"),size:Lv().optional(),name:xv().optional(),type:xv().optional()}),SI=Gv({uri:xv().min(1,"data.uri is required"),size:Lv().optional(),name:xv().optional(),type:xv().optional()}),TI=Bv(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>kv(t=>t instanceof e,t))(File):$v(),CI,SI]),_I=Gv({conversationId:xv().min(1,"conversationId is required"),conversationType:II,ext:wI.optional(),timestamp:Lv().int().positive("timestamp must be a positive integer").optional(),receiverList:qv(xv().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:Pv().optional(),webhookEnv:xv().optional(),priority:jv(["high","normal","low"]).optional(),needReadReceipt:Pv().optional(),isChatThread:Pv().optional()}),RI=Gv({type:xv().min(1,"messageList.type is required"),sender:Gv({userId:xv().min(1,"messageList.sender.userId is required"),nickname:xv().optional(),avatarUrl:xv().optional()}),conversationId:xv().min(1,"messageList.conversationId is required"),conversationType:II,timestamp:Lv().int().positive("messageList.timestamp must be positive"),body:Fv(Dv()),combineLevel:Lv().int().min(0).max(10).optional()}).passthrough(),AI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:sy.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:sy.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:sy.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),MI=AI(_I.extend({content:xv().min(1,"content is required"),targetLanguages:qv(xv().min(1)).optional()})),EI=AI(_I.extend({originalUrl:xv().min(1,"originalUrl is required").optional(),filename:xv().min(1,"filename is required").optional(),filetype:xv().min(1,"filetype is required").optional(),width:Lv().positive("width must be positive").optional(),height:Lv().positive("height must be positive").optional(),isGif:Pv().optional(),isOriginalImage:Pv().optional(),fileLength:Lv().positive("fileLength must be positive").optional(),data:TI.optional(),thumbnailUrl:xv().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),UI=AI(_I.extend({originalUrl:xv().min(1,"originalUrl is required").optional(),filename:xv().min(1,"filename is required").optional(),filetype:xv().min(1,"filetype is required").optional(),fileSize:Lv().positive("fileSize must be positive").optional(),fileLength:Lv().positive("fileLength must be positive").optional(),data:TI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),kI=AI(_I.extend({originalUrl:xv().min(1,"originalUrl is required").optional(),filename:xv().min(1,"filename is required").optional(),filetype:xv().min(1,"filetype is required").optional(),duration:Lv().positive("duration must be positive"),fileLength:Lv().positive("fileLength must be positive").optional(),data:TI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),NI=AI(_I.extend({originalUrl:xv().min(1,"originalUrl is required").optional(),filename:xv().min(1,"filename is required").optional(),filetype:xv().min(1,"filetype is required").optional(),duration:Lv().positive("duration must be positive"),width:Lv().positive("width must be positive").optional(),height:Lv().positive("height must be positive").optional(),fileLength:Lv().positive("fileLength must be positive").optional(),thumbnailUrl:xv().min(1).optional(),data:TI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),OI=AI(_I.extend({latitude:Lv(),longitude:Lv(),address:xv().min(1).optional(),buildingName:xv().min(1).optional()})),xI=AI(_I.extend({action:xv().min(1,"action is required")})),LI=AI(_I.extend({event:xv().min(1,"event is required"),params:Fv(xv()).optional()})),PI=AI(_I.extend({title:xv().min(1,"title is required"),summary:xv().min(1,"summary is required"),compatibleText:xv().min(1).optional(),messageList:qv(RI).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),DI=e=>{const t=e?.userId?.trim();if(!t)throw new Zr("sender.userId is required",{code:nt,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:t,nickname:e?.nickname,avatarUrl:e?.avatarUrl}},$I=()=>Wp(),qI=(e,t)=>{if(e)return e;if(!t)throw new Zr("url or data is required",{code:nt,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const r=Vp(t);if(!r)throw new Zr("Failed to resolve local url",{code:ot,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return r},GI=e=>!!e.isGif||(e.isOriginalImage??!1),BI=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??Wp(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:r,sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:s,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}),FI=(e,t)=>{const r=zv.validateOrThrow(PI,e),s=r.messageList,n=DI(t);pm(s);const o=mm(s);fm(o);const i={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:o},a=BI(r,n,"combine",i);return((e,t)=>{t&&uh.set(e,t)})(a,r.compatibleText),a},jI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},zI=e=>{if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s+=1)r[s]=t.charCodeAt(s);return r},KI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),HI=async e=>{try{return await e()}catch(t){if(!(t instanceof ts))throw t;const e=(e=>{const t="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case $t:case Ar:return"Translation service is not enabled";case Rr:return t?.includes("too long")?"Translation text is too long":t?.includes("target language")?"Invalid target language":"Invalid translation request";case Mr:return"Translation quota has been reached";case Er:return"Translation service error";default:return}})(t);if(!e)throw t;throw new ts(`REST business error: ${e}`,{code:t.code,details:t.details})}},VI=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",WI=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},JI=e=>({userId:e}),ZI=(e,t)=>{if(!KI(e)||!KI(e.data))throw Hg({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},QI=(e,t)=>{if(!KI(e)||!Array.isArray(e.data))throw Hg({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},YI=(e,t)=>Array.isArray(e)?e:QI(e,t),XI={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},ew={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},tw={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},rw=(e,t,r)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:n}=Qn(e.appKey),o=t.indexOf("/chatfiles/"),i=o>=0?t.slice(o):t,a=`${e.restBaseUrl}/${s}/${n}${i}`;return ro(a,r)},sw=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e))return e;const t=Object.values(e),r=[];for(const s of t)Array.isArray(s)&&r.push(...s);return r.length>0?r:void 0},nw=(e,t,r)=>{const s=VI(r.contentType??r.type),n=ew[s];if(!n)return null;const o=KI(r.content)?r.content:{},i=((e,t)=>{const r=VI(t.conversationType);if("groupchat"===r||"chatroom"===r)return VI(t.receiverId);const s=VI(t.senderId);return s===e?VI(t.receiverId):s})(t,r),a=tw[VI(r.conversationType)]??"singleChat",c={msgServerId:VI(r.messageId),msgLocalId:VI(r.messageId),from:VI(r.senderId),to:VI(r.receiverId),conversationId:i,conversationType:a,type:n,ext:KI(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(VI(r.sentTime)).getTime(),sender:{userId:VI(r.senderId)},highlight:sw(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=VI(o.remotePath??o.url),l=VI(o.secret??o.secretKey);switch(n){case"txt":d={type:"txt",content:VI(o.message??r.text)};break;case"img":{const t=rw(e,u,l);d={type:"img",url:t,thumb:o.thumb?rw(e,VI(o.thumb),VI(o.thumb_secret??o.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(o.width??(KI(o.size)?o.size.width:0))||0,height:Number(o.height??(KI(o.size)?o.size.height:0))||0,fileLength:Number(o.file_length??o.fileLength??0)};break}case"video":d={type:"video",url:rw(e,u,l),thumb:o.thumb||o.thumbnailRemotePath?rw(e,VI(o.thumb??o.thumbnailRemotePath),VI(o.thumb_secret??o.thumbnailSecretKey)):"",secret:l,filename:VI(o.filename??o.displayName),duration:Number(o.length??o.duration??0),fileLength:Number(o.file_length??o.fileLength??0)};break;case"file":d={type:"file",url:rw(e,u,l),secret:l,filename:VI(o.filename??o.displayName),fileLength:Number(o.file_length??o.fileLength??0)};break;case"loc":d={type:"loc",latitude:Number(o.lat??o.latitude??0),longitude:Number(o.lng??o.longitude??0),address:VI(o.addr??o.address),buildingName:VI(o.buildingName)};break;case"custom":d={type:"custom",customEvent:VI(o.customEvent),customExts:KI(o.customExts)?o.customExts:{}};break;default:return null}return{...c,body:d}},ow=async(e,t,r)=>{const s=`${jI(t)}/users/${t.userId}/messages/search/get`,n=((e,t)=>{const{option:r,pageNum:s=1,pageSize:n=20}=e,o=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),i={searchMode:"default",highlightEnable:!0,page:s,size:n};return 1===o.length?i.keyword=o[0]:(i.keywords=o,i.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?i.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?i.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(i.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(i.contentType=r.msgTypes.map(e=>XI[e]??e).join(",")),void 0!==r.startTime&&(i.startTime=r.startTime),void 0!==r.endTime&&(i.endTime=r.endTime),r.searchScope&&(i.searchExt=r.searchScope),r.direction&&(i.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:i}})(r,t.userId),o=await e.post(s,n,{operation:"searchMessages"}),i=KI(o)?o:{},a=KI(i.data)?i.data:i,c=KI(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=KI(c.pagination)?c.pagination:c,l=Number(u.pageNum??u.page??r.pageNum??1),h=Number(u.pageSize??u.size??r.pageSize??20),p=Number(u.totalPages??0),m=1===u.isFinished||l>=p,f=[];for(const g of d){if(!KI(g))continue;const e=nw(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:h,totalPages:p,isLast:m}},iw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/api/sdk/v1/${t}/${r}`},aw=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),cw=e=>aw(e)&&"string"==typeof e.path&&e.path.trim().length>0,dw=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||cw(e),uw=e=>{if(!aw(e))return;return{data:aw(e.data)?e.data:void 0,error:aw(e.error)?e.error:void 0}},lw=(e,t)=>{const r=uw(e),s=r?.data?.text;if("string"!=typeof s)throw new Hr(`${t} response data is invalid`,fr,{details:{api:t,response:e}});return s},hw=(e,t,r,s="sdk")=>"auth"===s?new Jr(e,{code:t,details:r}):"validation"===s?new Zr(e,{code:t,details:r}):new Hr(e,t,{details:r}),pw=e=>!(void 0===e||aw(e)&&!Array.isArray(e))||(void 0!==e?.format&&"string"!=typeof e.format||(void 0!==e?.sampleRate&&"number"!=typeof e.sampleRate||(void 0!==e?.bitsPerSample&&"number"!=typeof e.bitsPerSample||void 0!==e?.channels&&"number"!=typeof e.channels))),mw=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},fw=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof Hr&&aw(e.details)?e.details:void 0,r=uw(t?.rawResponse??t?.response??e),s=t?.serverCode??r?.error?.code,n=t?.serverMessage??r?.error?.message;return{serviceCode:"string"==typeof s||"number"==typeof s?String(s):void 0,serviceMessage:"string"==typeof n?n:void 0}})(e);if(e instanceof rs)return hw("File upload failed",$r,{cause:e.details});if(e instanceof Hr&&!t)return e;if(t)switch(t){case"4041001":return hw("File not found",Or,{serviceCode:t,serviceMessage:r});case"4001002":return hw("Invalid file",Ur,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return hw("File upload failed",$r,{serviceCode:t,serviceMessage:r});case"4001003":return hw("Voice duration exceeds 60 seconds",kr,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return hw("Voice-to-text service is not enabled",$t,{serviceCode:t,serviceMessage:r});case"4031002":return hw("Beta service usage limit exceeded",Br,{serviceCode:t,serviceMessage:r});case"4001001":return"string"==typeof(s=r)&&s.toLowerCase().includes("uploaded file exceeds")?hw("File too large",xr,{serviceCode:t,serviceMessage:r}):hw(r||"Missing or invalid request parameter",nt,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return hw("Voice-to-text failed",Nr,{serviceCode:t,serviceMessage:r});case"4011001":return hw(r||"Unauthorized or invalid token",dt,{serviceCode:t,serviceMessage:r},"auth");default:return hw(r||(e instanceof Error?e.message:"Voice-to-text failed"),Nr,{serviceCode:t,serviceMessage:r})}var s;return e instanceof Hr?hw(e.message,e.code,e.details):hw(e instanceof Error?e.message:"Voice-to-text failed",Nr)},gw=(e,t)=>{if(!aw(r=e)||"string"!=typeof r.filename||"string"!=typeof r.filetype||"number"!=typeof r.duration||"type"in r&&void 0!==r.type&&"voice"!==r.type)throw hw("Invalid file",Ur,{path:"voiceMessageBody"},"validation");var r;if(pw(t))throw hw("Invalid file",Ur,{path:"voiceParams"},"validation");if(!e.url)throw hw("File not found",Or,{path:"voiceMessageBody.url"});if(!mw(e.url))throw hw("Invalid file",Ur,{path:"voiceMessageBody.url"},"validation");return e},yw=(e,t)=>{if(pw(t))throw hw("Invalid file",Ur,{path:"voiceParams"},"validation");if(!dw(e))throw hw("Invalid file",Ur,{path:"file"},"validation");return e},vw=async(e,t,r,s)=>{const n=gw(r,s),o=mw(n.url);if(!o)throw((e,t,r,s="invalid")=>new Zr(e,{code:t,details:{fields:[{path:r,message:e,rule:s}]}}))("File not found",Or,"voiceMessageBody.url");try{const r=await e.post(`${iw(t)}/speech/transcriptions`,{data:{fileId:o,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:lw(r,"voiceMessageToText")}}catch(i){throw fw(i)}},bw=Gv({keywordList:qv(xv()).min(1,"keywordList must not be empty").max(5,"keywordList must have at most 5 keywords").refine(e=>e.map(e=>e.trim()).filter(e=>e.length>0).length>0,"keywordList must contain at least one non-empty keyword"),keywordListMatchType:jv(["or","and"]).optional(),conversationId:xv().min(1).optional(),conversationType:jv(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:qv(jv(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Lv().optional(),endTime:Lv().optional(),searchScope:jv(["none","with","only"]).optional(),direction:jv(["up","down"]).optional()}).refine(e=>void 0!==e.conversationId===(void 0!==e.conversationType),{message:"conversationId and conversationType must be provided together"}).refine(e=>void 0!==e.startTime===(void 0!==e.endTime),{message:"startTime and endTime must be provided together"}).refine(e=>void 0===e.startTime||void 0===e.endTime||e.endTime>=e.startTime,{message:"endTime must be >= startTime"}),Iw=Gv({option:bw,pageNum:Lv().int().min(1).default(1),pageSize:Lv().int().min(1).max(100).default(20)}),ww=Rb(Ab,{common:{},apis:{sendMessage:{range:"1,4,100,108,110,202,210,213-215,219-222,300-301,303,305,402,405-406,500-501,505-510,602-603,606-607,1200,1299",localErrors:{sendMessage:{operation_cancelled:{code:1,retryable:!1},upload_invalid_appkey:{code:100,retryable:!1},validation_invalid:{code:110,retryable:!1},not_connected:{code:300,retryable:!0},request_timeout:{code:301,retryable:!0},send_failed:{code:303,retryable:!1},upload_failed:{code:402,retryable:!0},file_too_large:{code:405,retryable:!1},file_content_improper:{code:406,retryable:!1},encode_failed:{code:500,retryable:!1}}},errors:{SERVICE_LIMIT_EXCEEDED:{code:4,retryable:!1},TOKEN_EXPIRED:{code:108,retryable:!1},AUTH_FAILED:{code:202,retryable:!1},PERMISSION_DENIED:{code:210,retryable:!1},BIND_ANOTHER_DEVICE:{code:213,retryable:!1},TOO_MANY_DEVICES:{code:214,retryable:!1},USER_MUTED:{code:215,retryable:!1},USER_MUTED_BY_ADMIN:{code:219,retryable:!1},USER_DEVICE_CHANGED:{code:220,retryable:!1},USER_NOT_ON_ROSTER:{code:221,retryable:!1},BLOCKED_BY_RECIPIENT:{code:222,retryable:!1,aliases:["blocked"]},SERVER_SERVING_DISABLED:{code:305,retryable:!1},MESSAGE_INCLUDE_ILLEGAL_CONTENT:{code:501,retryable:!1},SERVICE_NOT_ENABLED:{code:505,retryable:!1},MESSAGE_EXPIRED:{code:506,retryable:!1},MESSAGE_ILLEGAL_WHITELIST:{code:507,retryable:!1},MESSAGE_EXTERNAL_LOGIC_BLOCKED:{code:508,retryable:!1},MESSAGE_CURRENT_LIMITING:{code:509,retryable:!0},MESSAGE_SIZE_LIMIT:{code:510,retryable:!1},GROUP_NOT_JOINED:{code:602,retryable:!1},GROUP_PERMISSION_DENIED:{code:603,retryable:!1},GROUP_NOT_EXIST:{code:606,retryable:!1},GROUP_DISABLED:{code:607,retryable:!1},MESSAGE_BLOCKED:{code:1200,retryable:!1},THIRD_DEFAULT_FAILED:{code:1299,retryable:!1}}},getHistoryMessages:{range:"4,110,202,505",localErrors:{getHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},page_size_exceeded:{code:110,aliases:["pull number cannot be greater","limit is to large"],retryable:!1}}},removeHistoryMessages:{range:"110,112,202,505",localErrors:{removeHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},query_param_reaches_limit:{code:112,aliases:["delete msg list limit"],retryable:!1}}},getGroupMessageReadUsers:{range:"4,110,500",localErrors:{getGroupMessageReadUsers:{validation_invalid:{code:110,retryable:!1}}},errors:{message_not_found:{code:500,retryable:!1}}},recallMessage:{range:"110,201,300,504,505",localErrors:{recallMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},recall_time_limit:{code:504,retryable:!1},recall_disabled:{code:505,retryable:!1}}},updateMessage:{range:"110,111,201,210,300,511",localErrors:{modifyMessage:{validation_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1},not_login:{code:201,retryable:!0},permission_denied:{code:210,retryable:!1},not_connected:{code:300,retryable:!0},edit_failed:{code:511,retryable:!0}}},downloadMessageAttachment:{range:"400,401,403,407",localErrors:{downloadAttachment:{validation_invalid:{code:401,retryable:!1}}},errors:{not_found:{code:400,httpStatus:404,retryable:!1},invalid:{code:401,retryable:!1},download_failed:{code:403,retryable:!0},expired:{code:407,httpStatus:404,retryable:!1}}},downloadAndParseCombineMessage:{range:"110,401,403,500",localErrors:{downloadAndParseCombineMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_param:{code:110,retryable:!1},invalid_type:{code:500,retryable:!1},parse_failed:{code:401,retryable:!0},download_failed:{code:403,retryable:!0}}},addReaction:{range:"110,302,505,600,602,1300-1302",localErrors:{addReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{reaction_already_operated:{code:1301,retryable:!1},reaction_reach_limit:{code:1300,retryable:!1},group_not_joined:{code:602,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1},service_not_enabled:{code:505,retryable:!1},server_busy:{code:302,retryable:!0}}},removeReaction:{range:"110,505,1301,1302",localErrors:{removeReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},getReactionList:{range:"110,505,600",localErrors:{getReactionList:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},group_invalid_id:{code:600,retryable:!1}}},getReactionDetail:{range:"110,505,1302",localErrors:{getReactionDetail:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},pinMessage:{range:"4,110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_limit:{code:4,aliases:["91101"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102"],retryable:!1}}},unpinMessage:{range:"110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getPinnedMessageList:{range:"110,111",errors:{operation_unsupported:{code:111,aliases:["15002"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getSupportedTranslationLanguages:{range:"505",errors:{service_not_enabled:{code:505,aliases:["service not open!"],retryable:!1}}},translateMessage:{range:"505,1110-1113",localErrors:{translateMessage:{validation_invalid:{code:1110,retryable:!1}}},errors:{translate_text_too_long:{code:1110,runtimeMessage:"Translation text is too long",retryable:!1},translate_param_invalid:{code:1110,runtimeMessage:"Invalid target language",retryable:!1},service_not_enabled:{code:1111,runtimeMessage:"Translation service is not enabled",aliases:["service not open!"],retryable:!1},translate_usage_limit:{code:1112,runtimeMessage:"Translation quota has been reached",aliases:["The request has reached the maximum limit"],retryable:!1},translate_failed:{code:1113,runtimeMessage:"Translation service error",aliases:["The request failed, please try again later."],retryable:!1}}},voiceMessageToText:{range:"4,110,202,407-411,505",localErrors:{voiceMessageToText:{validation_invalid:{code:407,retryable:!1},file_not_found:{code:410,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},file_not_found:{code:410,retryable:!1,aliases:["4041001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},voiceFileToText:{range:"4,110,202,402,407-411,505",localErrors:{voiceFileToText:{validation_invalid:{code:407,retryable:!1},upload_required:{code:110,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},upload_failed:{code:402,retryable:!0,aliases:["5021001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},getConversationList:{range:"110",localErrors:{getConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPinnedConversationList:{range:"110",localErrors:{getPinnedConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getConversationListByMark:{range:"110",localErrors:{getConversationListByMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},deleteConversation:{range:"110",localErrors:{deleteConversation:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearConversationUnreadMessageCount:{range:"110,201,300,500",localErrors:{clearConversationUnreadMessageCount:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},clearAllConversationUnreadMessageCount:{range:"201,300,500",errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},sendMessageReadReceipts:{range:"110,300",localErrors:{sendMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_direction:{code:110,retryable:!1},not_connected:{code:300,retryable:!0}}},getGroupMessageReadReceipts:{range:"110,202,210,303",localErrors:{getGroupMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},auth_bad_access_token:{code:202,httpStatus:401,retryable:!1},forbidden_op:{code:210,httpStatus:403,retryable:!1},unknown_exception_error:{code:303,httpStatus:500,retryable:!0}}},setConversationPinned:{range:"110",localErrors:{setConversationPinned:{validation_invalid:{code:110,retryable:!1}}},errors:{}},addConversationMark:{range:"110",localErrors:{addConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},removeConversationMark:{range:"110",localErrors:{removeConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearAllMessagesAndConversations:{range:"",errors:{}},searchMessages:{range:"110,202,303,505",localErrors:{searchMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{parameter_error:{code:110,httpStatus:400,retryable:!1,aliases:["4000005","4000006"]},token_invalid:{code:202,httpStatus:401,retryable:!1,aliases:["4010101"]},service_not_enabled:{code:505,httpStatus:403,retryable:!1,aliases:["4030204"]},app_not_found:{code:110,httpStatus:404,retryable:!1,aliases:["4040302"]},server_error:{code:303,httpStatus:500,retryable:!0,aliases:["5000701","5020801"]}}}}}),Cw=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}async sendMessage(e,t){return this.getClientOrThrow().sendMessage(e,t)}createTextMessage(e){return((e,t)=>{const r=zv.validateOrThrow(MI,e),s=DI(t),n=$I(),o={content:r.content};return r.targetLanguages&&(o.targetLanguages=r.targetLanguages),BI(r,s,"text",o,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=zv.validateOrThrow(EI,e),n=DI(t),o=$I(),i=s.data?qI(void 0,s.data):"",a=s.originalUrl?no(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&Hp.set(o,s.data);const c=s.isGif??!1,d={localUrl:i,filename:s.filename,filetype:s.filetype,width:s.width,height:s.height,isGif:c,isOriginalImage:GI({isGif:c,isOriginalImage:s.isOriginalImage})};return a?.originalImageUrl&&(d.originalImageUrl=a.originalImageUrl,d.bigImageUrl=a.bigImageUrl,d.thumbnailUrl=a.thumbnailUrl),void 0!==s.fileLength&&(d.fileLength=s.fileLength),s.thumbnailUrl&&(d.thumbnailUrl=s.thumbnailUrl),BI(s,n,"image",d,o)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=zv.validateOrThrow(UI,e),s=DI(t),n=$I(),o=qI(r.originalUrl,r.data);r.data&&Hp.set(n,r.data);const i={url:o,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(i.fileSize=r.fileSize),void 0!==r.fileLength&&(i.fileLength=r.fileLength),BI(r,s,"file",i,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=zv.validateOrThrow(kI,e),s=DI(t),n=$I(),o=qI(r.originalUrl,r.data);r.data&&Hp.set(n,r.data);const i={url:o,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(i.fileLength=r.fileLength),BI(r,s,"voice",i,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=zv.validateOrThrow(NI,e),s=DI(t),n=$I(),o=qI(r.originalUrl,r.data);r.data&&Hp.set(n,r.data);const i={url:o,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(i.width=r.width),void 0!==r.height&&(i.height=r.height),void 0!==r.fileLength&&(i.fileLength=r.fileLength),r.thumbnailUrl&&(i.thumbnailUrl=r.thumbnailUrl),BI(r,s,"video",i,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=zv.validateOrThrow(OI,e),s=DI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),BI(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=zv.validateOrThrow(xI,e),s=DI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),BI(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=zv.validateOrThrow(LI,e),s=DI(t),n={event:r.event};return r.params&&(n.params=r.params),BI(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return FI(e,this.buildMessageSenderOrThrow())}getConversationList(e){if(void 0!==e?.mark&&(!Number.isInteger(e.mark)||e.mark<0||e.mark>19))throw new Zr("filter.mark must be an integer between 0 and 19",{code:ot,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const t=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(t=>null!==t.lastMessage&&((void 0===e?.isPinned||t.isPinned===e.isPinned)&&!(void 0!==e?.mark&&!((e,t)=>e.marks.includes(t))(t,e.mark)))).map(Eg);return this.getClientOrThrow().markConversationAccess(t.map(e=>({conversationId:e.conversationId,type:e.conversationType}))),t}setCurrentConversation(e){this.validateConversationLocator(e),this.getClientOrThrow().getCacheManager()?.setCurrentConversation({conversationId:e.conversationId,type:e.conversationType})}resetCurrentConversation(){this.getClientOrThrow().getCacheManager()?.resetCurrentConversation()}getCurrentConversation(){const e=this.getClientOrThrow().getCacheManager()?.getCurrentConversation()??null;return e?{conversationId:e.conversationId,conversationType:e.type}:null}refreshSessionList(e){return this.getClientOrThrow().refreshSessionList(e)}async deleteConversation(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=cI(t),n=Xb(r.conversationId,"params.conversationId"),o=tI(r.conversationType,"params.conversationType"),i=r.deleteRoamingMessages??!1;if("boolean"!=typeof i)throw Yb("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${s.orgName}/${s.appName}/user/${s.encodedUserId}/user_channel?resource=${s.encodedResource}`,{method:"DELETE",body:{channel:n,type:"groupChat"===o?"groupChat":rI(o),delete_roam:i},operation:"deleteConversation"}),{conversationId:n,conversationType:o,operation:"delete"}})(this.getRestClient(t),t,e),s=this.getClientOrThrow(),n=s.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return n?.changed&&s.emitConversationListUpdate("local"),r}async setConversationPinned(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=cI(t),n=Xb(r.conversationId,"params.conversationId"),o=tI(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw Yb("params.pinned","params.pinned must be a boolean");const i="groupChat"===o?"groupChat":rI(o),a=r.pinned?await e.post(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?resource=${s.encodedResource}`,{type:i,to:n},{operation:"setConversationPinned"}):await e.delete(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?type=${encodeURIComponent(i)}&to=${encodeURIComponent(n)}&resource=${s.encodedResource}`,{operation:"setConversationPinned"}),c=_l(a)&&_l(a.data)?a.data:{};return{conversationId:n,conversationType:o,operation:"setPinned",isPinned:"boolean"==typeof c.is_top?c.is_top:r.pinned,pinnedTime:"number"==typeof c.update_top_status_time?c.update_top_status_time:r.pinned?Date.now():0}})(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationPinnedMutation({conversationId:r.conversationId,type:r.conversationType,isPinned:r.isPinned??e.pinned,pinnedTime:r.pinnedTime});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>dI(e,t,r,!0))(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async removeConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>dI(e,t,r,!1))(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async clearAllMessagesAndConversations(){const e=this.getRestContextOrThrow();await(async(e,t)=>{const r=cI(t);await e.post(`/${r.orgName}/${r.appName}/sdk/message/roaming/user/${r.encodedUserId}/delete/all?resource=${r.encodedResource}`,void 0,{operation:"clearAllMessagesAndConversations"})})(this.getRestClient(e),e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversations();r?.changed&&t.emitConversationListUpdate("local")}async pinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>uI(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>uI(e,t,r,!1))(this.getRestClient(t),t,e))}async getPinnedMessageList(e){const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=cI(t),n=Xb(r.conversationId,"params.conversationId"),o=tI(r.conversationType,"params.conversationType"),i=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(rI(o))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=_l(i)&&_l(i.data)?i.data:{};return{items:(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!_l(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:_l(r.message)&&"string"==typeof r.message.id?r.message.id:"";if(!s)return e;const i="number"==typeof r.pin_opt_at?r.pin_opt_at:0,a=iI(r.message,{messageId:s,conversationId:n,conversationType:o,currentUserId:t.userId,timestamp:i});return a?(e.push({messageId:s,conversationId:n,conversationType:o,operatorId:"string"==typeof r.pin_operator?r.pin_operator:void 0,pinnedAt:i,message:a}),e):e},[])}})(this.getRestClient(t),t,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(e){this.validateUnreadConversationLocator(e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:e.conversationId,type:e.conversationType});r?.changed&&t.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(s){if(!r?.matched)throw s;To("Conversation unread remote sync failed after local clear",{conversationId:e.conversationId,conversationType:e.conversationType,error:s})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(e){if(this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),"text"!==e.message.type&&"custom"!==e.message.type)throw new Zr("only text and custom messages are editable",{code:Ut});await this.requireConnectedClient().sendMessageAction({kind:"update",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,body:e.message.body,messageType:e.message.type,ext:e.message.ext},(e,t)=>this.buildActionError(e,t));const t=Date.now(),r=this.getCurrentUserIdOrThrow(),s={operatorId:r,operationCount:1,operationTime:t};return{msgServerId:e.messageId,msgLocalId:"",from:r,to:e.conversationId,sender:{userId:r},conversationId:e.conversationId,conversationType:e.conversationType,type:e.message.type,sendStatus:"sent",ext:e.message.ext,timestamp:t,body:e.message.body,direct:"SEND",modifiedInfo:s}}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=`${jI(t)}/users/${t.userId}/messageroaming`,o=await e.post(n,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),i=ZI(o,"getHistoryMessages"),a=Array.isArray(i.msgs)?i.msgs:[],c=[];for(const d of a){if(!KI(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(zI(d.msg));e&&c.push(e)}return{items:c,cursor:WI(i.next_key),hasMore:!0!==i.is_last&&c.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=zv.validateOrThrow(Iw,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>ow(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s="singleChat"===r.conversationType?"userId":"groupId",n="singleChat"===r.conversationType?"chat":"group",o=encodeURIComponent(t.clientResource),i=r.messageIds?`${jI(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${o}`:`${jI(t)}/sdk/message/roaming/${n}/user/${t.userId}/time?${s}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${o}`;await e.delete(i,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const s=tb();s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${jI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,o=await e.get(n,{operation:"getGroupMessageReadUsers"}),i=ZI(o,"getGroupMessageReadUsers"),a=KI(i.group_ack)?i.group_ack:i,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>KI(e)&&"string"==typeof e.username?{userId:e.username,user:JI(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof i.ackmid?i.ackmid:r.messageId,users:c,count:"number"==typeof a.total?a.total:c.length,cursor:WI(a.next_key),hasMore:!0!==a.is_last&&c.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${jI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return QI(n,"getGroupMessageReadReceipts").map(e=>KI(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${jI(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${jI(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(s,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=tb(),n="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");s.set("msgIdList",n),s.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&s.set("groupId",r.groupId);const o=await e.get(`${jI(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return QI(o,"getReactionList").map(e=>{if(!KI(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>KI(e)&&"string"==typeof e.reaction?{reaction:e.reaction,count:"number"==typeof e.count?e.count:0,isAddedBySelf:!0===e.state,userIds:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[]}:null).filter(e=>null!==e)}}).filter(e=>null!==e)})(this.getRestClient(t),t,e))}async getReactionDetail(e){if(this.validateReactionParams(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=tb();s.set("msgId",r.messageId),s.set("message",r.reaction),s.set("cursor",r.cursor??""),s.set("limit",String(r.pageSize??20));const n=await e.get(`${jI(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),o=ZI(n,"getReactionDetail"),i=Array.isArray(o.reactionUserList)?o.reactionUserList.map(e=>KI(e)&&"string"==typeof e.userId?{userId:e.userId,user:JI(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],a=Array.isArray(o.userList)?o.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:JI(e)})):[],c=i.length>0?i:a;return{reaction:"string"==typeof o.reaction?o.reaction:r.reaction,count:"number"==typeof o.count?o.count:c.length,isAddedBySelf:!0===o.state,reactionUsers:c,cursor:WI(o.cursor),hasMore:WI(o.cursor).length>0,createdAt:"string"==typeof o.createdAt?o.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await HI(()=>e.get(`${jI(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return YI(r,"getSupportedTranslationLanguages").map(e=>KI(e)&&"string"==typeof e.code?{code:e.code,name:"string"==typeof e.name?e.name:e.code,nativeName:"string"==typeof e.nativeName?e.nativeName:e.code}:null).filter(e=>null!==e)})(this.getRestClient(e),e))}async translateMessage(e){if("text"!==e.message.type)throw new Zr("only text messages can be translated",{code:Rr,details:{fields:[{path:"message.type",message:"must be text",rule:"message_type"}]}});const t=e.message.body.content.trim();if(0===t.length)throw new Zr("message text is required",{code:Rr,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(e.targetLanguages)||0===e.targetLanguages.length)throw new Zr("targetLanguages is required",{code:Rr,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(e.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new Zr("targetLanguages contains invalid language code",{code:Rr,details:{fields:[{path:"targetLanguages",message:"contains invalid language code",rule:"language_code"}]}});const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=await HI(()=>e.post(`${jI(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=YI(s,"translateMessage"),o=KI(n[0])?n[0]:null;if(!o)throw Hg({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const i=Array.isArray(o.translations)?o.translations:[],a=KI(o.detectedLanguage)?o.detectedLanguage:void 0;return{detectedLanguage:a&&"string"==typeof a.language?{language:a.language,score:"number"==typeof a.score?a.score:Number(a.score??0)}:void 0,translations:i.map(e=>KI(e)&&"string"==typeof e.text&&"string"==typeof e.to?{text:e.text,to:e.to}:null).filter(e=>null!==e)}})(this.getRestClient(r),r,{text:t,targetLanguages:e.targetLanguages}))}async voiceMessageToText(e,t){gw(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>vw(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){yw(e,t);const r=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new Hr("Upload capability is missing for current platform",Lr);return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=yw(r,s),o=Fn({file:n,fallbackName:cw(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${iw(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[ml]:pl()},source:o.source,fields:{username:t.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let n=r.body;try{n=JSON.parse(r.body)}catch{n=r.body}if(r.status<200||r.status>=300)throw new Hr("Voice-to-text failed",Nr,{details:{httpStatus:r.status,rawResponse:n}});return{text:lw(n,"voiceFileToText")}}catch(i){if(i instanceof Hr)throw fw(i);throw fw(Qu(i))}})(s,r,e,t))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(e){if("message"in e){if("combine"!==e.message.type)throw new Zr("message must be a combine message",{code:ot});const t=e.message.body;return{url:t.url??"",secret:t.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}return{url:e.url,secret:e.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(e,t){return e===ct||e===dt?new Jr(t??"authentication failed",{code:e}):e===gt||e===ft?new Wr(t??"connection unavailable",{code:e}):107===e||110===e||205===e||500===e||e===nt||e===ot?new Zr(t??"invalid parameter",{code:e}):e===Dt?new Hr(t??"message recall time limit reached",e):e===zt?new Hr(t??"message update failed",e):e===Ut?new Zr(t??"operation unsupported",{code:e}):new Hr(t??"message action failed",e)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(e,t){return new Zr(e,{code:ot,details:{fields:[{path:t,message:e,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("ChatManager is not bound to event context",{code:nt});return this.eventContext}getClientOrThrow(){if(!this.client)throw new Zr("ChatManager is not bound to client",{code:nt});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Zg(e.restBaseUrl,{errorMap:ww,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireConnectedClient(){const e=this.getClientOrThrow();if(e.getConnectionState()!==s)throw new Wr("client is not connected",{code:gt});return e}getCurrentUserIdOrThrow(){const e=this.getClientOrThrow().getCurrentUserId();if(!e)throw new Jr("user is not logged in",{code:ct});return e}buildMessageSenderOrThrow(){const e=this.getClientOrThrow(),t=this.getCurrentUserIdOrThrow(),r=e.getCacheManager()?.getUserInfoSummaries([t],!1)[0];return{userId:t,nickname:r?.nickname,avatarUrl:r?.avatarUrl}}async hydrateGroupMessageReadUsers(e,t){const r=this.getClientOrThrow();if(!r.isUserInfoSyncEnabled()||0===t.users.length)return t;const s=r.getCacheManager(),n=await bI({groupId:e,users:t.users.map(e=>e.user),includeNameCard:!0,cacheManager:s,fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoReadCapability(r);return t?await t.getUserInfoByUserId({userIds:e}):[]},hydrateGroupNamecards:async(e,t)=>{const s=this.getGroupNamecardHydrationCapability(r);s&&await s.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))}});return this.dispatchFetchedUserInfoUpdates(r,n.fetchedUserInfos),{...t,users:t.users.map(e=>{const t=n.usersById.get(e.userId)??e.user;return{...e,user:t}})}}getUserInfoReadCapability(e){const t=e.getManagerByCapability("userInfo:read");return t&&"function"==typeof t.getUserInfoByUserId?t:null}getGroupNamecardHydrationCapability(e){const t=e.getManagerByCapability("group:namecard");return t&&"function"==typeof t.hydrateMessageProfileGroupNamecards?t:null}dispatchFetchedUserInfoUpdates(e,t){if(0===t.length)return;const r=e.getCurrentUserId(),s=t.find(e=>e.userId===r),n=t.filter(e=>e.userId!==r);s&&e.dispatchOwnInfoUpdated(s),e.dispatchUserInfoUpdated(n),t.length>0&&e.refreshConversationDisplayFromUserInfos(t.map(e=>({userId:e.userId})),"profile")}async executeRestOperation(e){try{return await e()}catch(t){throw this.mapRestError(t)}}mapRestError(e){return e instanceof Zr||e instanceof Jr||e instanceof Wr||e instanceof Vr?e:e instanceof es?new Vr(e.message,{code:e.code,details:e.details}):e instanceof ts||e instanceof Hr?e:new Hr(String(e),Fr)}};Cw.key="chatManager";let Sw=Cw;class Tw{constructor(e,t){this.chatThreadId=e,this.manager=t}getInfo(){return this.manager.getChatThreadInfo({chatThreadId:this.chatThreadId})}refresh(){return this.getInfo()}join(){return this.manager.joinChatThread({chatThreadId:this.chatThreadId})}leave(){return this.manager.leaveChatThread({chatThreadId:this.chatThreadId})}destroy(){return this.manager.destroyChatThread({chatThreadId:this.chatThreadId})}updateName(e){return this.manager.updateChatThreadName({chatThreadId:this.chatThreadId,name:e.name})}getMemberList(e={}){return this.manager.getChatThreadMemberList({chatThreadId:this.chatThreadId,...e})}removeMember(e){return this.manager.removeChatThreadMember({chatThreadId:this.chatThreadId,memberId:e.memberId})}}const _w=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),Rw=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Aw=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw _w(t);return e.trim()},Mw=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw Rw(t,`${t} must be a string`);return e},Ew=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw Rw(t,`${t} must be an integer between 1 and 50`);return e},Uw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},kw=e=>_l(e)?e:null,Nw=e=>{const t=kw(e);return t?.data??e},Ow=e=>{const t=kw(e);if(Array.isArray(t?.entities))return t.entities;const r=Nw(e);if(Array.isArray(r))return r;const s=kw(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},xw=e=>{const t=kw(e),r=kw(t?.data),s=kw(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof s?.cursor?s.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},Lw=e=>{const t=kw(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const s="number"==typeof t.timestamp?t.timestamp:0,n=t.payload,o="string"==typeof n?Rl(n,{}):kw(n)??{},i=Array.isArray(o.bodies)?o.bodies:[],a=kw(i[0])??{};return{msgId:r,type:("string"==typeof a.type?a.type:void 0)??("string"==typeof o.type?o.type:void 0)??"",body:a,timestamp:s}},Pw=e=>{const t=kw(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0)??("string"==typeof t.chatThreadId?t.chatThreadId:void 0),s=("string"==typeof t.parentId?t.parentId:void 0)??("string"==typeof t.groupId?t.groupId:void 0)??("string"==typeof t.group_id?t.group_id:void 0),n="string"==typeof t.name?t.name:"";return r&&s&&n?{chatThreadId:r,parentId:s,name:n,ownerId:"string"==typeof t.owner?t.owner:void 0,memberCount:"number"==typeof t.affiliationsCount?t.affiliationsCount:"number"==typeof t.affiliations_count?t.affiliations_count:void 0,messageCount:"number"==typeof t.messageCount?t.messageCount:"number"==typeof t.message_count?t.message_count:void 0,createdAt:"number"==typeof t.created?t.created:"number"==typeof t.createTimestamp?t.createTimestamp:void 0,lastMessage:Lw(t.lastMessage??t.last_message)}:null},Dw=e=>({items:Ow(e).map(e=>Pw(e)).filter(e=>null!==e),cursor:xw(e)}),$w=async(e,t,r)=>{const s=Uw(t),n=Aw(r,"chatThreadId");return(e=>{const t=Nw(e),r=Array.isArray(t)?t[0]:t,s=Pw(r);if(!s)throw Rw("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},qw=async(e,t,r)=>{const s=Uw(t),n=Aw(r.chatThreadId,"params.chatThreadId"),o=Ew(r.pageSize,"params.pageSize"),i=Mw(r.cursor,"params.cursor"),a=tb({limit:String(o),cursor:i}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:Ow(d=c).map(e=>{if("string"==typeof e)return{memberId:e};const t=kw(e);if(!t)return null;const r=("string"==typeof t.memberId?t.memberId:void 0)??("string"==typeof t.user?t.user:void 0)??("string"==typeof t.username?t.username:void 0);return r?{memberId:r,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null}).filter(e=>null!==e),cursor:xw(d)};var d},Gw=async(e,t,r)=>{const s=Uw(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw _w("params.chatThreadIds");if(r.chatThreadIds.length>20)throw Rw("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>Aw(e,`params.chatThreadIds[${t}]`)),o=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:Ow(o).map(e=>{const t=kw(e);if(!t)return null;const r=("string"==typeof t.chatThreadId?t.chatThreadId:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0);return r?{chatThreadId:r,lastMessage:Lw(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},Bw=Rb(Ab,{common:{},apis:{createChatThread:{range:"4,110,201,210,301,303,606",localErrors:{createChatThread:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getJoinedChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getJoinedChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadInfo:{range:"110,201,210,301,303,606",localErrors:{getChatThreadInfo:{validation_invalid:{code:110,retryable:!1}},getInfo:{validation_invalid:{code:110,retryable:!1}},refresh:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},joinChatThread:{range:"4,110,201,210,301,303,606",localErrors:{joinChatThread:{validation_invalid:{code:110,retryable:!1}},join:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},leaveChatThread:{range:"110,201,210,301,303,606",localErrors:{leaveChatThread:{validation_invalid:{code:110,retryable:!1}},leave:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},destroyChatThread:{range:"110,201,210,301,303,606",localErrors:{destroyChatThread:{validation_invalid:{code:110,retryable:!1}},destroy:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},updateChatThreadName:{range:"110,201,210,301,303,606",localErrors:{updateChatThreadName:{validation_invalid:{code:110,retryable:!1}},updateName:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadMemberList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadMemberList:{validation_invalid:{code:110,retryable:!1}},getMemberList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},removeChatThreadMember:{range:"110,201,210,301,303,606",localErrors:{removeChatThreadMember:{validation_invalid:{code:110,retryable:!1}},removeMember:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadLastMessageList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadLastMessageList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}}}}),Fw=class{constructor(){this.capabilities=["rawNotify:chatThread"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.registry=new Map}bind(e,t){this.client=e,this.eventContext=t??null,this.registry.clear()}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}handleRawNotify(e){if("chatThread"!==e.type)return;const t=this.buildChatThreadPublicEvent(e.payload);t&&this.eventContext?.dispatch?.(t.eventName,t.payload)}getChatThread(e){const t=e.trim();if(0===t.length)throw new Zr("chatThreadId is required",{code:nt,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const r=this.registry.get(t);if(r)return r;const s=new Tw(t,this);return this.registry.set(t,s),s}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=Uw(t),n=Aw(r.parentId,"params.parentId"),o=Aw(r.name,"params.name"),i=Aw(r.messageId,"params.messageId"),a=await e.post(`/${s.orgName}/${s.appName}/thread?resource=${s.encodedResource}`,{name:o,msg_id:i,group_id:n,owner:t.userId},{operation:"createChatThread"}),c=kw(Nw(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw Rw("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:d}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=Uw(t),n=Aw(r.parentId,"params.parentId"),o=Ew(r.pageSize,"params.pageSize"),i=Mw(r.cursor,"params.cursor"),a=tb({limit:String(o),cursor:i}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return Dw(c)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const s=Uw(t),n=Ew(r.pageSize,"params.pageSize"),o=Mw(r.cursor,"params.cursor"),i=tb({limit:String(n),cursor:o}),a="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${s.encodedUserId}?${i.toString()}`:`/${s.orgName}/${s.appName}/threads/user/${s.encodedUserId}?${i.toString()}`,c=await e.get(a,{operation:"getJoinedChatThreadList"});return Dw(c)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return $w(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Uw(t),n=Aw(r,"chatThreadId");await e.post(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/user/${s.encodedUserId}/join?resource=${s.encodedResource}`,void 0,{operation:"joinChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async leaveChatThread(e){return this.runOperation("leaveChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Uw(t),n=Aw(r,"chatThreadId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/user/${s.encodedUserId}/quit?resource=${s.encodedResource}`,{operation:"leaveChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async destroyChatThread(e){return this.runOperation("destroyChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Uw(t),n=Aw(r,"chatThreadId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.encodedResource}`,{operation:"destroyChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async updateChatThreadName(e){return this.runOperation("updateChatThreadName",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Uw(t),n=Aw(r.chatThreadId,"params.chatThreadId"),o=Aw(r.name,"params.name");await e.put(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.encodedResource}`,{name:o},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return qw(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Uw(t),n=Aw(r.chatThreadId,"params.chatThreadId"),o=Aw(r.memberId,"params.memberId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users/${encodeURIComponent(o)}?resource=${s.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return Gw(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new Zr("ChatThreadManager is not bound to client",{code:nt,details:{fields:[{path:"chatThreadManager.client",message:"ChatThreadManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("ChatThreadManager is not bound to event context",{code:nt,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Zg(e.restBaseUrl,{errorMap:Bw,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}async runOperation(e,t){try{return await t()}catch(r){if(r instanceof Hr)throw r;const t=r instanceof Error?r.message:String(r);throw new Hr(`ChatThreadManager ${e} failed: ${t}`,Fr)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",s="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!s)return null;const n="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,o="string"==typeof t.name?t.name:void 0,i="number"==typeof t.message_count?t.message_count:void 0,a=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,c="number"==typeof t.timestamp?t.timestamp:0,d="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:s,name:o??"",messageId:n,messageCount:i,lastMessage:a};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:o,messageId:n,thread:u,timestamp:c}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:o,messageId:n,messageCount:i,lastMessage:a,thread:u,timestamp:c}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:s,operatorId:d,timestamp:c}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:s,operatorId:d,memberId:t.userIds?.[0],timestamp:c}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};Fw.key="chatThreadManager";let jw=Fw;class zw{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const Kw=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Hw=e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},Vw=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Ww=e=>({userId:e}),Jw=(e,t,r)=>{const s={userId:r};for(const n of Kw){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Zw=async(e,t)=>{const r=Hw(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const i of n)s.set(i.userId,Vw(i));const o=r.filter(e=>!s.has(e));if(o.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:o});for(const t of e)s.set(t.userId,t)}for(const i of r)s.has(i)||s.set(i,Ww(i));return s},Qw=e=>_l(e)?e:null,Yw=e=>"string"==typeof e?e:void 0,Xw=e=>{const t=Yw(e)?.trim();return t||void 0},eC=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}},tC=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},rC=e=>{const t=Qw(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},sC=e=>{const t=Qw(e);return t?Qw(t.data)?t.data:t:null},nC=(e,t)=>{const r=Qw(e),s=r&&Qw(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return eC(n[0])},oC=e=>Xw(e.chatRoomId)??Xw(e.chatroomid)??Xw(e.id)??"",iC=e=>Yw(e.name)??Yw(e.title)??Yw(e.groupname)??"",aC=e=>Ww(e),cC=(e,t)=>{const r=Qw(e);if(!r)return null;const s=oC(r);if(!s)return null;const n=t?.stripOwnerAppKeyPrefix?(e=>{if(!e)return;const t=e.indexOf("_");return t<0?e:e.slice(t+1)})(Xw(r.owner)):Xw(r.owner);return{chatRoomId:s,name:iC(r),owner:n?aC(n):void 0,memberCount:eC(r.memberCount)??eC(r.affiliations_count),disabled:tC(r.disabled)}},dC=(e,t)=>{const r=(e=>{const t=Qw(e);return t?eC(t.count):void 0})(e),s=rC(e).map(e=>cC(e,t)).filter(e=>null!==e),n=nC(e,"pagenum"),o=nC(e,"pagesize");return{items:s,pageNum:n,pageSize:o,total:r,hasMore:void 0!==r&&void 0!==n&&void 0!==o?n*o<r:void 0}},uC=(e,t)=>{const r=rC(e),s=Qw(r[0])??sC(e)??{},n=cC(s)??{chatRoomId:oC(s),name:iC(s)},o=((e,t)=>{if(!t)return;if(Xw(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const s of r){const e=Qw(s);if(e){if(Xw(e.owner)===t)return"owner";if(Xw(e.admin)===t)return"admin";if(Xw(e.member)===t)return"member"}}})(s,t),i=eC(s.muteExpireAt)??eC(s.mute_expire)??eC(s.expire),a=tC(s.inAllowlist)??tC(s.white)??tC(s.in_whitelist),c=tC(s.muted);return{...n,description:Yw(s.description),maxMembers:eC(s.maxMembers)??eC(s.maxusers)??eC(s.max_users),createdAt:eC(s.createdAt)??eC(s.created),ext:Yw(s.ext)??Yw(s.custom),announcement:Yw(s.announcement),permissionType:o,currentUserStatus:void 0!==a||void 0!==c||void 0!==i||void 0!==o?{inAllowlist:a,muted:c,muteExpireAt:i,permissionType:o}:void 0}},lC=e=>rC(e).map(e=>Xw(e)).filter(e=>Boolean(e)).map(e=>aC(e)),hC=(e,t)=>{const r=sC(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=Qw(r.errorKeys)??{},o={};for(const[i,a]of Object.entries(n))"string"==typeof a&&(o[i]={code:mC(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:o}},pC=e=>{const t=Qw(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],o=[];return s.forEach(e=>{const t=Qw(e),r=(e=>{const t=Qw(e);if(!t)return null;const r=Xw(t.user),s=Xw(t.chatRoomId)??Xw(t.chatroomid)??Xw(t.id),n=Yw(t.action),o=tC(t.result);return r&&s&&void 0!==n&&void 0!==o?{chatRoomId:s,user:aC(r),action:n,reason:Yw(t.reason),...o?{}:{reason:Yw(t.reason)??"failed"}}:null})(e);if(!r||!t)return;tC(t.result)?n.push(r):o.push(r)}),{succeeded:n,failed:o}},mC=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?Br:e.includes("is not part of you")?Ir:e.includes("is not Legal")||e.includes("is not exist")?nt:fr,fC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},gC=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),yC=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),vC=(e,t)=>`/${e.orgName}/${e.appName}${t}`,bC=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw yC(t,`${t} must be a string`);return e}},IC=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw yC(t,`${t} must be a number`);return e}},wC=(e,t)=>{const r=tb();"number"==typeof e?.pageNum&&r.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&r.set("pagesize",String(e.pageSize));const s=r.toString();return s?`?${s}`:""},CC=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw gC(t);return e.trim()},SC=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw gC(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw yC(`${t}[${n}]`,`${t}[${n}] must be a string`);const o=e.trim();o&&!s.has(o)&&(s.add(o),r.push(o))}),0===r.length)throw gC(t);return r},TC=(e,t)=>SC(e,t),_C=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o={},i=bC(r.name,"params.name"),a=bC(r.description,"params.description"),c=IC(r.maxMembers,"params.maxMembers");if(void 0!==i&&(o.groupname=i),void 0!==a&&(o.description=a),void 0!==c&&(o.maxusers=c),0===Object.keys(o).length)throw gC("params");const d=vC(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=sC(e)??{};return{nameUpdated:tC(t.groupname),descriptionUpdated:tC(t.description),maxMembersUpdated:tC(t.maxusers)}})(await e.put(d,o,{operation:"updateChatRoomInfo"}))},RC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=tb();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const r=t.toString();return r?`?${r}`:""})(r)}`);return(e=>{const t=[];for(const n of rC(e)){const e=Qw(n);if(!e)continue;const r=Xw(e.owner),s=Xw(e.admin),o=Xw(e.member),i=r??s??o;i&&t.push({user:aC(i),role:r?"owner":s?"admin":"member",joinedAt:eC(e.joinedAt)??eC(e.joined_time)})}const r=Qw(e),s=r?Xw(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(o,{operation:"getChatRoomMemberList"}))},AC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/chatrooms/${encodeURIComponent(n)}/admin`),i=await e.get(o,{operation:"getChatRoomAdminList"});return lC(i)},MC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=tb();o.set("version","v3"),"number"==typeof r.pageNum&&o.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&o.set("pagesize",String(r.pageSize));const i=vC(s,`/chatrooms/${encodeURIComponent(n)}/mute?${o.toString()}`);return(e=>{const t=rC(e);if(t.every(e=>"string"==typeof e))return lC(e).map(e=>({user:e}));const r=[];for(const s of t){const e=Qw(s);if(!e)continue;const t=Xw(e.user)??Xw(e.member)??Xw(e.owner)??Xw(e.admin);t&&r.push({user:aC(t),muteExpire:eC(e.muteExpire)??eC(e.expire)??eC(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(i,{operation:"getChatRoomMuteList"}))},EC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=sC(e)??{};return{muted:tC(t.muted)??tC(t.value)??Boolean(t.data),muteExpireAt:eC(t.muteExpireAt)??eC(t.expire)??eC(t.mute_expire)}})(await e.get(o,{operation:"isCurrentUserMutedInChatRoom"}))},UC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=wC(r),i=o?"&":"",a=vC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${i}${o.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return lC(c).map(e=>({user:e}))},kC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),i=await e.get(o,{operation:"getChatRoomAllowlist"});return lC(i).map(e=>({user:e}))},NC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=sC(e)??{};return tC(t.value)??tC(t.white)??!1})(await e.get(o,{operation:"checkIfInChatRoomAllowList"}))},OC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=sC(e)??{};return{announcement:Yw(t.announcement)??""}})(await e.get(o,{operation:"getChatRoomAnnouncement"}))},xC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=sC(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(o,{keys:r.keys?TC(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},LC=async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw yC(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw gC(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw yC(t,`${t} contains invalid key`);if("string"!=typeof r)throw yC(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:i=!0,isForced:a=!1}=r,c=a?"/forced":"",d=vC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:o,autoDelete:i?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return hC(u,n)},PC={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},DC=(e,t,r)=>new Zr(e,{code:"required"===r?nt:ot,details:{fields:[{path:t,message:e,rule:r}]}}),$C=(e,t)=>{if("string"!=typeof e)throw DC(`${t} must be a string`,t,"invalid_format");return e},qC=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw DC(`${t} must be a string, number, or boolean`,t,"invalid_format")},GC=(e,t="attribute")=>{const r=PC[e];if(!r)throw DC(`${t} is invalid`,t,"invalid_format");return r},BC=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw DC(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,o]of e.entries()){const e=$C(o,`${t}[${n}]`).trim();e&&(s.has(e)||(s.add(e),r.push(e)))}if(0===r.length)throw DC(`${t} is required`,t,"required");return r},FC=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw DC(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,o]of e.entries()){const e=$C(o,`${t}[${n}]`);if(!(e in PC))throw DC(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw DC(`${t} is required`,t,"required");return r},jC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/get`},zC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},KC=e=>({targets:BC(e)}),HC=e=>!!_l(e)&&("nickname"in e||"avatarurl"in e||"avatarUrl"in e||"mail"in e||"phone"in e||"gender"in e||"sign"in e||"birth"in e||"ext"in e),VC=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!_l(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},WC=(e,t)=>{const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r},JC=(e,t)=>{const r=(e=>{const t=new Map,r=_l(e)?e:null;if(r?.data&&_l(r.data))for(const[s,n]of Object.entries(r.data))HC(n)&&t.set(s,n);return VC(r?.entities,t),VC(r?.data&&_l(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=_l(e)?e:null;if(!r?.lastModified||!_l(r.lastModified))return t;for(const[s,n]of Object.entries(r.lastModified))"number"==typeof n&&t.set(s,n);return t})(e),n=[];for(const o of t){const e=r.get(o);e&&n.push({profile:WC(o,e),lastModified:s.get(o)})}return n},ZC=(e,t)=>JC(e,t).map(e=>e.profile),QC=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,$C(r,s)]):e.push([t,String(qC(r,s))]))},YC=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),XC={onChatRoomDestroyed:Se,onMembersJoined:Te,onMembersExited:_e,onRemovedFromChatRoom:Re,onMuteListAdded:Ae,onMuteListRemoved:Me,onAllowListAdded:Ee,onAllowListRemoved:Ue,onAllMemberMuteStateChanged:ke,onAdminAdded:Ne,onAdminRemoved:Oe,onOwnerChanged:xe,onAnnouncementChanged:Le,onChatRoomInfoChanged:Pe,onAttributesUpdate:De,onAttributesRemoved:$e},eS=Rb(Ab,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomInfo:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},destroyChatRoom:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},joinChatRoom:{range:"4,705,704,707",errors:{exceed_limit:{code:4,httpStatus:403,retryable:!1},members_full:{code:704,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"member list is full"},user_in_blocklist:{code:707,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"is in the blacklist"},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},leaveChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMemberList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addChatRoomMembers:{range:"110,204,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAdminList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAdmin:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomAdmin:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMuteList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteChatRoomMembers:{range:"110,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},isCurrentUserMutedInChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomBlocklist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},blockChatRoomMembers:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},unblockChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAllowlist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addUsersToChatRoomAllowlist:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeUsersFromChatRoomAllowlist:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},checkIfInChatRoomAllowList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAnnouncement:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomAnnouncement:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomSharedFileList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},deleteChatRoomSharedFile:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAttributes:{range:"110,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},setChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}}}}),tS=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=new Map}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){const r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{const r=XC[e];return r&&t?[[r,t]]:[]}));this.eventContext?.addEventHandler(e,r)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("chatroom"!==e.type)return;const t=e.payload,r=await this.buildIncomingEventPayload(t.eventName,t);if(!r)return;const s=XC[t.eventName];s&&this.eventContext?.dispatch?.(s,r)}async buildIncomingEventPayload(e,t){const r=t.payload,s=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(e){case"onChatRoomDestroyed":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName};case"onMembersJoined":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),s),ext:r.ext};case"onMembersExited":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),s)};case"onRemovedFromChatRoom":return{reason:r.reasonCode??0,chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,participant:this.pickEventUser(r.participantId,s)};case"onMuteListAdded":return{chatRoomId:r.chatRoomId,mutes:this.pickEventMuteEntries(r.userIds,r.muteExpire,s),muteExpire:r.muteExpire};case"onMuteListRemoved":return{chatRoomId:r.chatRoomId,mutes:this.pickEventUsers(r.userIds,s)};case"onAllowListAdded":case"onAllowListRemoved":return{chatRoomId:r.chatRoomId,allowlist:this.pickEventUsers(r.userIds,s)};case"onAllMemberMuteStateChanged":return{chatRoomId:r.chatRoomId,isMuted:Boolean(r.isMuted)};case"onAdminAdded":case"onAdminRemoved":return{chatRoomId:r.chatRoomId,admin:this.pickEventUser(r.adminId,s)};case"onOwnerChanged":return{chatRoomId:r.chatRoomId,newOwner:this.pickEventUser(r.newOwnerId,s),oldOwner:this.pickEventUser(r.oldOwnerId,s)};case"onAnnouncementChanged":return{chatRoomId:r.chatRoomId,announcement:r.announcement??""};case"onChatRoomInfoChanged":return{chatRoomId:r.chatRoomId,chatRoomInfo:await this.resolveChatRoomDetailForEvent(r)};case"onAttributesUpdate":return{chatRoomId:r.chatRoomId,attributes:r.attributes??{},from:this.pickEventUser(r.from,s)};case"onAttributesRemoved":return{chatRoomId:r.chatRoomId,keyList:r.keyList??[],from:this.pickEventUser(r.from,s)};default:return null}}async getChatRoomList(e={}){return this.runOperation("getChatRoomList",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r={})=>{const s=fC(t),n=vC(s,`/chatrooms${wC(r)}`),o=await e.get(n,{operation:"getChatRoomList"});return dC(o)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(e){this.requireClient();const t=e.trim();if(0===t.length)throw new Zr("chatRoomId is required",{code:nt,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const r=this.chatRoomRegistry.get(t);if(r)return r;const s=new zw(t,this);return this.chatRoomRegistry.set(t,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true`),i=await e.get(o,{operation:"getChatRoomInfo"});return uC(i,t.userId)})(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return _C(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=CC(e.chatRoomId,"params.chatRoomId"),s=this.normalizeOptionalString(e.ext,"params.ext"),n=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:s,leaveOtherRooms:n})).chatRoomInfo??{}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=CC(e.chatRoomId,"params.chatRoomId");await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await RC(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(r.items)}})}async removeMembers(e){return this.runOperation("removeMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=SC(r.userIds,"params.userIds"),i=vC(s,`/chatrooms/${encodeURIComponent(n)}/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{operation:"removeChatRoomMembers"});return pC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await AC(this.getRestClient(t),t,e);return this.hydrateUserInfos(r)})}async addAdmin(e){return this.runOperation("addAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=CC(r.userId,"params.userId"),i=vC(s,`/chatrooms/${encodeURIComponent(n)}/admin?resource=${s.encodedResource}`);await e.post(i,{newadmin:o},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=CC(r.userId,"params.userId"),i=vC(s,`/chatrooms/${encodeURIComponent(n)}/admin/${encodeURIComponent(o)}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await MC(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async muteMembers(e){return this.runOperation("muteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=SC(r.userIds,"params.userIds"),i=IC(r.duration,"params.duration"),a=vC(s,`/chatrooms/${encodeURIComponent(n)}/mute?resource=${s.encodedResource}`);await e.post(a,{usernames:o,mute_duration:i},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=SC(r.userIds,"params.userIds"),i=vC(s,`/chatrooms/${encodeURIComponent(n)}/mute/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.post(o,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=vC(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.delete(o,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return EC(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await UC(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async blockMembers(e){return this.runOperation("blockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=SC(r.userIds,"params.userIds"),i=1===o.length,a=vC(s,i?`/chatrooms/${encodeURIComponent(n)}/blocks/users/${encodeURIComponent(o[0]??"")}?resource=${s.encodedResource}`:`/chatrooms/${encodeURIComponent(n)}/blocks/users?resource=${s.encodedResource}`),c=await e.post(a,i?void 0:{usernames:o},{operation:"blockChatRoomMembers"});return pC(c)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async unblockMembers(e){return this.runOperation("unblockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=SC(r.userIds,"params.userIds"),i=vC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{operation:"unblockChatRoomMembers"});return pC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await kC(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async addUsersToAllowlist(e){return this.runOperation("addUsersToAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=SC(r.userIds,"params.userIds"),i=vC(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(i,{usernames:o},{operation:"addUsersToChatRoomAllowlist"});return pC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async removeUsersFromAllowlist(e){return this.runOperation("removeUsersFromAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=SC(r.userIds,"params.userIds"),i=vC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{operation:"removeUsersFromChatRoomAllowlist"});return pC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return NC(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return OC(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=bC(r.announcement,"params.announcement");if(void 0===o)throw gC("params.announcement");const i=vC(s,`/chatrooms/${encodeURIComponent(n)}/announcement?resource=${s.encodedResource}`);await e.post(i,{announcement:o},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return xC(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await LC(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async removeAttributes(e){return this.runOperation("removeAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=fC(t),n=CC(r.chatRoomId,"params.chatRoomId"),o=TC(r.keys,"params.keys"),{isForced:i=!1}=r,a=i?"/forced":"",c=vC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:o},operation:"removeChatRoomAttributes"});return hC(d,n)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw To(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`ChatRoomManager ${e} failed: ${t.message}`,Fr):new Hr(`ChatRoomManager ${e} failed`,Fr)}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new Hr(e.message,e.code)}return e}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Zg(e.restBaseUrl,{errorMap:eS,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 Hr("ChatRoomManager is not bound to client",nt);return this.client}normalizeOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw new Zr(`${t} must be a string`,{code:ot,details:{fields:[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]}});return e}}normalizeOptionalBoolean(e,t){if(void 0!==e){if("boolean"!=typeof e)throw new Zr(`${t} must be a boolean`,{code:ot,details:{fields:[{path:t,message:`${t} must be a boolean`,rule:"invalid_format"}]}});return e}}getCacheManager(){return this.client?.getCacheManager()??null}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 Zw(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return To("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=Hw(e),s=await Zw(r,t);return r.map(e=>Jw(void 0,s.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return To("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=KC(e),s=await this.getRestClient(t).request(jC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return ZC(s,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],s=[],n=new Set;for(const o of r){if("string"!=typeof o)continue;const e=o.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return Jw(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>Jw(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){To("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:Jw(e.user,r.get(e.user.userId),e.user.userId)}))}async hydrateActionListResult(e){return{succeeded:await this.hydrateEntriesWithUsers(e.succeeded),failed:await this.hydrateEntriesWithUsers(e.failed)}}async hydrateSummaryOwners(e){const t=e.map(e=>e.owner?.userId).filter(e=>"string"==typeof e),r=await this.resolveUserInfoMap(t);return e.map(e=>e.owner?.userId?{...e,owner:Jw(e.owner,r.get(e.owner.userId),e.owner.userId)}:e)}async hydrateChatRoomDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveUserInfoMap([e.owner.userId]);return{...e,owner:Jw(e.owner,t.get(e.owner.userId),e.owner.userId)}}};tS.key="chatRoomManager";let rS=tS;const sS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},nS=e=>_l(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):[],oS=(e,t)=>{if(!Array.isArray(e.userIds)||0===e.userIds.length)throw new Zr(`${t} is required`,{code:nt,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});const r=e.userIds.map((e,r)=>{if("string"!=typeof e)throw new Zr(`${t}[${r}] must be a string`,{code:ot,details:{fields:[{path:`${t}[${r}]`,message:"userId must be a string",rule:"invalid_format"}]}});return e.trim()}),s=(e=>{const t=[],r=new Set;for(const s of e)s&&!r.has(s)&&(r.add(s),t.push(s));return t})(r);if(0===s.length)throw new Zr(`${t} is required`,{code:nt,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});return s.length!==r.length&&_l(e),s},iS=async(e,t)=>{const r=sS(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return nS(n).map(e=>({userId:e}))},aS=async(e,t,r)=>{const s=sS(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`,o=await e.post(n,{usernames:r},{operation:"addUsersToBlocklist"});return{succeeded:nS(o).map(e=>({userId:e})),failed:[]}},cS={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 dS=!1,uS=null;const lS=()=>uS||(dS||(Dc.util.Long=mi,Dc.configure(),dS=!0),pd(),uS=Dc.Root.fromJSON(cS),hd(uS),uS),hS=e=>"number"==typeof e?e:mi.isLong(e)?e.toNumber():0,pS=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:hS(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:hS(t.protocolVersion)}};class mS{encodeRequest(e){const t=lS().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=Gb){const t=lS().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Pb,status:e})).finish()}decode(e){const t=lS(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case Lb:return{type:Lb};case Pb:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Pb,status:hS(r.status)}}case $b:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:$b,header:pS(r.header),data:Array.isArray(r.data)?r.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:hS(t.createdAt),updatedAt:hS(t.updatedAt),metadataUpdatedAt:hS(t.metadataUpdatedAt)}})(e)):[],cursor:hS(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:hS(r.responseType)||Bb}}case qb:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:qb,header:pS(r.header),code:"string"==typeof r.code?r.code:"",message:"string"==typeof r.message?r.message:"Unknown roster error"}}default:return{type:"number"==typeof r.type?r.type:xb}}}}class fS{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(e){const t=e.header?.requestId;if(t&&t!==this.requestId)throw new Hr("Roster response requestId mismatched",Tr,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:t}});if(this.completed)throw new Hr("Roster response received after completion",Sr,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new Hr("Roster response type changed in same session",Sr,{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 Hr("Roster cursor duplicated",Sr,{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===Fb?"incremental":"full",version:this.version,pages:this.pages}}}const gS=e=>e.type===$b,yS=e=>"message"in e&&"code"in e;class vS{constructor(e){this.codec=new mS,this.sharedSession=e}async sync(e){const t=new fS(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(e,t){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:e.header.requestId,encode:()=>{const r=this.buildAttemptRequest(e,t.getNextCursor());return this.codec.encodeRequest(r)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:gS(t)||yS(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===Lb)return void(await r.send(this.codec.encodePong()));if(gS(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(yS(e))throw(e=>{const t=e.header?.requestId,r=r=>({stage:"sync_page",serverCode:e.code,requestId:t,retryable:r});switch(Number.parseInt(e.code,10)){case zb:return new Jr(e.message,{code:dt,details:r(!1)});case Kb:return new Hr(e.message,Br,{details:r(!0)});case jb:return new Hr(e.message,nt,{details:r(!1)});case Hb:return new Hr(e.message,ot,{details:r(!1)});case Vb:return new Hr(e.message,fr,{details:r(!0)});case Wb:return new Hr(e.message,Cr,{details:r(!1)});default:return new Hr(e.message,Cr,{details:r(!0)})}})(e);return}catch(s){throw s instanceof Hr?s:new Hr("Roster frame decode failed",Tr,{details:{stage:"response_decode",cause:s instanceof Error?s.message:String(s)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const bS=e=>e.versionState.version?"incremental":"full",IS=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?bS(s):"full",version:n}:t.requiresSync||"complete"!==s.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===s.cacheMeta.cacheIntegrity&&n?{decision:"incremental",version:t.version||n}:{decision:"full",version:t.version||n}:{decision:"skip",version:t.version||n}},wS=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{}}},CS=e=>{const t=(e=>{if(!(e instanceof Hr&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},SS=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),TS=e=>{To("Contact sync duration",e)};class _S{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(),t=Date.now();let r;this.dependencies.onStart();try{const s=await this.dependencies.queryMetadata(e.versionState.version);if(r=IS({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void TS({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(CS(s)){const r=IS({metadataFailed:!0,state:e}),n=s instanceof Hr?s:new Hr("Contact metadata request failed",wr,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:SS("metadata",n.code,n.message,!1)}),void TS({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:e.versionState.version,stage:"metadata",hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}if(r=IS({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:SS("metadata",wr,s instanceof Error?s.message:String(s),!0)}),void TS({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const s=await this.dependencies.getSyncUrls(),n=this.dependencies.buildRosterRequest({decision:r.decision,version:e.versionState.version}),o=await new vS(this.dependencies.getSharedSyncSession()).sync({urls:s,request:n}),i=(e=>{const t=[];for(const r of e)for(const e of r.data){const r=wS(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:r.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:r.nickname,avatarUrl:r.avatarUrl,sign:r.sign,ext:r.ext}})}return t})(o.pages),a=this.dependencies.applySyncResult({mode:o.mode,relations:i.map(e=>e.relation),userInfos:i.map(e=>e.userInfo),version:o.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),TS({outcome:"finish",decision:r.decision,durationMs:Date.now()-t,version:o.version,source:"sync",changed:a.changed,hasUsableSnapshot:a.snapshot.complete})}catch(s){const n=s instanceof Hr?s:new Hr("Contact sync failed",Cr,{details:{stage:"sync_page",cause:s instanceof Error?s.message:String(s)}}),o=n.details??{},i="string"==typeof o.stage?o.stage:"sync_page";this.dependencies.onFinish({error:SS(i,n.code,n.message,!0)}),TS({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:i,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const RS={items:[],loaded:!1,source:"server"},AS=Rb(Ab,{common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,223",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:223,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}}),MS=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=RS,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=RS,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"),r=this.validateOptionalString(e.message,"params.message"),s=this.getRestContextOrThrow(),n=this.getRestClient(s);So("ContactManager addContact",{userId:t,hasMessage:"string"==typeof r&&r.length>0}),await(async(e,t,r)=>{const s=sS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/apply?resource=${s.encodedResource}`;await e.post(n,{usernames:[r.userId],reason:r.message??""},{operation:"addContact"})})(n,s,{userId:t,message:r})})}async deleteContact(e){return this.runOperation("deleteContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);So("ContactManager deleteContact",{userId:t}),await(async(e,t,r)=>{const s=sS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.delete(n,{operation:"deleteContact"})})(s,r,{userId:t});const n=this.client?.getCacheManager()?.removeContact(t);So("ContactManager deleteContact patched cache",{userId:t,changed:n?.changed??!1})})}async acceptContactInvite(e){return this.runOperation("acceptContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);So("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,r)=>{const s=sS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/accept/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"acceptContactInvite"})})(s,r,{userId:t}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(e){return this.runOperation("declineContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);So("ContactManager declineContactInvite",{userId:t}),await(async(e,t,r)=>{const s=sS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/decline/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"declineContactInvite"})})(s,r,{userId:t})})}async setContactRemark(e){return this.runOperation("setContactRemark",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.validateRemark(e.remark,"params.remark"),s=this.getRestContextOrThrow(),n=this.getRestClient(s);So("ContactManager setContactRemark",{userId:t,remarkLength:r.length}),await(async(e,t,r)=>{const s=sS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.put(n,{remark:r.remark},{operation:"setContactRemark"})})(n,s,{userId:t,remark:r});const o=this.client?.getCacheManager()?.updateContactRemark(t,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),So("ContactManager setContactRemark patched cache",{userId:t,changed:o?.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 r=await this.enrichBlocklistUsers(await iS(t,e));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},So("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=oS(e,"params.userIds"),s=this.getRestClient(t);So("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await aS(s,t,r),o=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(o),{succeeded:o,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=oS(e,"params.userIds"),s=this.getRestClient(t);So("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length}),await(async(e,t,r)=>{const s=sS(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`;await e.request(n,{method:"DELETE",body:{usernames:r},operation:"removeUserFromBlocklist"})})(s,t,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw To(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`ContactManager ${e} failed: ${t.message}`,Fr):new Hr(`ContactManager ${e} failed`,Fr)}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 Zg(e.restBaseUrl,{errorMap:AS,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=RS)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const r of e)t.set(r.userId,r);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 r of e)t.delete(r);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 r=e.trim();if(!r)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return r}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(e,t){const r=t.some(e=>"invalid_format"===e.rule)?ot:nt;return new Zr(e,{code:r,details:{fields:t}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await kb(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 To("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=KC(e),s=await this.getRestClient(t).request(jC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return ZC(s,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 _S(e)}};MS.key="contactManager";let ES=MS;class US{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 kS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},NS=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),OS=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),xS=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw NS(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw OS(`${t}[${n}]`,`${t}[${n}] must be a string`);const o=e.trim();o&&!s.has(o)&&(s.add(o),r.push(o))}),0===r.length)throw NS(t);return r},LS=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw NS(t);return e.trim()},PS=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw OS(t,`${t} must be a string`);return e}},DS=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw OS(t,`${t} must be a boolean`);return e}},$S=(e,t)=>`/${e.orgName}/${e.appName}${t}`,qS=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),GS=e=>{const t=tb();"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}`:""},BS=async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Dl(e),r=Nl(t[0]),s=$l(e)??r;return{groupId:s&&Bl(s)||r&&Bl(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?xS(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"}))},FS=async(e,t,r)=>{const s=kS(t),n=LS(r.groupId,"params.groupId"),o=$S(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),i=await e.get(o,{operation:"getGroupInfo"});return jl(i)},jS=async(e,t,r)=>{const s=kS(t),n=LS(r.groupId,"params.groupId"),o={},i=PS(r.name,"params.name"),a=PS(r.description,"params.description"),c=PS(r.avatar,"params.avatar"),d=PS(r.ext,"params.ext"),u=DS(r.public,"params.public"),l=DS(r.joinApprovalRequired,"params.joinApprovalRequired"),h=DS(r.allowInvites,"params.allowInvites"),p=DS(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw OS(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==i&&(o.groupname=i),void 0!==a&&(o.description=a),void 0!==c&&(o.avatar=c),void 0!==d&&(o.custom=d),void 0!==u&&(o.public=u),void 0!==l&&(o.membersonly=l),void 0!==h&&(o.allowinvites=h),void 0!==p&&(o.invite_need_confirm=p),void 0!==m&&(o.maxusers=m),0===Object.keys(o).length)throw NS("params");const f=$S(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,o,{operation:"updateGroupInfo"})},zS=async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/users${(e=>{const t=tb();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 o of Dl(e)){const e=Nl(o);if(!e)continue;const r=xl(e.owner),s=xl(e.admin),n=xl(e.member),i=r??s??n;if(!i)continue;const a=Ll(e.joinedAt)??Ll(e.joined_time);t.push({user:zl(i),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=ql(e,"pagenum"),s=ql(e,"pagesize"),n=Gl(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},KS=async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/admin`),o=await e.get(n,{operation:"getGroupAdminList"});return Kl(o)},HS=async(e,t,r)=>{const s=kS(t),n=LS(r.groupId,"params.groupId"),o=GS(r),i=o?"&":"",a=$S(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${i}${o.replace("?","")}`);return(e=>{const t=[];for(const r of Dl(e)){const e=xl(r);if(e){t.push({user:zl(e)});continue}const s=Nl(r);if(!s)continue;const n=xl(s.user);if(!n)continue;const o=Ll(s.expire);t.push({user:zl(n),...void 0===o?{}:{muteExpire:o}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},VS=async(e,t,r)=>{const s=kS(t),n=LS(r.groupId,"params.groupId"),o=GS(r),i=o?"&":"",a=$S(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${i}${o.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return Kl(c).map(e=>({user:e}))},WS=async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/white/users`),o=await e.get(n,{operation:"getGroupAllowlist"});return Kl(o).map(e=>({user:e}))},JS=async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=$l(e)??{};return{announcement:Ol(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},ZS=async(e,t,r)=>{const s=kS(t),n=tb();n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const o=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=ql(e,"pagenum"),r=ql(e,"pagesize"),s=Gl(e,r);return{items:Dl(e).map(e=>Hl(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(o,{operation:"getGroupSharedFileList"}))},QS=(e,t)=>{const r=kS(e);return $S(r,`/chatgroups/${encodeURIComponent(LS(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(LS(t.fileId,"params.fileId"))}`)},YS=async(e,t,r)=>{const s=kS(t),n=LS(r.groupId,"params.groupId"),o=LS(r.userId,"params.userId"),i=((e,t,r)=>{if(t!==e.userId)return null;const s=Object.entries(r);if(0===s.length)return null;let n;for(const[o,i]of s){if(!qS.has(o)||"string"!=typeof i)return null;if(void 0!==n){if(n!==i)return null}else n=i}return void 0===n?null:{nameCard:n}})(t,o,r.memberAttributes);if(i){const t=$S(s,`/sdk/chatgroups/${encodeURIComponent(n)}/nameCard`);return await e.put(t,i,{operation:"setGroupMemberAttributes"})}const a=$S(s,`/sdk/metadata/chatgroup/${encodeURIComponent(n)}/user/${encodeURIComponent(o)}?resource=${s.encodedResource}`);return await e.put(a,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},XS=async(e,t,r)=>{const s=kS(t),n=$S(s,`/sdk/metadata/chatgroup/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/get`);return(e=>{const t=$l(e)??{},r=Nl(t.data)??t,s={};for(const[n,o]of Object.entries(r)){const e=Nl(o);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:xS(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},eT=e=>{const t=_l(e)?e:{},r=t.data,s=_l(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return tT(n);const o=_l(r)?r:t,i=_l(o.namecards)?o.namecards:o,a={};for(const[c,d]of Object.entries(i)){if("string"==typeof d){a[c]={namecard:d};continue}if(!_l(d))continue;const e=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof e&&(a[c]={namecard:e,namecardUpdateTime:rT(d)})}return a},tT=e=>{const t={};return e.forEach(e=>{if(!_l(e))return;const r=e.username??e.userId??e.userid??e.user_id,s=e.name_card??e.namecard??e.nameCard??e.groupNamecard??e.group_namecard??e.group_name_card;"string"==typeof r&&r.trim()&&"string"==typeof s&&(t[r.trim()]={namecard:s,namecardUpdateTime:rT(e)})}),t},rT=e=>Nh("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),sT=e=>{if(_l(e))return Nh("number"==typeof e.timestamp?e.timestamp:"number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0)};class nT{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 oT=e=>({...e}),iT=e=>({...e,owner:e.owner?{...e.owner}:void 0});class aT{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=oT({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=iT({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=oT(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?oT(this.summarySnapshot):this.detailSnapshot?oT(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?iT(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 cT{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 dT{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new cT,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 aT(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 s=t?.items.find(t=>t.groupId===e);return s?{...s}: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 s={...r,...t,groupId:e};return this.joinedGroupById.set(e,s),this.mergeSummary(this.toGroupSummary(s)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...s}:{...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 uT=0,lT=5,hT=12,pT=13,mT=0,fT=1,gT=2,yT=0,vT=1,bT=2,IT=3,wT=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(s=e.role,s===mT?"owner":s===fT?"admin":s===gT?"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===yT?"DEFAULT":r===vT?"ALL":r===bT?"AT":r===IT?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},CT=e=>e.updatedAt??0,ST=(e,t)=>{if(!e)return!0;return CT(t)>=CT(e)},TT={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 _T=null,RT=!1;const AT=()=>_T||(RT||(Dc.util.Long=mi,Dc.configure(),RT=!0),pd(),_T=Dc.Root.fromJSON(TT),hd(_T),_T),MT=e=>AT().lookupType(e),ET=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(mi.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}},UT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:ET(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:ET(t.protocol_version)??ET(t.protocolVersion)??0}};class kT{constructor(){this.requestType=MT("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=MT("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=MT("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 s=this.tryDecodeRequest(e);return s||{type:uT}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=ET(t.type);return r!==hT?null:{type:r,header:UT(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:ET(t.last_sync_time)??ET(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=ET(t.type);return r!==pT?null:{type:r,header:UT(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:ET(t.members_count)??ET(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:ET(t.role),mute_expiration:ET(t.mute_expiration)??ET(t.muteExpiration),remind_type:ET(t.remind_type)??ET(t.remindType),create_at:ET(t.create_at)??ET(t.createAt),update_at:ET(t.update_at)??ET(t.updateAt),joined_timestamp:ET(t.joined_timestamp)??ET(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:ET(t.last_sync_finished_ts)??ET(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=ET(t.type);return r!==lT?null:{type:r,header:UT(t.header),code:ET(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class NT{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==pT)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new Hr("Joined groups response received after completion",fr,{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 Hr("Joined groups final batch missing lastSyncFinishedTs",fr,{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 OT=e=>e.type===pT,xT=e=>e.type===lT;class LT{constructor(e){this.codec=new kT,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new NT(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,t,r){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:t,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,t,r.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:OT(t)||xT(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(OT(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(xT(e))throw(e=>{const t=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new Hr(e.message,nt,{details:t("request_send",!1)});case 1602:return new Hr(e.message,fr,{details:t("batch_merge",!0)});case 1002:return new Jr(e.message,{code:dt,details:t("auth",!1)});case 1003:return new Hr(e.message,Br,{details:t("server_limit",!0)});default:return new Hr(e.message,fr,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof Hr?t:new Hr("Joined groups frame decode failed",Tr,{details:{stage:"response_decode",cause:t instanceof Error?t.message:String(t)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class PT{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const r=await this.dependencies.getSyncUrls();if(0===r.length)throw new Hr("Group sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect",retryable:!0}});const s=this.buildRequest(),n=await new LT(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),o=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=wT(r);e&&t.push(e)}return t})(e.groups)),i=this.dependencies.getRuntimeSnapshot(),a=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=new Map;for(const n of e.incomingItems){const e=r.get(n.groupId)??t.get(n.groupId);ST(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=vf;return{items:Array.from(s?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:s?"limited":"synced",limited:s,storageLimit:yf,serverLimit:vf,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:i?.items??[],incomingItems:o,lastSyncFinishedTs:n.lastSyncFinishedTs}),c=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(a);const d=this.dependencies.getRuntimeSnapshot()??a;try{await c.commitJoinedGroupPreviewSnapshot(d);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(d,e)&&await c.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw i&&this.dependencies.applyRuntimeSnapshot(i),new Xr("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}To("Group sync finished",{durationMs:Date.now()-e,itemCount:a.items.length,limited:a.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof Hr?e:new Hr("Group sync failed",fr,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},s=r.serverCode;return{dataType:"group",code:t.code,stage:(n=r.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:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof s||"string"==typeof s?s:void 0};var n})(t);To("Group sync failed",{durationMs:Date.now()-e,stage:r.stage,code:r.code,serverCode:r.serverCode}),this.dependencies.onFinish({status:"failed",error:r})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:t,appName:r}=Qn(e.appKey);return{type:hT,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const DT=Rb(Ab,{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:{}}}}),$T=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 dT,this.groupEventSync=new nT(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,s=await this.buildIncomingEventPayload(r,t);if(!s)return;if(this.eventContext?.dispatch?.(r,s),r!==we)return;if(!("attribute"in s)||!("user"in s))return;const n=this.extractGroupNamecard(s.attribute);if(void 0===n||!s.user?.userId)return;const o=this.client?.getCurrentUserId();s.user.userId!==o&&(this.getCacheManager()?.setGroupNamecards([{groupId:s.groupId,userId:s.user.userId,namecard:n,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(Ce,{groupId:s.groupId,userId:s.user.userId,namecard:n}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await BS(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const t=e.trim();if(0===t.length)throw new Zr("groupId is required",{code:nt,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const r=this.groupRegistry.get(t);if(r)return r;this.getGroupSummaryForHandle(t),this.getGroupRepository().getOrCreate(t);const s=new US(t,this);return this.groupRegistry.set(t,s),s}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await FS(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(s)})}async getGroupInfoList(e){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=kS(t),n=xS(r.groupIds,"params.groupIds"),o=$S(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),i=await e.get(o,{operation:"getGroupInfoList"});return(_l(i)&&Array.isArray(i.data)?i.data:[]).map(e=>jl({data:[e]}))})(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailsUsers(r);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,s=e===ne?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case Q:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case Y:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case X:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case ee:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case te:case re:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case se:return{groupId:r.groupId,groupName:r.groupName};case ne:return{groupId:r.groupId,groupName:r.groupName??s};case oe:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case ie:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case ae:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case ce:case de:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case ue:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case le:case he:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case pe:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case me:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,n)};case fe:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,n)};case ge:return{groupId:r.groupId,announcement:r.announcement??""};case ye:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case ve:return{groupId:r.groupId,fileId:r.fileId??""};case be:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case Ie:{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 we: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 t=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},r=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:t,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(n){To("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:n})}if(r)return r;const s=this.getGroupRepository().getDetailSnapshot(e.groupId);return s||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await jS(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:LS(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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}?version=v3&resource=${s.encodedResource}`);await e.delete(n,{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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/quit?resource=${s.encodedResource}`);await e.delete(n,{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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/apply?resource=${s.encodedResource}`);await e.post(n,{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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:xS(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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:LS(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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:LS(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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{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 zS(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 s=kS(t),n=xS(r.userIds,"params.userIds"),o=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await KS(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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/admin?resource=${s.encodedResource}`);await e.post(n,{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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`);await e.delete(n,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await HS(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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:xS(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 s=kS(t),n=xS(r.userIds,"params.userIds"),o=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/mute/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/ban?resource=${s.encodedResource}`);await e.post(n,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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/ban?resource=${s.encodedResource}`);await e.delete(n,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await VS(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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:xS(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 s=kS(t),n=xS(r.userIds,"params.userIds"),o=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/blocks/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await WS(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 s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:xS(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 s=kS(t),n=xS(r.userIds,"params.userIds"),o=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/white/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(e){return this.runOperation("checkIfInGroupAllowList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),o=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof o?o:_l(o)&&"boolean"==typeof o.data?o.data:Boolean(o)})(this.getRestClient(t),t,e)})}async checkIfInGroupMuteList(e){return this.runOperation("checkIfInGroupMuteList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=kS(t),n=$S(s,`/sdk/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),o=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof o?o:_l(o)&&"boolean"==typeof o.data?o.data:Boolean(o)})(this.getRestClient(t),t,e)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return JS(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/announcement?resource=${s.encodedResource}`);await e.post(n,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await ZS(this.getRestClient(t),t,e),s=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?s.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const t=this.getRestContextOrThrow(),r=QS(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=Fn({file:e.file}),n=jp({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),o=n?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const i=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[ml]:pl()},source:s.source,timeoutMs:3e5,onProgress:e.onFileUploadProgress}));if(!i)throw new Error("platform upload adapter is unavailable");if(i.status<200||i.status>=300)throw new Hr("uploadGroupSharedFile failed",mr,{details:{status:i.status}});o?.finish({code:i.status,success:!0}),n?.finish({code:0,success:!0}),e.onFileUploadComplete?.(i.body)}catch(i){const t=Qu(i);throw o?.finish({code:t.code,success:!1,description:t.message}),n?.finish({code:t.code,success:!1,description:t.message}),t.code===Gr&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(t),t}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=kS(t),n=$S(s,`/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(LS(r.fileId,"params.fileId"))}?resource=${s.encodedResource}`);await e.delete(n,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let t,r;try{const s=this.getRestContextOrThrow(),n=`${s.restBaseUrl}${QS(s,e)}`;t=jp({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:n});const o=this.requireClient().getRequestAdapter();if(!o)throw new Hr("downloadGroupSharedFile request adapter is unavailable",hr);const i=await o.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[ml]:pl()},responseType:"arraybuffer",timeoutMs:6e4});if(i.status<200||i.status>=300)throw r?.finish({code:i.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:i.status,success:!1,description:"downloadGroupSharedFile failed"}),new Hr("downloadGroupSharedFile failed",mr);r?.finish({code:i.status,success:!0}),t?.finish({code:0,success:!0});const a="undefined"!=typeof Blob?new Blob([i.data]):i.data;e.onFileDownloadComplete?.(a)}catch(s){const n=s instanceof Hr?s.code:hr,o=s instanceof Error?s.message:String(s);throw r?.finish({code:n,success:!1,description:o}),t?.finish({code:n,success:!1,description:o}),e.onFileDownloadError?.(s),s}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await YS(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return XS(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,t){0!==t.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const r=this.getRestContextOrThrow(),s=t.map(e=>e.userId),n=await(async(e,t,r)=>{const s=kS(t),n=$S(s,`/sdk/chatgroups/${encodeURIComponent(LS(r.groupId,"params.groupId"))}/nameCard/batch/get`),o=await e.post(n,{members:xS(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:eT(o),responseTimestamp:sT(o)}})(this.getRestClient(r),r,{groupId:e,userIds:s}),o=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),i=[],a=new Set;for(const[t,d]of Object.entries(n.items))a.add(t),i.push({groupId:e,userId:t,namecard:d.namecard,namecardUpdateTime:o.get(t)??d.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const c=s.filter(e=>!a.has(e));c.length>0&&"number"==typeof n.responseTimestamp&&i.push(...c.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:n.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(i);for(const e of i)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(Ce,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});c.length>0&&"number"!=typeof n.responseTimestamp&&To("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:s,missingUserIds:c})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw To(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`GroupManager ${e} failed: ${t.message}`,Fr):new Hr(`GroupManager ${e} failed`,Fr)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Zg(e.restBaseUrl,{errorMap:DT,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new Hr("GroupManager is not bound to client",nt);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new dT),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new nT(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 s=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return s||void 0}async resolveMembersJoinedGroupName(e){const t=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(t)return t;const r=this.resolveUsableGroupName(e.groupName,e.groupId);if(r)return r;const s=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await FS(this.getRestClient(t),t,{groupId:e.groupId}),n=this.getGroupRepository();if(n.getSessionKey()!==s)return;return n.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(n){return void To("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,t,r){if(t.userId!==e)return;const s=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof s)return;const n=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof n&&To("Group member attributes update response missing server update time",{groupId:t.groupId,userId:t.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:t.groupId,userId:t.userId,namecard:s,namecardUpdateTime:n,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const s of r){const e=Nh("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!_l(e))return;r.push(e.lastModified,e.last_modified,e.timestamp,e.updateTime,e.update_time,e.updatedAt,e.updated_at);const s=e.data;if(_l(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];_l(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;_l(n)&&r.push(n[t])}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 kl(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return To("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],s=[],n=new Set;for(const o of r){if("string"!=typeof o)continue;const e=o.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return Ul(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>Ul(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:Ul(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case ue:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case pe:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case X:case oe:return void this.addCurrentUserJoinedGroupFromEvent(t);case me:{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 fe: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 se:case ne:return void(await this.removeJoinedGroupLocal(t.groupId));case ie:case ae:case ce:case de:case le:case he:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case me:case fe:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const s=this.getGroupRepository().getDetailSnapshot(e);return!(!s||"number"!=typeof s.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,s.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(s){return To("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(s){return To("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 s=await FS(this.getRestClient(r),r,{groupId:e}),n=this.getGroupRepository();if(n.getSessionKey()!==t)return!1;n.mergeDetail(s);const o=n.getJoinedGroupSummarySnapshot(e);if(!o)return!1;const i=n.mergeJoinedGroupSummary(e,{...o.name||!s.name?{}:{name:s.name},...void 0!==o.description||void 0===s.description?{}:{description:s.description},...void 0!==o.memberCount||void 0===s.memberCount?{}:{memberCount:s.memberCount},...void 0!==o.role||void 0===s.role?{}:{role:s.role},...void 0!==o.disabled||void 0===s.disabled?{}:{disabled:s.disabled},...o.ownerId||!s.owner?.userId?{}:{ownerId:s.owner.userId},...void 0!==o.avatarUrl||void 0===s.avatarUrl?{}:{avatarUrl:s.avatarUrl},...void 0!==o.muteAllMembers||void 0===s.muteAllMembers?{}:{muteAllMembers:s.muteAllMembers},...void 0!==o.createdAt||void 0===s.createdAt?{}:{createdAt:s.createdAt},...void 0!==o.joinedAt||void 0===s.joinedAt?{}:{joinedAt:s.joinedAt}});if(i){this.persistJoinedGroupSnapshot(i);const t=n.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:s.name||t.name,avatarUrl:s.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void To("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{To("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=KC(e),s=await this.getRestClient(t).request(jC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return ZC(s,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(hI(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await bI({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 vI({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(),s=e.find(e=>e.userId===r),n=e.filter(e=>e.userId!==r);s&&t.dispatchOwnInfoUpdated?.(s),t.dispatchUserInfoUpdated?.(n),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new PT(e)}};$T.key="groupManager";let qT=$T;const GT=Rb(Ab,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),BT=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(e){return this.runOperation("publishPresence",async()=>{this.validateDescription(e.customStatus);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=`/${s}/${n}/users/${t.userId}/presence/${t.clientResource}/1`,i={ext:e.customStatus};So("Call publishPresence",{customStatus:e.customStatus}),await r.request(o,{method:"POST",body:i,operation:"publishPresence"})})}async subscribePresence(e){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(e.userIds),this.validateExpiry(e.expiry);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=`/${s}/${n}/users/${t.userId}/presence/${e.expiry}`,i={usernames:e.userIds};So("Call subscribePresence",{userIds:e.userIds,expiry:e.expiry});const a=await r.request(o,{method:"POST",body:i,operation:"subscribePresences"});return this.normalizeSubscribeResponse(a)})}async unsubscribePresence(e){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=`/${s}/${n}/users/${t.userId}/presence`;So("Call unsubscribePresence",{userIds:e.userIds}),await r.request(o,{method:"DELETE",body:e.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(e){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(e.pageNum,e.pageSize);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=`/${s}/${n}/users/${t.userId}/presence/sublist?pageNum=${e.pageNum}&pageSize=${e.pageSize}`;So("Call getSubscribedPresenceList",{pageNum:e.pageNum,pageSize:e.pageSize});const i=await r.request(o,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(i)})}async getPresenceStatus(e){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=`/${s}/${n}/users/${t.userId}/presence`,i={usernames:e.userIds};So("Call getPresenceStatus",{userIds:e.userIds});const a=await r.request(o,{method:"POST",body:i,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(a)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw To(`PresenceManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`PresenceManager ${e} failed: ${t.message}`,Fr):new Hr(`PresenceManager ${e} failed`,Fr)}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("PresenceManager is not bound to event context",{code:nt,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new Zr("PresenceManager is not bound to client",{code:nt,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Zg(e.restBaseUrl,{errorMap:GT,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,n]of Object.entries(e))if("number"==typeof n&&Number.isFinite(n))r[s]=Math.trunc(n);else if("string"==typeof n&&n.trim().length>0){const e=Number(n);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new Zr("Invalid parameters",{code:ot,details:{fields:e}})}};BT.key="presenceManager";let FT=BT;const jT=Rb(Ab,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),zT=["singleChat","groupChat"],KT=["ALL","AT","NONE","DEFAULT"],HT=["ALL","AT","NONE"],VT=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),WT=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=`/${s}/${n}/users/${t.userId}`;So("Call uploadPushToken",{deviceId:e.deviceId,notifierName:e.notifierName}),await r.request(o,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken"})})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=`/${s}/${n}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,i=this.buildSilentModePayload(e.rule);So("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await r.request(o,{method:"PUT",body:i,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/user/${e.userId}`;So("Call getGlobalSilentMode");const o=await t.request(n,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(o))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=this.mapConversationTypeToPath(e.conversationType),i=`/${s}/${n}/users/${t.userId}/notification/${o}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);So("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const c=await r.request(i,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(c),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=this.mapConversationTypeToPath(e.conversationType),i=`/${s}/${n}/users/${t.userId}/notification/${o}/${encodeURIComponent(e.conversationId)}`;So("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(i,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=this.mapConversationTypeToPath(e.conversationType),i=`/${s}/${n}/users/${t.userId}/notification/${o}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;So("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(i,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),i=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${s}/${n}/users/${t.userId}/notification?user=${o}&group=${i}`;So("Call getConversationSilentModes",{count:e.conversationList.length});const c=await r.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(c,"user"),u=this.resolveConversationRuleMap(c,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:u[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),o=`/${s}/${n}/users/${t.userId}/notification/language`;So("Call setPushLanguage",{language:e.language}),await r.request(o,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/language`;So("Call getPushLanguage");const o=await t.request(n,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(o,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{So("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),r=Ng({items:t.getCacheManager()?.loadSessionList()??[],pageSize:e.pageSize,cursor:e.cursor});return Promise.resolve(r)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof Hr?e:e instanceof Error?new Hr(`PushManager operation failed: ${e.message}`,Fr):new Hr("PushManager operation failed",Fr)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Zg(e.restBaseUrl,{errorMap:jT,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new Hr("PushManager is not bound to client",nt);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!zT.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,r)=>{this.validateConversationId(e.conversationId,`${t}[${r}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${r}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!VT(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!HT.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,r){const s=Object.keys(e).find(e=>!r.includes(e));if(s)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${s}`,message:`${s} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!VT(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const r=this.parseRuleView(e);return r?t?{...this.toRuleViewFromFallback(t),...r}:r:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!VT(e))return null;const t={},r=this.normalizeRemindType(e.type);null!==r&&(t.remindType=r);const s=e.ignoreDuration;"number"==typeof s&&Number.isInteger(s)&&s>0&&(t.expireTimestamp=s);const n=e.ignoreInterval;if("string"==typeof n){const e=this.parseInterval(n);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const r=Number(t[1]),s=Number(t[2]),n=Number(t[3]),o=Number(t[4]);return Number.isInteger(r)&&Number.isInteger(s)&&Number.isInteger(n)&&Number.isInteger(o)?r<0||r>23||n<0||n>23||s<0||s>59||o<0||o>59?null:{startTime:{hours:r,minutes:s},endTime:{hours:n,minutes:o}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(VT(e.data)){const r=e.data[t];if(VT(r))return r}const r=e[t];return VT(r)?r:{}}resolveSilentModeRuleSource(e){if(!VT(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return VT(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":KT.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(VT(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const r=e.data.language;if("string"==typeof r&&r.length>0)return r}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(e,t){return new Zr(e,{code:ot,details:{fields:t}})}};WT.key="pushManager";let JT=WT;const ZT=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},QT=(e,t="params.userIds")=>BC(e,t),YT=e=>{const t=QT(e);if(t.length>100)throw((e,t,r,s=ot)=>new Zr(e,{code:s,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",Br);return{usernames:t}},XT=(e,t)=>{const r=(e=>QT(e))(t);return`${ZT(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},e_=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},t_=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],r_=Rb(Ab,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),s_=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,r=t?.getCacheManager();if(!t||!r||!t.getCurrentUserId())return;const s=e.payload,n=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=e_(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const o=r.applyUserInfoNotifyPatch(n);if(!o.applied)return void So("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:o.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[o.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",o.record.profile);const i=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(Z,{userInfo:o.record.profile,contact:i})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=KC(BC(e.userIds,"params.userIds")),n=jC(t);So("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const o=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),i=this.normalizeFetchEnvelope(o,s.targets);return this.writeCache(i),i.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(n=BC(e.userIds,"params.userIds"),o=FC(e.attributes,"params.attributes"),{targets:BC(n),properties:FC(o).map(e=>GC(e,"params.attributes"))});var n,o;const i=jC(t);So("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const a=await r.request(i,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),c=this.normalizeFetchEnvelope(a,s.targets);return this.writeCache(c),c.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>ZT(e))(t),n=YT(e.userIds);So("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=XT(t,e.userIds);So("UserInfoManager unsubscribeUsersInfo",{userIds:BC(e.userIds,"params.userIds")}),await r.request(s,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),r=(e=>ZT(e))(e);So("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>{const t=[];if(QC(t,"nickname",e.nickname,"params.nickname"),QC(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),QC(t,"mail",e.mail,"params.mail"),QC(t,"phone",e.phone,"params.phone"),QC(t,"gender",e.gender,"params.gender"),QC(t,"sign",e.sign,"params.sign"),QC(t,"birth",e.birth,"params.birth"),QC(t,"ext",e.ext,"params.ext"),0===t.length)throw DC("params must include at least one updatable field","params","required");return YC(t)})(e),n=zC(t);So("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const o=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),i=this.normalizeUpdateEnvelope(o,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([i]),this.dispatchSelfUpdate(i.profile),i.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=((e,t)=>{const r=GC(e,"attribute"),s=qC(t,"value");if("gender"!==r&&"string"!=typeof s)throw DC("value must be a string","value","invalid_format");return YC([[r,String(s)]])})(e,t),o=zC(r);So("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const i=await s.request(o,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),a=this.normalizeUpdateEnvelope(i,r.userId,{userId:r.userId,[e]:t});return this.writeCache([a]),this.dispatchSelfUpdate(a.profile),a.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof Hr?t:(To("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new Hr(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new Zr("UserInfoManager is not bound to client",{code:nt,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Zg(e.restBaseUrl,{errorMap:r_,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return JC(e,t)}normalizeUpdateEnvelope(e,t,r){const s=_l(e)?e:null,n=(s&&_l(s.data)?s.data:null)??(s&&this.looksLikeUserInfoAttributes(s)?s:null),o=s&&"number"==typeof s.lastModified?s.lastModified:void 0;return{profile:n?this.toUserInfo(t,n):{userId:t,...r??{}},lastModified:o}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(e){return!!_l(e)&&("nickname"in e||"avatarurl"in e||"avatarUrl"in e||"mail"in e||"phone"in e||"gender"in e||"sign"in e||"birth"in e||"ext"in e)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of t_)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return t_.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=Nh(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:r,lastSyncAt:t,lastAccess:t,lastUpdate:e.lastModified??t}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};s_.key="userInfoManager";let n_=s_;return e.AuthenticationError=Jr,e.CONVERSATION_MARK={MARK_0:0,MARK_1:1,MARK_2:2,MARK_3:3,MARK_4:4,MARK_5:5,MARK_6:6,MARK_7:7,MARK_8:8,MARK_9:9,MARK_10:10,MARK_11:11,MARK_12:12,MARK_13:13,MARK_14:14,MARK_15:15,MARK_16:16,MARK_17:17,MARK_18:18,MARK_19:19},e.CacheManager=Ff,e.ChatClient=Qb,e.ChatManager=Sw,e.ChatRoom=zw,e.ChatRoomManager=rS,e.ChatThread=Tw,e.ChatThreadManager=jw,e.ConnectionError=Wr,e.ContactManager=ES,e.Group=US,e.GroupManager=qT,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.MessageReceiveError=Yr,e.MessageSendError=Qr,e.NetworkError=Vr,e.PresenceManager=FT,e.PushManager=JT,e.RUNTIME_PLATFORMS=Eo,e.RestBusinessError=ts,e.RestTransportError=es,e.SDKError=Hr,e.StorageError=Xr,e.StreamMessageStatus=rt,e.UploadError=rs,e.UserInfoManager=n_,e.ValidationError=Zr,e.createPlatformAdapter=Zu,e.detectRuntimePlatform=(e,t)=>di(t,e).platform,e.isSDKError=function(e){if(e instanceof Hr)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},e.setLogLevel=function(e){vo instanceof yo&&vo.setLevel(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
1
+ var IMSDK=function(e){"use strict";const t="disconnected",r="connecting",s="connected",n="reconnecting",i="reconnectFailed",o="onConnecting",a="onConnected",c="onDisconnected",d="onReconnectFailed",u="onTokenWillExpire",l="onTokenExpired",h="onOfflineMessageSyncStart",p="onOfflineMessageSyncFinish",m="onSendTimeout",f="onGroupNotify",g="onChatRoomNotify",y="onChatThreadNotify",v="onUserInfoNotify",b="__internal:onMessageSent",I="login",w="reconnect",C="online",S="offline-recover",T="heartbeat-failed",_="send-timeout",R="close",A="error",M="limit",E="offline",U="token-expired",N="onMessage",k="onStreamMessage",O="onConversationListUpdate",x="onMessageReadReceipts",L="onMessageDelivered",P="onMessageRecalled",D="onMessageUpdated",q="onReactionChanged",B="onPinnedMessageChanged",$="onMultiDeviceContact",F="onMultiDeviceConversation",G="onSyncDataStart",j="onSyncDataFinished",z="onPresenceStatusChange",K="onContactInvited",H="onContactDeleted",V="onContactAdded",W="onContactRefuse",J="onContactAgreed",Z="onContactInfoUpdated",Q="onInvitationReceived",Y="onRequestToJoinReceived",X="onRequestToJoinAccepted",ee="onRequestToJoinDeclined",te="onInvitationAccepted",re="onInvitationDeclined",se="onUserRemoved",ne="onGroupDestroyed",ie="onAutoAcceptInvitationFromGroup",oe="onMuteListAdded",ae="onMuteListRemoved",ce="onAllowListAdded",de="onAllowListRemoved",ue="onAllMemberMuteStateChanged",le="onAdminAdded",he="onAdminRemoved",pe="onOwnerChanged",me="onMembersJoined",fe="onMembersExited",ge="onAnnouncementChanged",ye="onSharedFileAdded",ve="onSharedFileDeleted",be="onGroupInfoChanged",Ie="onGroupDisabledChanged",we="onGroupMemberAttributeChanged",Ce="onUserGroupNamecardUpdated",Se="__chatroom:onChatRoomDestroyed",Te="__chatroom:onMembersJoined",_e="__chatroom:onMembersExited",Re="__chatroom:onRemovedFromChatRoom",Ae="__chatroom:onMuteListAdded",Me="__chatroom:onMuteListRemoved",Ee="__chatroom:onAllowListAdded",Ue="__chatroom:onAllowListRemoved",Ne="__chatroom:onAllMemberMuteStateChanged",ke="__chatroom:onAdminAdded",Oe="__chatroom:onAdminRemoved",xe="__chatroom:onOwnerChanged",Le="__chatroom:onAnnouncementChanged",Pe="__chatroom:onChatRoomInfoChanged",De="__chatroom:onAttributesUpdate",qe="__chatroom:onAttributesRemoved",Be="onChatRoomDestroyed",$e="onMembersJoined",Fe="onMembersExited",Ge="onRemovedFromChatRoom",je="onMuteListAdded",ze="onMuteListRemoved",Ke="onAllowListAdded",He="onAllowListRemoved",Ve="onAllMemberMuteStateChanged",We="onAdminAdded",Je="onAdminRemoved",Ze="onOwnerChanged",Qe="onAnnouncementChanged",Ye="onChatRoomInfoChanged",Xe="onAttributesUpdate",et="onAttributesRemoved",rt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function st(e){return"object"==typeof e.stream&&null!==e.stream}const nt=110,it=110,ot=110,at=200,ct=201,dt=202,ut=210,lt=108,ht=213,pt=214,mt=215,ft=301,gt=300,yt=1,vt=301,bt=202,It=300,wt=304,Ct=3,St=300,Tt=301,_t=303,Rt=1,At=500,Mt=500,Et=222,Ut=111,Nt=302,kt=400,Ot=401,xt=407,Lt=501,Pt=502,Dt=504,qt=505,Bt=506,$t=507,Ft=508,Gt=509,jt=510,zt=511,Kt=206,Ht=207,Vt=216,Wt=217,Jt=218,Zt=219,Qt=220,Yt=221,Xt=305,er=403,tr=405,rr=406,sr=1200,nr=1299,ir=303,or=110,ar=4,cr=4,dr=500,ur=2,lr=500,hr=2,pr=301,mr=303,fr=303,gr=602,yr=603,vr=606,br=607,Ir=703,wr=1700,Cr=1701,Sr=1702,Tr=1703,_r=1704,Rr=1110,Ar=1111,Mr=1112,Er=1113,Ur=407,Nr=408,kr=409,Or=410,xr=411,Lr=110,Pr=100,Dr=405,qr=402,Br=301,$r=1,Fr=4,Gr=1,jr="[REDACTED]",zr=e=>{if(!e)return"";const t=e.includes("?"),r=e.includes("#");try{return((e,t,r)=>(e.username&&(e.username=jr),e.password&&(e.password=jr),e.search=t?`?${jr}`:"",e.hash=r?`#${jr}`:"",e.toString()))(new URL(e),t,r)}catch{const t=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===t?"[invalid-url]":`${e.slice(0,t)}?${jr}`}},Kr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,zr(t)]:[e,t]));class Hr extends Error{constructor(e,t=Gr,r){super(e),this.name="SDKError",this.code=t,this.details=r?.details?Kr(r.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,Hr)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class Vr extends Hr{constructor(e,t){super(e,t?.code??hr,t),this.name="NetworkError"}}class Wr extends Hr{constructor(e,t){super(e,t?.code??gt,t),this.name="ConnectionError"}}class Jr extends Hr{constructor(e,t){super(e,t?.code??dt,t),this.name="AuthenticationError"}}class Zr extends Hr{constructor(e,t){super(e,t?.code??ot,t),this.name="ValidationError"}}class Qr extends Hr{constructor(e,t){super(e,t?.code??_t,t),this.name="MessageSendError"}}class Yr extends Hr{constructor(e,t){super(e,t?.code??Mt,t),this.name="MessageReceiveError"}}class Xr extends Hr{constructor(e,t){super(e,t?.code??Ct,t),this.name="StorageError"}}class es extends Hr{constructor(e,t){super(e,t?.code??hr,t),this.name="RestTransportError"}}class ts extends Hr{constructor(e,t){super(e,t?.code??fr,t),this.name="RestBusinessError"}}class rs extends Hr{constructor(e,t){super(e,t?.code??qr,t),this.name="UploadError"}}const ss=0,ns=1,is=2,os=3,as=4,cs=0,ds=1,us=2,ls=3,hs=4,ps=5,ms=6,fs=7,gs=8,ys=0,vs=1,bs=2,Is=3,ws=4,Cs=5,Ss=6,Ts=7,_s=8,Rs=0,As=1,Ms=2,Es=3,Us=4,Ns=0,Os=1,xs=2,Ls=3,Ps=5,Ds=0,qs=1,Bs=2,$s=0,Fs=0,Gs=2,js=0,zs=1,Ks=2,Hs=3,Vs=4,Ws=5,Js=6,Zs=7,Qs=8,Ys=9,Xs=10,en=11,tn=12,rn=13,sn=14,nn=15,on=16,an=17,cn=18,dn=19,un=20,ln=1,hn=2,pn=3,mn=4,fn=5,gn=6,yn=7,vn=8,bn="Sorry, user register limit",In="Sorry, user register rate limit",wn="Sorry, token expired",Cn="Sorry, token or password does not match login info",Sn="Sorry, user not found",Tn="Sorry, the app month live count limit",_n="Sorry, the app day live count limit",Rn="Sorry, the app online count limit",An={[zs]:dt,[Ks]:dt,[Hs]:nt,[Vs]:it,[Ws]:gt,[Js]:lt,[Zs]:ut,[dn]:ut,[Qs]:gt,[Ys]:Gr,[Xs]:Gr,[en]:ht,[tn]:ut,[rn]:pt,[sn]:Fr,[nn]:mt,[on]:Gr,[an]:Gr,[cn]:Mt,[un]:Qt},Mn=new Set([zs,Ks,Hs,Vs,Js,Zs,dn,Ys,Xs,en,tn,rn,sn,nn,on,an,cn,un]),En={[bn]:Fr,[In]:Fr,[wn]:lt,[Cn]:dt,[Sn]:dt,blocked:Et,"group not found":vr,"illegal chatroom tag":nt,"not in group or chatroom":gr,"exceed recall time limit":Dt,"message recall disabled":qt,"group ack not open":qt,"group ack msg permission denied":yr,"the message has expired":Bt,"limit send group ack msg":Fr,"not in group or chatroom white list":$t,nonroster:Yt,"group is disabled":br,"roaming is not open":qt,"Sorry, message does not exist":nt,"Sorry, edit limit reached":Fr,"Sorry, You do not have permission":ut,"Sorry, format is incorrect":nt,"Sorry, edit is not available":Xt,"Sorry, edit fail":zt},Un=[["limit directed users",Fr],["no permission to recall message",ut]],Nn={[Tn]:Fr,[_n]:Fr,[Rn]:Fr,"sensitive words":Lt,"blocked by mod_antispam":Lt,"user is mute":Zt,"traffic limit":Gt,"Sorry, data is too large":jt},kn=(e,t)=>{if("number"!=typeof e)return{code:Gr,retryable:!0};const r=((e,t)=>{if(t){if(e===zs){const e=En[t];if(void 0!==e)return e;for(const[r,s]of Un)if(t.includes(r))return s;try{const e=JSON.parse(t);if("moderation"===e.error_type)return sr;if("string"==typeof e.error_type)return nr}catch{}return}return e===Zs?Nn[t]:e===dn?Ft:e===nn?mt:void 0}})(e,t);return{code:r??(An[e]??Gr),retryable:!Mn.has(e)}},On={[Fr]:"Message operation exceeded a service limit",[lt]:"Message cannot be sent because the authentication token expired",[nt]:"Message cannot be sent because the request is invalid",[dt]:"Message cannot be sent because authentication failed",[ut]:"Message operation is forbidden",[ht]:"Message cannot be sent because the account is bound to another device",[pt]:"Message cannot be sent because the account is logged in on too many devices",[mt]:"Message cannot be sent because the user is muted in the group or chat room",[Et]:"Message cannot be sent because you are blocked by the recipient",[Zt]:"Message cannot be sent because the user is globally muted",[Qt]:"Message cannot be sent because the current device has changed",[Yt]:"Message cannot be sent because the recipient is not in your contact list",[gt]:"Message cannot be sent because the server is unreachable",[Xt]:"Message editing is not available",[Mt]:"Message processing failed",[Lt]:"Message contains prohibited content",[Pt]:"Message sending traffic limit exceeded",[Dt]:"The message recall time limit has been exceeded",[qt]:"The required messaging service is not enabled",[Bt]:"The message has expired",[$t]:"The user is not in the group or chat room allowlist",[Ft]:"The message was blocked by external logic",[Gt]:"Message sending rate limit exceeded",[jt]:"Message size exceeds the limit",[zt]:"Message editing failed",[gr]:"The user is not in the group or chat room",[yr]:"The user does not have permission to perform this group message operation",[vr]:"The group does not exist",[br]:"The group is disabled",[sr]:"The message was rejected by content moderation",[nr]:"The message was rejected by a third-party service"},xn=3e5,Ln={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"},Pn=e=>"undefined"!=typeof Blob&&e instanceof Blob,Dn=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),r=t.length>0?t[t.length-1]:void 0;if(r)return r},qn=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const r=e.slice(t+1).toLowerCase();return Ln[r]},Bn=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t&&t.length>0)return t}},$n=e=>{const t=e.file,r=e.sourceMeta,s=t.name||(r?Bn(r,["name","fileName","filename"]):void 0),n=e.file.type||(r?Bn(r,["type","mimeType","filetype"]):void 0),i=e.file.size||(r?((e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t}})(r,["size","fileSize","fileLength"]):void 0),o=Fn({fileName:s,fileType:n,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize,webFile:e.file}},Fn=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),Gn=e=>{const{file:t,fallbackName:r,fallbackMimeType:s,fallbackSize:n}=e,i=(e=>{if(Pn(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const r of["file","originFileObj","raw","blob"]){const e=t[r];if(Pn(e))return e}})(t);if(i)return $n({file:i,fallbackName:r,fallbackMimeType:s,fallbackSize:n,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=Dn(t.path),i=Fn({fileName:t.name??e,fileType:t.type??qn(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});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=Dn(t.uri),i=Fn({fileName:t.name??e,fileType:t.type??qn(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});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 o=Fn({fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"web-file",name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize}},jn=5242880,zn=5242880,Kn="CHAT",Hn="GROUP",Vn="ROOM",Wn="original",Jn="large",Zn=e=>/^https?:\/\//i.test(e),Qn=e=>{const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw new rs("Invalid appKey for upload",{code:Pr,details:{appKey:e}});return{orgName:t[0],appName:t[1]}},Yn=e=>"singleChat"===e?Kn:"groupChat"===e?Hn:Vn,Xn=(e,t)=>ti(e,{size:t}),ei=e=>{try{return decodeURIComponent(e)}catch{return e}},ti=(e,t)=>{const[r="",s]=e.split("#",2),[n,i=""]=r.split("?",2),o=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const r=encodeURIComponent(e),s=o.filter(t=>{const[s=""]=t.split("=",2);return s!==r&&ei(s)!==e});o.length=0,o.push(...s),void 0!==t&&o.push(`${r}=${encodeURIComponent(String(t))}`)}),`${n}${o.length>0?`?${o.join("&")}`:""}${s?`#${s}`:""}`},ri=(e,t)=>{if(!e)return"";const r={};return e.includes("em-redirect")||(r["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(r["share-secret"]=t),0===Object.keys(r).length?e:ti(e,r)},si=e=>{const t=(r=e.messageType,s=e.imageType,"image"!==r?"attachment":s===Wn?"image-origin":"image-big");var r,s;const n=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>n;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:n,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},ni=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const r=(e=>{const[t="",r]=e.split("#",2),[s,n=""]=t.split("?",2),i=n.split("&").filter(Boolean).filter(e=>{const[t="",r=""]=e.split("=",2),s=ei(t),n=ei(r);return"size"!==s||!["big","large","thumbnail","small"].includes(n)}).join("&");return`${s}${i?`?${i}`:""}${r?`#${r}`:""}`})(e);return{originalImageUrl:r,bigImageUrl:Xn(r,"large"),thumbnailUrl:Xn(r,"small")}},ii=e=>e===Wn?"origin":"large",oi=e=>2===e?Jn:Wn,ai=e=>{const t=e.response.entities?.[0];if(!t?.uuid)throw new rs("Upload response missing uuid",{code:qr,details:{response:e.response}});const r=t["share-secret"],s=t["file-metadata"]??{},n="number"==typeof s["content-length"]?s["content-length"]:e.fallbackSize,i="string"==typeof s["content-type"]?s["content-type"]:e.fileType,o=`${e.restBaseUrl}/${e.orgName}/${e.appName}/chatfiles/${t.uuid}`;if("image"===e.messageType){const t=(e.imageType??Jn)===Wn;return{...ni(o,{deriveVariants:!e.useCustomAttachmentUpload}),isOriginalImage:t,secret:r,fileLength:n,filetype:i,filename:e.fileName,width:e.width,height:e.height}}const a="video"===e.messageType?`${o}?vframe=true`:void 0;return{url:o,secret:r,fileLength:n,filetype:i,filename:e.fileName,thumbnailUrl:a}},ci=e=>new Promise(t=>{setTimeout(t,e)});const di=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(" "):"",r=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${r}`}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 r=e;for(;r.length>this.maxChunkBytes;)t.push(r.slice(0,this.maxChunkBytes)),r=r.slice(this.maxChunkBytes);return r.length>0&&t.push(r),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 ci(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:r,userId:s,token:n,resource:i,requestAdapter:o}=this.context;if(!(t&&r&&s&&n&&o))return!1;let a="",c="";try{const e=Qn(r);a=e.orgName,c=e.appName}catch{return!1}const d=`${t}/${a}/${c}/sdk/users/${s}/client/logs`,u={resource:i??"webim",logContent:e};try{const e=await o.request({url:d,method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json"},body:u,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}}},ui="[MASKED]",li=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),hi=e=>!!e&&li.has((e=>e.toLowerCase())(e)),pi=(e,t,r)=>{const s=r??new WeakSet;if("string"==typeof e)return((e,t)=>hi(t)?ui: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:(n=e).name,message:n.message};var n;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>pi(e,void 0,s));if("object"==typeof e){if(s.has(e))return"[Circular]";if(s.add(e),(e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Date||e instanceof Error))(e)){const t={};for(const[r,n]of Object.entries(e))hi(r)?t[r]=ui:t[r]=pi(n,r,s);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},mi="undefined"!=typeof document,fi={DEBUG:0,WARN:1,ERROR:2};class gi{constructor(e="WARN"){this.level=e}setLevel(e){this.level=e}shouldLog(e){return fi[e]>=fi[this.level]}emit(e,t,r){const s=(e=>{const t=new WeakSet;return e.map(e=>pi(e,void 0,t))})(r),n=((e,t,r)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:r}))(e,t,s);di.append(n);const i=new Date,o=`[Chat][${e}][${`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}:${String(i.getSeconds()).padStart(2,"0")}.${String(i.getMilliseconds()).padStart(3,"0")}`}]`;mi?console.log(`%c${o}`,"color: rgb(0, 157, 255); font-weight: bold",t,...s):console.log(o,t,...s)}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 yi=new gi;function vi(e){di.setState(e)}function bi(e){di.updateContext(e)}async function Ii(){await di.reportNow()}function wi(){di.stop()}const Ci=(e,...t)=>yi.debug(e,...t),Si=(e,...t)=>yi.warn(e,...t),Ti=(e,...t)=>yi.error(e,...t),_i=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>=55296&&s<=56319&&r+1<e.length){const t=e.charCodeAt(r+1);t>=56320&&t<=57343&&(s=65536+(s-55296<<10)+(t-56320),r+=1)}s<=127?t.push(s):s<=2047?t.push(192|s>>6,128|63&s):s<=65535?t.push(224|s>>12,128|s>>6&63,128|63&s):t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}return new Uint8Array(t)},Ri=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r+=1){const s=e[r]??0;if(s<128){t+=String.fromCharCode(s);continue}if(s>=192&&s<224){const n=e[r+1]??0;t+=String.fromCharCode((31&s)<<6|63&n),r+=1;continue}if(s>=224&&s<240){const n=e[r+1]??0,i=e[r+2]??0;t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i),r+=2;continue}const n=((7&s)<<18|(63&(e[r+1]??0))<<12|(63&(e[r+2]??0))<<6|63&(e[r+3]??0))-65536;t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),r+=3}return t};class Ai{constructor(){this.lastEventKey=null}normalize(e,u){const l=(e=>{switch(e){case r:case n:return o;case s:return a;case t:return c;case i:return d;default:return null}})(e);if(!l)return null;const h=((e,t)=>[e,t.state,t.reason,String(t.attempt),String(t.maxAttempts),String(t.isLoginPhase),String(t.isOnline),String(t.errorCode??""),t.errorMessage??""].join("|"))(l,u);return this.lastEventKey===h?null:(this.lastEventKey=h,{eventName:l,payload:u})}reset(){this.lastEventKey=null}}const Mi={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"},Ei="init",Ui="request",Ni="upload",ki="socket",Oi="proto",xi="runtime",Li="PLATFORM_INIT_FAILED",Pi="PLATFORM_MISSING_CAPABILITY",Di="PLATFORM_REQUEST_FAILED",qi="PLATFORM_UPLOAD_FAILED",Bi="PLATFORM_SOCKET_FAILED",$i="PLATFORM_PROTO_FAILED",Fi=(e,t)=>{const r=new Error(e);return r.name="PlatformAdapterError",r.code=t.code,r.stage=t.stage,r.retryable=t.retryable,t.details&&(r.details=Kr(t.details)),r},Gi=0,ji=1,zi=2,Ki=3,Hi=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],Vi=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const r={},s=e;for(const n of Hi)try{const e=s[n];void 0!==e&&(r[n]=e)}catch{}for(const n of Object.keys(t))r[n]=t[n];return r})("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}:{}})},Wi={web:Mi.WEB,"mp-weixin":Mi.WECHAT_MINIAPP,"mp-alipay":Mi.ALIPAY_MINIAPP,"mp-baidu":Mi.BAIDU_MINIAPP,"mp-toutiao":Mi.TOUTIAO_MINIAPP,"mp-lark":Mi.LARK_MINIAPP,"mp-qq":Mi.QQ_MINIAPP,"mp-kuaishou":Mi.KUAISHOU_MINIAPP,"mp-jd":Mi.JD_MINIAPP,"mp-360":Mi.MINIAPP_360,"mp-harmony":Mi.HARMONY_MINIAPP,"quickapp-webview":Mi.QUICKAPP,"quickapp-webview-union":Mi.QUICKAPP,"quickapp-webview-huawei":Mi.QUICKAPP},Ji=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Zi=e=>(e=>Ji(e,"canIUse")&&Ji(e,"getSystemInfo"))(e)||(e=>Ji(e,"request")&&Ji(e,"connectSocket"))(e),Qi=e=>Ji(e,"request")&&Ji(e,"connectSocket")&&Ji(e,"uploadFile"),Yi=(e,t)=>t===Mi.WECHAT_MINIAPP?e.wx:t===Mi.QQ_MINIAPP?e.qq:t===Mi.TOUTIAO_MINIAPP?e.tt:t===Mi.BAIDU_MINIAPP?e.swan:t===Mi.ALIPAY_MINIAPP?e.my:t===Mi.DINGTALK_MINIAPP?e.dd:t===Mi.JD_MINIAPP?e.jd:t===Mi.KUAISHOU_MINIAPP?e.ks:t===Mi.UNIAPP?e.uni:void 0,Xi=e=>{const t=e?.miniGlobal;return Zi(t)?t:e},eo=e=>{const t=Xi(e);return Qi(t)?t:void 0},to=e=>void 0!==e.window&&void 0!==e.document,ro=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),so=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(Zi(t))return!0;try{if(!Ji(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},no=e=>Qi(e.wx)?Mi.WECHAT_MINIAPP:Qi(e.my)?Mi.ALIPAY_MINIAPP:Qi(e.dd)?Mi.DINGTALK_MINIAPP:Qi(e.swan)?Mi.BAIDU_MINIAPP:Qi(e.tt)?Mi.TOUTIAO_MINIAPP:Qi(e.qq)?Mi.QQ_MINIAPP:Qi(e.jd)?Mi.JD_MINIAPP:Qi(e.ks)?Mi.KUAISHOU_MINIAPP:void 0,io=e=>void 0!==no(e),oo=e=>{const t=no(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return Wi[r]??Mi.UNIAPP}catch{return Mi.UNIAPP}return to(e)?Mi.WEB:Mi.UNIAPP},ao=(e,t)=>{const r=eo(Yi(e,t));if(r)return r;const s=eo(e.uni);return s||(e.uni??e)},co=(e,t)=>{const r=e??Vi();if(t){const e=t===Mi.UNIAPP||so(r),s=e?oo(r):t;return{platform:t,hostPlatform:s,framework:e?"uniapp":to(r)?"web":"native",global:e?ao(r,s):Xi(Yi(r,t))??r}}if(so(r)){const e=oo(r);return{platform:Mi.UNIAPP,hostPlatform:e,framework:"uniapp",global:ao(r,e)}}return Zi(r.swan)?{platform:Mi.BAIDU_MINIAPP,hostPlatform:Mi.BAIDU_MINIAPP,framework:"native",global:Xi(r.swan)??r.swan}:Zi(r.tt)?{platform:Mi.TOUTIAO_MINIAPP,hostPlatform:Mi.TOUTIAO_MINIAPP,framework:"native",global:Xi(r.tt)??r.tt}:Zi(r.dd)?{platform:Mi.DINGTALK_MINIAPP,hostPlatform:Mi.DINGTALK_MINIAPP,framework:"native",global:Xi(r.dd)??r.dd}:Zi(r.my)?{platform:Mi.ALIPAY_MINIAPP,hostPlatform:Mi.ALIPAY_MINIAPP,framework:"native",global:Xi(r.my)??r.my}:Zi(r.wx)?{platform:Mi.WECHAT_MINIAPP,hostPlatform:Mi.WECHAT_MINIAPP,framework:"native",global:Xi(r.wx)??r.wx}:Zi(r.qq)?{platform:Mi.QQ_MINIAPP,hostPlatform:Mi.QQ_MINIAPP,framework:"native",global:Xi(r.qq)??r.qq}:Zi(r.jd)?{platform:Mi.JD_MINIAPP,hostPlatform:Mi.JD_MINIAPP,framework:"native",global:Xi(r.jd)??r.jd}:Zi(r.ks)?{platform:Mi.KUAISHOU_MINIAPP,hostPlatform:Mi.KUAISHOU_MINIAPP,framework:"native",global:Xi(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:Mi.REACT_NATIVE,hostPlatform:Mi.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:to(r)?Mi.ELECTRON_RENDERER:Mi.ELECTRON_MAIN,hostPlatform:to(r)?Mi.ELECTRON_RENDERER:Mi.ELECTRON_MAIN,framework:"electron",global:r}:ro(r)||to(r)?{platform:Mi.WEB,hostPlatform:Mi.WEB,framework:ro(r)?"worker":"web",global:r}:{platform:Mi.UNKNOWN,hostPlatform:Mi.UNKNOWN,framework:"native",global:r}},uo=e=>e===Mi.WECHAT_MINIAPP||e===Mi.QQ_MINIAPP||e===Mi.TOUTIAO_MINIAPP||e===Mi.BAIDU_MINIAPP||e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP||e===Mi.LARK_MINIAPP||e===Mi.KUAISHOU_MINIAPP||e===Mi.JD_MINIAPP||e===Mi.MINIAPP_360||e===Mi.HARMONY_MINIAPP||e===Mi.QUICKAPP||e===Mi.UNIAPP,lo=["request","upload","socket","proto"],ho=(e,t=lo)=>{const r=((e,t=lo)=>t.filter(t=>!e[t]))(e,t);if(0!==r.length)throw Fi("Platform missing required capabilities.",{code:Pi,stage:Ei,retryable:!1,details:{required:[...t],missing:r}})};var po=null;try{po=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function mo(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function fo(e){return!0===(e&&e.__isLong__)}function go(e){var t=Math.clz32(e&-e);return e?31-t:t}mo.prototype.__isLong__,Object.defineProperty(mo.prototype,"__isLong__",{value:!0}),mo.isLong=fo;var yo={},vo={};function bo(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=vo[e])?s:(r=wo(e,0,!0),n&&(vo[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=yo[e])?s:(r=wo(e,e<0?-1:0,!1),n&&(yo[e]=r),r)}function Io(e,t){if(isNaN(e))return t?Uo:Eo;if(t){if(e<0)return Uo;if(e>=Ro)return Lo}else{if(e<=-Ao)return Po;if(e+1>=Ao)return xo}return e<0?Io(-e,t).neg():wo(e%_o|0,e/_o|0,t)}function wo(e,t,r){return new mo(e,t,r)}mo.fromInt=bo,mo.fromNumber=Io,mo.fromBits=wo;var Co=Math.pow;function So(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?Uo:Eo;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return So(e.substring(1),t,r).neg();for(var n=Io(Co(r,8)),i=Eo,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),c=parseInt(e.substring(o,o+a),r);if(a<8){var d=Io(Co(r,a));i=i.mul(d).add(Io(c))}else i=(i=i.mul(n)).add(Io(c))}return i.unsigned=t,i}function To(e,t){return"number"==typeof e?Io(e,t):"string"==typeof e?So(e,t):wo(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}mo.fromString=So,mo.fromValue=To;var _o=4294967296,Ro=_o*_o,Ao=Ro/2,Mo=bo(1<<24),Eo=bo(0);mo.ZERO=Eo;var Uo=bo(0,!0);mo.UZERO=Uo;var No=bo(1);mo.ONE=No;var ko=bo(1,!0);mo.UONE=ko;var Oo=bo(-1);mo.NEG_ONE=Oo;var xo=wo(-1,2147483647,!1);mo.MAX_VALUE=xo;var Lo=wo(-1,-1,!0);mo.MAX_UNSIGNED_VALUE=Lo;var Po=wo(0,-2147483648,!1);mo.MIN_VALUE=Po;var Do=mo.prototype;Do.toInt=function(){return this.unsigned?this.low>>>0:this.low},Do.toNumber=function(){return this.unsigned?(this.high>>>0)*_o+(this.low>>>0):this.high*_o+(this.low>>>0)},Do.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Po)){var t=Io(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=Io(Co(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),c=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return c+o;for(;c.length<6;)c="0"+c;o=""+c+o}},Do.getHighBits=function(){return this.high},Do.getHighBitsUnsigned=function(){return this.high>>>0},Do.getLowBits=function(){return this.low},Do.getLowBitsUnsigned=function(){return this.low>>>0},Do.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Po)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},Do.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},Do.isZero=function(){return 0===this.high&&0===this.low},Do.eqz=Do.isZero,Do.isNegative=function(){return!this.unsigned&&this.high<0},Do.isPositive=function(){return this.unsigned||this.high>=0},Do.isOdd=function(){return!(1&~this.low)},Do.isEven=function(){return!(1&this.low)},Do.equals=function(e){return fo(e)||(e=To(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Do.eq=Do.equals,Do.notEquals=function(e){return!this.eq(e)},Do.neq=Do.notEquals,Do.ne=Do.notEquals,Do.lessThan=function(e){return this.comp(e)<0},Do.lt=Do.lessThan,Do.lessThanOrEqual=function(e){return this.comp(e)<=0},Do.lte=Do.lessThanOrEqual,Do.le=Do.lessThanOrEqual,Do.greaterThan=function(e){return this.comp(e)>0},Do.gt=Do.greaterThan,Do.greaterThanOrEqual=function(e){return this.comp(e)>=0},Do.gte=Do.greaterThanOrEqual,Do.ge=Do.greaterThanOrEqual,Do.compare=function(e){if(fo(e)||(e=To(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Do.comp=Do.compare,Do.negate=function(){return!this.unsigned&&this.eq(Po)?Po:this.not().add(No)},Do.neg=Do.negate,Do.add=function(e){fo(e)||(e=To(e));var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=0,d=0,u=0,l=0;return u+=(l+=n+(65535&e.low))>>>16,d+=(u+=s+a)>>>16,c+=(d+=r+o)>>>16,c+=t+i,wo((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},Do.subtract=function(e){return fo(e)||(e=To(e)),this.add(e.neg())},Do.sub=Do.subtract,Do.multiply=function(e){if(this.isZero())return this;if(fo(e)||(e=To(e)),po)return wo(po.mul(this.low,this.high,e.low,e.high),po.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Uo:Eo;if(this.eq(Po))return e.isOdd()?Po:Eo;if(e.eq(Po))return this.isOdd()?Po:Eo;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Mo)&&e.lt(Mo))return Io(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=65535&e.low,d=0,u=0,l=0,h=0;return l+=(h+=n*c)>>>16,u+=(l+=s*c)>>>16,l&=65535,u+=(l+=n*a)>>>16,d+=(u+=r*c)>>>16,u&=65535,d+=(u+=s*a)>>>16,u&=65535,d+=(u+=n*o)>>>16,d+=t*c+r*a+s*o+n*i,wo((l&=65535)<<16|(h&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},Do.mul=Do.multiply,Do.divide=function(e){if(fo(e)||(e=To(e)),e.isZero())throw Error("division by zero");var t,r,s;if(po)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?wo((this.unsigned?po.div_u:po.div_s)(this.low,this.high,e.low,e.high),po.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Uo:Eo;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Uo;if(e.gt(this.shru(1)))return ko;s=Uo}else{if(this.eq(Po))return e.eq(No)||e.eq(Oo)?Po:e.eq(Po)?No:(t=this.shr(1).div(e).shl(1)).eq(Eo)?e.isNegative()?No:Oo:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(Po))return this.unsigned?Uo:Eo;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Eo}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var n=Math.ceil(Math.log(t)/Math.LN2),i=n<=48?1:Co(2,n-48),o=Io(t),a=o.mul(e);a.isNegative()||a.gt(r);)a=(o=Io(t-=i,this.unsigned)).mul(e);o.isZero()&&(o=No),s=s.add(o),r=r.sub(a)}return s},Do.div=Do.divide,Do.modulo=function(e){return fo(e)||(e=To(e)),po?wo((this.unsigned?po.rem_u:po.rem_s)(this.low,this.high,e.low,e.high),po.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Do.mod=Do.modulo,Do.rem=Do.modulo,Do.not=function(){return wo(~this.low,~this.high,this.unsigned)},Do.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},Do.clz=Do.countLeadingZeros,Do.countTrailingZeros=function(){return this.low?go(this.low):go(this.high)+32},Do.ctz=Do.countTrailingZeros,Do.and=function(e){return fo(e)||(e=To(e)),wo(this.low&e.low,this.high&e.high,this.unsigned)},Do.or=function(e){return fo(e)||(e=To(e)),wo(this.low|e.low,this.high|e.high,this.unsigned)},Do.xor=function(e){return fo(e)||(e=To(e)),wo(this.low^e.low,this.high^e.high,this.unsigned)},Do.shiftLeft=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):wo(0,this.low<<e-32,this.unsigned)},Do.shl=Do.shiftLeft,Do.shiftRight=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):wo(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Do.shr=Do.shiftRight,Do.shiftRightUnsigned=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):wo(32===e?this.high:this.high>>>e-32,0,this.unsigned)},Do.shru=Do.shiftRightUnsigned,Do.shr_u=Do.shiftRightUnsigned,Do.rotateLeft=function(e){var t;return fo(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?wo(this.high,this.low,this.unsigned):e<32?(t=32-e,wo(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),wo(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},Do.rotl=Do.rotateLeft,Do.rotateRight=function(e){var t;return fo(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?wo(this.high,this.low,this.unsigned):e<32?(t=32-e,wo(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),wo(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},Do.rotr=Do.rotateRight,Do.toSigned=function(){return this.unsigned?wo(this.low,this.high,!1):this},Do.toUnsigned=function(){return this.unsigned?this:wo(this.low,this.high,!0)},Do.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Do.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},Do.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},mo.fromBytes=function(e,t,r){return r?mo.fromBytesLE(e,t):mo.fromBytesBE(e,t)},mo.fromBytesLE=function(e,t){return new mo(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},mo.fromBytesBE=function(e,t){return new mo(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(mo.fromBigInt=function(e,t){return wo(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},mo.fromValue=function(e,t){return"bigint"==typeof e?mo.fromBigInt(e,t):To(e,t)},Do.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var qo="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Bo(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{r=this instanceof e}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}),r}var $o,Fo,Go={exports:{}},jo={},zo={};function Ko(){if(Fo)return $o;return Fo=1,$o=function(e,t){var r=new Array(arguments.length-1),s=0,n=2,i=!0;for(;n<arguments.length;)r[s++]=arguments[n++];return new Promise(function(n,o){r[s]=function(e){if(i)if(i=!1,e)o(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];n.apply(null,t)}};try{e.apply(t||null,r)}catch(a){i&&(i=!1,o(a))}})},$o}var Ho,Vo,Wo,Jo,Zo,Qo={};var Yo,Xo,ea,ta,ra,sa={};var na,ia,oa,aa,ca,da,ua,la,ha,pa,ma={exports:{}};ma.exports;function fa(){return na||(na=1,e=ma,t=ma.exports,"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function r(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function s(e){return!0===(e&&e.__isLong__)}function n(e){var t=Math.clz32(e&-e);return e?31-t:t}r.prototype.__isLong__,Object.defineProperty(r.prototype,"__isLong__",{value:!0}),r.isLong=s;var i={},o={};function a(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=o[e])?s:(r=d(e,0,!0),n&&(o[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=i[e])?s:(r=d(e,e<0?-1:0,!1),n&&(i[e]=r),r)}function c(e,t){if(isNaN(e))return t?b:v;if(t){if(e<0)return b;if(e>=f)return T}else{if(e<=-g)return _;if(e+1>=g)return S}return e<0?c(-e,t).neg():d(e%m|0,e/m|0,t)}function d(e,t,s){return new r(e,t,s)}r.fromInt=a,r.fromNumber=c,r.fromBits=d;var u=Math.pow;function l(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?b:v;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return l(e.substring(1),t,r).neg();for(var n=c(u(r,8)),i=v,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),d=parseInt(e.substring(o,o+a),r);if(a<8){var h=c(u(r,a));i=i.mul(h).add(c(d))}else i=(i=i.mul(n)).add(c(d))}return i.unsigned=t,i}function h(e,t){return"number"==typeof e?c(e,t):"string"==typeof e?l(e,t):d(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}r.fromString=l,r.fromValue=h;var p=65536,m=p*p,f=m*m,g=f/2,y=a(1<<24),v=a(0);r.ZERO=v;var b=a(0,!0);r.UZERO=b;var I=a(1);r.ONE=I;var w=a(1,!0);r.UONE=w;var C=a(-1);r.NEG_ONE=C;var S=d(-1,2147483647,!1);r.MAX_VALUE=S;var T=d(-1,-1,!0);r.MAX_UNSIGNED_VALUE=T;var _=d(0,-2147483648,!1);r.MIN_VALUE=_;var R=r.prototype;R.toInt=function(){return this.unsigned?this.low>>>0:this.low},R.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},R.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(_)){var t=c(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=c(u(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),d=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return d+o;for(;d.length<6;)d="0"+d;o=""+d+o}},R.getHighBits=function(){return this.high},R.getHighBitsUnsigned=function(){return this.high>>>0},R.getLowBits=function(){return this.low},R.getLowBitsUnsigned=function(){return this.low>>>0},R.getNumBitsAbs=function(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},R.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&-1===e&&!(0===this.low&&-2097152===this.high)},R.isZero=function(){return 0===this.high&&0===this.low},R.eqz=R.isZero,R.isNegative=function(){return!this.unsigned&&this.high<0},R.isPositive=function(){return this.unsigned||this.high>=0},R.isOdd=function(){return!(1&~this.low)},R.isEven=function(){return!(1&this.low)},R.equals=function(e){return s(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},R.eq=R.equals,R.notEquals=function(e){return!this.eq(e)},R.neq=R.notEquals,R.ne=R.notEquals,R.lessThan=function(e){return this.comp(e)<0},R.lt=R.lessThan,R.lessThanOrEqual=function(e){return this.comp(e)<=0},R.lte=R.lessThanOrEqual,R.le=R.lessThanOrEqual,R.greaterThan=function(e){return this.comp(e)>0},R.gt=R.greaterThan,R.greaterThanOrEqual=function(e){return this.comp(e)>=0},R.gte=R.greaterThanOrEqual,R.ge=R.greaterThanOrEqual,R.compare=function(e){if(s(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},R.comp=R.compare,R.negate=function(){return!this.unsigned&&this.eq(_)?_:this.not().add(I)},R.neg=R.negate,R.add=function(e){s(e)||(e=h(e));var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,u=0,l=0,p=0,m=0;return p+=(m+=i+(65535&e.low))>>>16,l+=(p+=n+c)>>>16,u+=(l+=r+a)>>>16,u+=t+o,d((p&=65535)<<16|(m&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},R.subtract=function(e){return s(e)||(e=h(e)),this.add(e.neg())},R.sub=R.subtract,R.multiply=function(e){if(this.isZero())return this;if(s(e)||(e=h(e)),t)return d(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return this.unsigned?b:v;if(this.eq(_))return e.isOdd()?_:v;if(e.eq(_))return this.isOdd()?_:v;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(y)&&e.lt(y))return c(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,a=e.high>>>16,u=65535&e.high,l=e.low>>>16,p=65535&e.low,m=0,f=0,g=0,I=0;return g+=(I+=o*p)>>>16,f+=(g+=i*p)>>>16,g&=65535,f+=(g+=o*l)>>>16,m+=(f+=n*p)>>>16,f&=65535,m+=(f+=i*l)>>>16,f&=65535,m+=(f+=o*u)>>>16,m+=r*p+n*l+i*u+o*a,d((g&=65535)<<16|(I&=65535),(m&=65535)<<16|(f&=65535),this.unsigned)},R.mul=R.multiply,R.divide=function(e){if(s(e)||(e=h(e)),e.isZero())throw Error("division by zero");var r,n,i;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?d((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?b:v;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return b;if(e.gt(this.shru(1)))return w;i=b}else{if(this.eq(_))return e.eq(I)||e.eq(C)?_:e.eq(_)?I:(r=this.shr(1).div(e).shl(1)).eq(v)?e.isNegative()?I:C:(n=this.sub(e.mul(r)),i=r.add(n.div(e)));if(e.eq(_))return this.unsigned?b:v;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=v}for(n=this;n.gte(e);){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var o=Math.ceil(Math.log(r)/Math.LN2),a=o<=48?1:u(2,o-48),l=c(r),p=l.mul(e);p.isNegative()||p.gt(n);)p=(l=c(r-=a,this.unsigned)).mul(e);l.isZero()&&(l=I),i=i.add(l),n=n.sub(p)}return i},R.div=R.divide,R.modulo=function(e){return s(e)||(e=h(e)),t?d((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},R.mod=R.modulo,R.rem=R.modulo,R.not=function(){return d(~this.low,~this.high,this.unsigned)},R.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},R.clz=R.countLeadingZeros,R.countTrailingZeros=function(){return this.low?n(this.low):n(this.high)+32},R.ctz=R.countTrailingZeros,R.and=function(e){return s(e)||(e=h(e)),d(this.low&e.low,this.high&e.high,this.unsigned)},R.or=function(e){return s(e)||(e=h(e)),d(this.low|e.low,this.high|e.high,this.unsigned)},R.xor=function(e){return s(e)||(e=h(e)),d(this.low^e.low,this.high^e.high,this.unsigned)},R.shiftLeft=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):d(0,this.low<<e-32,this.unsigned)},R.shl=R.shiftLeft,R.shiftRight=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):d(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},R.shr=R.shiftRight,R.shiftRightUnsigned=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):d(32===e?this.high:this.high>>>e-32,0,this.unsigned)},R.shru=R.shiftRightUnsigned,R.shr_u=R.shiftRightUnsigned,R.rotateLeft=function(e){var t;return s(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),d(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},R.rotl=R.rotateLeft,R.rotateRight=function(e){var t;return s(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),d(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},R.rotr=R.rotateRight,R.toSigned=function(){return this.unsigned?d(this.low,this.high,!1):this},R.toUnsigned=function(){return this.unsigned?this:d(this.low,this.high,!0)},R.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},R.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},R.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},r.fromBytes=function(e,t,s){return s?r.fromBytesLE(e,t):r.fromBytesBE(e,t)},r.fromBytesLE=function(e,t){return new r(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},r.fromBytesBE=function(e,t){return new r(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(r.fromBigInt=function(e,t){return d(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},r.fromValue=function(e,t){return"bigint"==typeof e?r.fromBigInt(e,t):h(e,t)},R.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e}),e.default=r}(t),e.exports=(r=t).default||r),ma.exports;var e,t,r}function ga(){return ia||(ia=1,function(e){var t,r,s=e;function n(e){return"__proto__"===e||"prototype"===e||"constructor"===e}function i(e){var t="boolean"==typeof arguments[arguments.length-1],r=t?arguments.length-1:arguments.length;t=t&&arguments[arguments.length-1];for(var s=1;s<r;++s){var i=arguments[s];if(i)for(var o=Object.keys(i),a=0;a<o.length;++a)n(o[a])||void 0!==e[o[a]]&&t||(e[o[a]]=i[o[a]])}return e}function o(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),r&&i(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}s.asPromise=Ko(),s.base64=(Ho||(Ho=1,function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var r=new Array(64),s=new Array(123),n=0;n<64;)s[r[n]=n<26?n+65:n<52?n+71:n<62?n-4:n-59|43]=n++;t.encode=function(e,t,s){for(var n,i=null,o=[],a=0,c=0;t<s;){var d=e[t++];switch(c){case 0:o[a++]=r[d>>2],n=(3&d)<<4,c=1;break;case 1:o[a++]=r[n|d>>4],n=(15&d)<<2,c=2;break;case 2:o[a++]=r[n|d>>6],o[a++]=r[63&d],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=r[n],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var i="invalid encoding";t.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c<e.length;){var d=e.charCodeAt(c++);if(61===d&&a>1)break;if(void 0===(d=s[d]))throw Error(i);switch(a){case 0:n=d,a=1;break;case 1:t[r++]=n<<2|(48&d)>>4,n=d,a=2;break;case 2:t[r++]=(15&n)<<4|(60&d)>>2,n=d,a=3;break;case 3:t[r++]=(3&n)<<6|d,a=0}}if(1===a)throw Error(i);return r-o},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(Qo)),Qo),s.EventEmitter=function(){if(Wo)return Vo;function e(){this._listeners=Object.create(null)}return Wo=1,Vo=e,e.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},e.prototype.off=function(e,t){if(void 0===e)this._listeners=Object.create(null);else if(void 0===t)this._listeners[e]=[];else{var r=this._listeners[e];if(!r)return this;for(var s=0;s<r.length;)r[s].fn===t?r.splice(s,1):++s}return this},e.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var r=[],s=1;s<arguments.length;)r.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,r)}return this},Vo}(),s.float=function(){if(Zo)return Jo;function e(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),s=128===r[3];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3]}function i(e,s,n){t[0]=e,s[n]=r[3],s[n+1]=r[2],s[n+2]=r[1],s[n+3]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],t[0]}function a(e,s){return r[3]=e[s],r[2]=e[s+1],r[1]=e[s+2],r[0]=e[s+3],t[0]}e.writeFloatLE=s?n:i,e.writeFloatBE=s?i:n,e.readFloatLE=s?o:a,e.readFloatBE=s?a:o}():function(){function i(e,t,r,s){var n=t<0?1:0;if(n&&(t=-t),0===t)e(1/t>0?0:2147483648,r,s);else if(isNaN(t))e(2143289344,r,s);else if(t>34028234663852886e22)e((n<<31|2139095040)>>>0,r,s);else if(t<11754943508222875e-54)e((n<<31|Math.round(t/1401298464324817e-60))>>>0,r,s);else{var i=Math.floor(Math.log(t)/Math.LN2);e((n<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,s)}}function o(e,t,r){var s=e(t,r),n=2*(s>>31)+1,i=s>>>23&255,o=8388607&s;return 255===i?o?NaN:n*(1/0):0===i?1401298464324817e-60*n*o:n*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=i.bind(null,t),e.writeFloatBE=i.bind(null,r),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,n)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),s=128===r[7];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3],s[n+4]=r[4],s[n+5]=r[5],s[n+6]=r[6],s[n+7]=r[7]}function i(e,s,n){t[0]=e,s[n]=r[7],s[n+1]=r[6],s[n+2]=r[5],s[n+3]=r[4],s[n+4]=r[3],s[n+5]=r[2],s[n+6]=r[1],s[n+7]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],r[4]=e[s+4],r[5]=e[s+5],r[6]=e[s+6],r[7]=e[s+7],t[0]}function a(e,s){return r[7]=e[s],r[6]=e[s+1],r[5]=e[s+2],r[4]=e[s+3],r[3]=e[s+4],r[2]=e[s+5],r[1]=e[s+6],r[0]=e[s+7],t[0]}e.writeDoubleLE=s?n:i,e.writeDoubleBE=s?i:n,e.readDoubleLE=s?o:a,e.readDoubleBE=s?a:o}():function(){function i(e,t,r,s,n,i){var o=s<0?1:0;if(o&&(s=-s),0===s)e(0,n,i+t),e(1/s>0?0:2147483648,n,i+r);else if(isNaN(s))e(0,n,i+t),e(2146959360,n,i+r);else if(s>17976931348623157e292)e(0,n,i+t),e((o<<31|2146435072)>>>0,n,i+r);else{var a;if(s<22250738585072014e-324)e((a=s/5e-324)>>>0,n,i+t),e((o<<31|a/4294967296)>>>0,n,i+r);else{var c=Math.floor(Math.log(s)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=s*Math.pow(2,-c))>>>0,n,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,n,i+r)}}}function o(e,t,r,s,n){var i=e(s,n+t),o=e(s,n+r),a=2*(o>>31)+1,c=o>>>20&2047,d=4294967296*(1048575&o)+i;return 2047===c?d?NaN:a*(1/0):0===c?5e-324*a*d:a*Math.pow(2,c-1075)*(d+4503599627370496)}e.writeDoubleLE=i.bind(null,t,0,4),e.writeDoubleBE=i.bind(null,r,4,0),e.readDoubleLE=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,n,4,0)}(),e}function t(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function r(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function n(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return Zo=1,Jo=e(e)}(),s.utf8=(Yo||(Yo=1,r=65533,(t=sa).length=function(e){for(var t=0,r=0,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(s+1))?(++s,t+=4):t+=3;return t},t.read=function(e,t,s){if(s-t<1)return"";for(var n,i,o,a,c=null,d=[],u=0;t<s;)(n=e[t++])<=127?d[u++]=n:n>=192&&n<224?(o=(31&n)<<6|63&e[t++],d[u++]=o>=128?o:r):n>=224&&n<240?(a=(15&n)<<12|(63&e[t++])<<6|63&e[t++],d[u++]=a>=2048?a:r):n>=240&&((i=(7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])<65536||i>1114111?d[u++]=r:(i-=65536,d[u++]=55296+(i>>10),d[u++]=56320+(1023&i))),u>8191&&((c||(c=[])).push(String.fromCharCode.apply(String,d.slice(0,u))),u=0);return c?(u&&c.push(String.fromCharCode.apply(String,d.slice(0,u))),c.join("")):String.fromCharCode.apply(String,d.slice(0,u))},t.write=function(e,t,r){for(var s,n,i=r,o=0;o<e.length;++o)(s=e.charCodeAt(o))<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(o+1)))?(s=65536+((1023&s)<<10)+(1023&n),++o,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-i}),sa),s.pool=ea?Xo:(ea=1,Xo=function(e,t,r){var s=r||8192,n=s>>>1,i=null,o=s;return function(r){if(r<1||r>n)return e(r);o+r>s&&(i=e(s),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),a}}),s.LongBits=function(){if(ra)return ta;ra=1,ta=t;var e=ga();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var s=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return r;var s=e<0;s&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return s&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new t(n,i)},t.from=function(s){if("number"==typeof s)return t.fromNumber(s);if(e.isString(s)){if(!e.Long)return t.fromNumber(parseInt(s,10));s=e.Long.fromString(s)}return s.low||s.high?new t(s.low>>>0,s.high>>>0):r},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return t.fromHash=function(e){return e===s?r:new t((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10},ta}(),s.isUnsafeProperty=n,s.isNode=Boolean(void 0!==qo&&qo&&qo.process&&qo.process.versions&&qo.process.versions.node),s.global=s.isNode&&qo||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||zo,s.emptyArray=Object.freeze?Object.freeze([]):[],s.emptyObject=Object.freeze?Object.freeze({}):{},s.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},s.isString=function(e){return"string"==typeof e||e instanceof String},s.isObject=function(e){return e&&"object"==typeof e},s.isset=s.isSet=function(e,t){var r=e[t];return!(null==r||!Object.hasOwnProperty.call(e,t))&&("object"!=typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},s.Buffer=function(){try{var e=s.global.Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),s._Buffer_from=null,s._Buffer_allocUnsafe=null,s.newBuffer=function(e){return"number"==typeof e?s.Buffer?s._Buffer_allocUnsafe(e):new s.Array(e):s.Buffer?s._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},s.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,s.Long=s.global.dcodeIO&&s.global.dcodeIO.Long||s.global.Long||function(){try{var e=fa();return e&&e.isLong?e:null}catch(t){return null}}(),s.key2Re=/^true|false|0|1$/,s.key32Re=/^-?(?:0|[1-9][0-9]*)$/,s.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,s.longToHash=function(e){return e?s.LongBits.from(e).toHash():s.LongBits.zeroHash},s.longFromHash=function(e,t){var r=s.LongBits.fromHash(e);return s.Long?s.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},s.merge=i,s.nestingLimit=32,s.recursionLimit=100,s.makeProp=function(e,t){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,writable:!0})},s.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},s.newError=o,s.ProtocolError=o("ProtocolError"),s.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;r>-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},s.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},s.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},s._configure=function(){var e=s.Buffer;e?(s._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},s._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):s._Buffer_from=s._Buffer_allocUnsafe=null}}(zo)),zo}function ya(){if(aa)return oa;aa=1,oa=c;var e,t=ga(),r=t.LongBits,s=t.base64,n=t.utf8;function i(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function o(){}function a(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function c(){this.len=0,this.head=new i(o,0,0),this.tail=this.head,this.states=null}var d=function(){return t.Buffer?function(){return(c.create=function(){return new e})()}:function(){return new c}};function u(e,t,r){t[r]=255&e}function l(e,t){this.len=e,this.next=void 0,this.val=t}function h(e,t,r){for(var s=e.lo,n=e.hi;n;)t[r++]=127&s|128,s=(s>>>7|n<<25)>>>0,n>>>=7;for(;s>127;)t[r++]=127&s|128,s>>>=7;t[r++]=s}function p(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}c.create=d(),c.alloc=function(e){return new t.Array(e)},t.Array!==Array&&(c.alloc=t.pool(c.alloc,t.Array.prototype.subarray)),c.prototype._push=function(e,t,r){return this.tail=this.tail.next=new i(e,t,r),this.len+=t,this},l.prototype=Object.create(i.prototype),l.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},c.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new l((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},c.prototype.int32=function(e){return(e|=0)<0?this._push(h,10,r.fromNumber(e)):this.uint32(e)},c.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},c.prototype.uint64=function(e){var t=r.from(e);return this._push(h,t.length(),t)},c.prototype.int64=c.prototype.uint64,c.prototype.sint64=function(e){var t=r.from(e).zzEncode();return this._push(h,t.length(),t)},c.prototype.bool=function(e){return this._push(u,1,e?1:0)},c.prototype.fixed32=function(e){return this._push(p,4,e>>>0)},c.prototype.sfixed32=c.prototype.fixed32,c.prototype.fixed64=function(e){var t=r.from(e);return this._push(p,4,t.lo)._push(p,4,t.hi)},c.prototype.sfixed64=c.prototype.fixed64,c.prototype.float=function(e){return this._push(t.float.writeFloatLE,4,e)},c.prototype.double=function(e){return this._push(t.float.writeDoubleLE,8,e)};var m=t.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var s=0;s<e.length;++s)t[r+s]=e[s]};return c.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(u,1,0);if(t.isString(e)){var n=c.alloc(r=s.length(e));s.decode(e,n,0),e=n}return this.uint32(r)._push(m,r,e)},c.prototype.string=function(e){var t=n.length(e);return t?this.uint32(t)._push(n.write,t,e):this._push(u,1,0)},c.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new i(o,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new i(o,0,0),this.len=0),this},c.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},c.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},c._configure=function(t){e=t,c.create=d(),e._configure()},oa}function va(){if(la)return ua;la=1,ua=i;var e,t=ga(),r=t.LongBits,s=t.utf8;function n(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function i(e){this.buf=e,this.pos=0,this.len=e.length}var o="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new i(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new i(e);throw Error("illegal buffer")},a=function(){return t.Buffer?function(r){return(i.create=function(r){return t.Buffer.isBuffer(r)?new e(r):o(r)})(r)}:o};function c(){var e=new r(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw n(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw n(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function u(){if(this.pos+8>this.len)throw n(this,8);return new r(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}return i.create=a(),i.prototype._slice=t.Array.prototype.subarray||t.Array.prototype.slice,i.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,n(this,10);return e}}(),i.prototype.int32=function(){return 0|this.uint32()},i.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},i.prototype.bool=function(){return 0!==this.uint32()},i.prototype.fixed32=function(){if(this.pos+4>this.len)throw n(this,4);return d(this.buf,this.pos+=4)},i.prototype.sfixed32=function(){if(this.pos+4>this.len)throw n(this,4);return 0|d(this.buf,this.pos+=4)},i.prototype.float=function(){if(this.pos+4>this.len)throw n(this,4);var e=t.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},i.prototype.double=function(){if(this.pos+8>this.len)throw n(this,4);var e=t.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},i.prototype.bytes=function(){var e=this.uint32(),r=this.pos,s=this.pos+e;if(s>this.len)throw n(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,s);if(r===s){var i=t.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,s)},i.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},i.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw n(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw n(this)}while(128&this.buf[this.pos++]);return this},i.recursionLimit=t.recursionLimit,i.prototype.skipType=function(e,t){if(void 0===t&&(t=0),t>i.recursionLimit)throw Error("maximum nesting depth exceeded");switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e,t+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},i._configure=function(r){e=r,i.create=a(),e._configure();var s=t.Long?"toLong":"toNumber";t.merge(i.prototype,{int64:function(){return c.call(this)[s](!1)},uint64:function(){return c.call(this)[s](!0)},sint64:function(){return c.call(this).zzDecode()[s](!1)},fixed64:function(){return u.call(this)[s](!0)},sfixed64:function(){return u.call(this)[s](!1)}})},ua}var ba,Ia,wa,Ca,Sa,Ta,_a={};function Ra(){return wa||(wa=1,_a.Service=function(){if(Ia)return ba;Ia=1,ba=t;var e=ga();function t(t,r,s){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");e.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(r),this.responseDelimited=Boolean(s)}return(t.prototype=Object.create(e.EventEmitter.prototype)).constructor=t,t.prototype.rpcCall=function t(r,s,n,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return e.asPromise(t,a,r,s,n,i);if(a.rpcImpl)try{return a.rpcImpl(r,s[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(e,t){if(e)return a.emit("error",e,r),o(e);if(null!==t){if(!(t instanceof n))try{t=n[a.responseDelimited?"decodeDelimited":"decode"](t)}catch(s){return a.emit("error",s,r),o(s)}return a.emit("data",t,r),o(null,t)}a.end(!0)})}catch(c){return a.emit("error",c,r),void setTimeout(function(){o(c)},0)}else setTimeout(function(){o(Error("already ended"))},0)},t.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},ba}()),_a}function Aa(){return Sa?Ca:(Sa=1,Ca=Object.create(null))}function Ma(){return Ta||(Ta=1,function(e){var t=e;function r(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=ya(),t.BufferWriter=function(){if(da)return ca;da=1,ca=r;var e=ya();(r.prototype=Object.create(e.prototype)).constructor=r;var t=ga();function r(){e.call(this)}function s(e,r,s){e.length<40?t.utf8.write(e,r,s):r.utf8Write?r.utf8Write(e,s):r.write(e,s)}return r._configure=function(){r.alloc=t._Buffer_allocUnsafe,r.writeBytesBuffer=t.Buffer&&t.Buffer.prototype instanceof Uint8Array&&"set"===t.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var s=0;s<e.length;)t[r++]=e[s++]}},r.prototype.bytes=function(e){t.isString(e)&&(e=t._Buffer_from(e,"base64"));var s=e.length>>>0;return this.uint32(s),s&&this._push(r.writeBytesBuffer,s,e),this},r.prototype.string=function(e){var r=t.Buffer.byteLength(e);return this.uint32(r),r&&this._push(s,r,e),this},r._configure(),ca}(),t.Reader=va(),t.BufferReader=function(){if(pa)return ha;pa=1,ha=r;var e=va();(r.prototype=Object.create(e.prototype)).constructor=r;var t=ga();function r(t){e.call(this,t)}return r._configure=function(){t.Buffer&&(r.prototype._slice=t.Buffer.prototype.slice)},r.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},r._configure(),ha}(),t.util=ga(),t.rpc=Ra(),t.roots=Aa(),t.configure=r,r()}(jo)),jo}var Ea,Ua,Na={},ka={exports:{}};function Oa(){if(Ua)return Ea;Ua=1,Ea=t;var e=/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/;function t(r,s){"string"==typeof r&&(s=r,r=void 0);var n=[];function i(e){if("string"!=typeof e){var r=o();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var s=Object.keys(e),a=new Array(s.length+1),c=new Array(s.length),d=0;d<s.length;)a[d]=s[d],c[d]=e[s[d++]];return a[d]=r,Function.apply(null,a).apply(null,c)}return Function(r)()}for(var u=new Array(arguments.length-1),l=0;l<u.length;)u[l]=arguments[++l];if(l=0,e=e.replace(/%([%dfijs])/g,function(e,t){var r=u[l++];switch(t){case"d":case"f":return String(Number(r));case"i":return String(Math.floor(r));case"j":return JSON.stringify(r);case"s":return String(r)}return"%"}),l!==u.length)throw Error("parameter count mismatch");return n.push(e),i}function o(t){return"function "+function(t){if(!t)return"";if(!(t=String(t).replace(/[^\w$]/g,"")))return"";/^\d/.test(t)&&(t="_"+t);return e.test(t)?t+"_":t}(t||s)+"("+(r&&r.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return i.toString=o,i}return t.verbose=!1,Ea}const xa=Bo(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var La,Pa,Da,qa;function Ba(){if(qa)return Da;qa=1,Da=r;var e=Ko(),t=function(){if(Pa)return La;Pa=1;var e=null;try{(e=xa)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return La=e}();function r(s,n,i){return"function"==typeof n?(i=n,n={}):n||(n={}),i?!n.xhr&&t&&t.readFile?t.readFile(s,function(e,t){return e&&"undefined"!=typeof XMLHttpRequest?r.xhr(s,n,i):e?i(e):i(null,n.binary?t:t.toString("utf8"))}):r.xhr(s,n,i):e(r,this,s,n)}return r.xhr=function(e,t,r){var s=new XMLHttpRequest;s.onreadystatechange=function(){if(4===s.readyState){if(0!==s.status&&200!==s.status)return r(Error("status "+s.status));if(t.binary){var e=s.response;if(!e){e=[];for(var n=0;n<s.responseText.length;++n)e.push(255&s.responseText.charCodeAt(n))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,s.responseText)}},t.binary&&("overrideMimeType"in s&&s.overrideMimeType("text/plain; charset=x-user-defined"),s.responseType="arraybuffer"),s.open("GET",e),s.send()},Da}var $a,Fa={};var Ga,ja,za,Ka,Ha,Va,Wa,Ja,Za,Qa,Ya,Xa,ec,tc,rc,sc,nc,ic={};function oc(){if(Ha)return Ka;Ha=1,Ka=c;var e=zc();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=Gc(),i=$c(),o=jc();function a(e,t){if(e&&e.length){for(var r={},s=0;s<e.length;++s)r[e[s].name]=e[s].toJSON(t);return r}}function c(t,r){e.call(this,t,r),this.nested=void 0,this._nestedArray=null,this._lookupCache=Object.create(null),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function d(e){e._nestedArray=null,e._lookupCache=Object.create(null);for(var t=e;t=t.parent;)t._lookupCache=Object.create(null);return e}return c.fromJSON=function(e,t,r){return r=i.checkDepth(r),new c(e,t.options).addJSON(t.nested,r)},c.arrayToJSON=a,c.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},c.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(c.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=i.toArray(this.nested))}}),c.prototype.toJSON=function(e){return i.toObject(["options",this.options,"nested",a(this.nestedArray,e)])},c.prototype.addJSON=function(e,o){o=i.checkDepth(o);if(e)for(var a,d=Object.keys(e),u=0;u<d.length;++u)a=e[d[u]],this.add((void 0!==a.fields?t.fromJSON:void 0!==a.values?s.fromJSON:void 0!==a.methods?r.fromJSON:void 0!==a.id?n.fromJSON:c.fromJSON)(d[u],a,o+1));return this},c.prototype.get=function(e){return this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)?this.nested[e]:null},c.prototype.getEnum=function(e){if(this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)&&this.nested[e]instanceof s)return this.nested[e].values;throw Error("no such enum: "+e)},c.prototype.add=function(e){if(!(e instanceof n&&void 0!==e.extend||e instanceof t||e instanceof o||e instanceof s||e instanceof r||e instanceof c))throw TypeError("object must be a valid nested object");if("__proto__"===e.name)return this;if(this.nested){var i=this.get(e.name);if(i){if(!(i instanceof c&&e instanceof c)||i instanceof t||i instanceof r)throw Error("duplicate name '"+e.name+"' in "+this);for(var a=i.nestedArray,u=0;u<a.length;++u)e.add(a[u]);this.remove(i),this.nested||(this.nested={}),e.setOptions(i.options,!0)}}else this.nested={};this.nested[e.name]=e,this instanceof t||this instanceof r||this instanceof s||this instanceof n||e._edition||(e._edition=e._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var l=this;l=l.parent;)l._needsRecursiveFeatureResolution=!0,l._needsRecursiveResolve=!0;return e.onAdd(this),d(this)},c.prototype.remove=function(t){if(!(t instanceof e))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=void 0),t.onRemove(this),d(this)},c.prototype.define=function(e,t){if(i.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");if(e.length>i.recursionLimit)throw Error("max depth exceeded");for(var r=this;e.length>0;){var s=e.shift();if(r.nested&&r.nested[s]){if(!((r=r.nested[s])instanceof c))throw Error("path conflicts with non-namespace objects")}else r.add(r=new c(s))}return t&&r.addJSON(t),r},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var e=this.nestedArray,t=0;for(this.resolve();t<e.length;)e[t]instanceof c?e[t++].resolveAll():e[t++].resolve();return this._needsRecursiveResolve=!1,this},c.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.nestedArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},c.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),i.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;var s=e.join(".");if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+s];if(n&&(!t||t.indexOf(n.constructor)>-1))return n;if((n=this._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;if(r)return null;for(var o=this;o.parent;){if((n=o.parent._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;o=o.parent}return null},c.prototype._lookupImpl=function(e,t){if(Object.prototype.hasOwnProperty.call(this._lookupCache,t))return this._lookupCache[t];var r=this.get(e[0]),s=null;if(r)1===e.length?s=r:r instanceof c&&(e=e.slice(1),s=r._lookupImpl(e,e.join(".")));else for(var n=0;n<this.nestedArray.length;++n)if(this._nestedArray[n]instanceof c&&(r=this._nestedArray[n]._lookupImpl(e,t))){s=r;break}return this._lookupCache[t]=s,s},c.prototype.lookupType=function(e){var r=this.lookup(e,[t]);if(!r)throw Error("no such type: "+e);return r},c.prototype.lookupEnum=function(e){var t=this.lookup(e,[s]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},c.prototype.lookupTypeOrEnum=function(e){var r=this.lookup(e,[t,s]);if(!r)throw Error("no such Type or Enum '"+e+"' in "+this);return r},c.prototype.lookupService=function(e){var t=this.lookup(e,[r]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},c._configure=function(e,n,i){t=e,r=n,s=i},Ka}function ac(){if(Wa)return Va;Wa=1,Va=s;var e=Gc();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=Fc(),r=$c();function s(t,s,n,i,o,a){if(e.call(this,t,s,i,void 0,void 0,o,a),!r.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}return s.fromJSON=function(e,t){return new s(e,t.id,t.keyType,t.type,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},s.prototype.resolve=function(){if(this.resolved)return this;if(void 0===t.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return e.prototype.resolve.call(this)},s.d=function(e,t,n){return"function"==typeof n?n=r.decorateType(n).name:n&&"object"==typeof n&&(n=r.decorateEnum(n).name),function(i,o){r.decorateType(i.constructor).add(new s(o,e,t,n))}},Va}function cc(){if(Za)return Ja;Za=1,Ja=r;var e=zc();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=$c();function r(r,s,n,i,o,a,c,d,u){if(t.isObject(o)?(c=o,o=a=void 0):t.isObject(a)&&(c=a,a=void 0),void 0!==s&&!t.isString(s))throw TypeError("type must be a string");if(!t.isString(n))throw TypeError("requestType must be a string");if(!t.isString(i))throw TypeError("responseType must be a string");e.call(this,r,c),this.type=s||"rpc",this.requestType=n,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=d,this.parsedOptions=u}return r.fromJSON=function(e,t){return new r(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},r.prototype.toJSON=function(e){var r=!!e&&Boolean(e.keepComments);return t.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",r?this.comment:void 0,"parsedOptions",this.parsedOptions])},r.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),e.prototype.resolve.call(this))},Ja}function dc(){if(Ya)return Qa;Ya=1,Qa=n;var e=oc();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=cc(),r=$c(),s=Ra();function n(t,r){e.call(this,t,r),this.methods={},this._methodsArray=null}function i(e){return e._methodsArray=null,e}return n.fromJSON=function(e,s,i){i=r.checkDepth(i);var o=new n(e,s.options);if(s.methods)for(var a=Object.keys(s.methods),c=0;c<a.length;++c)o.add(t.fromJSON(a[c],s.methods[a[c]]));return s.nested&&o.addJSON(s.nested,i),s.edition&&(o._edition=s.edition),o.comment=s.comment,o._defaultEdition="proto3",o},n.prototype.toJSON=function(t){var s=e.prototype.toJSON.call(this,t),n=!!t&&Boolean(t.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",s&&s.options||void 0,"methods",e.arrayToJSON(this.methodsArray,t)||{},"nested",s&&s.nested||void 0,"comment",n?this.comment:void 0])},Object.defineProperty(n.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=r.toArray(this.methods))}}),n.prototype.get=function(t){return Object.prototype.hasOwnProperty.call(this.methods,t)?this.methods[t]:e.prototype.get.call(this,t)},n.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolve.call(this);for(var t=this.methodsArray,r=0;r<t.length;++r)t[r].resolve();return this},n.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.methodsArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},n.prototype.add=function(r){if(this.get(r.name))throw Error("duplicate name '"+r.name+"' in "+this);return r instanceof t?"__proto__"===r.name?this:(this.methods[r.name]=r,r.parent=this,i(this)):e.prototype.add.call(this,r)},n.prototype.remove=function(r){if(r instanceof t){if(this.methods[r.name]!==r)throw Error(r+" is not a member of "+this);return delete this.methods[r.name],r.parent=null,i(this)}return e.prototype.remove.call(this,r)},n.prototype.create=function(e,t,n){for(var i,o=new s.Service(e,t,n),a=0;a<this.methodsArray.length;++a){o[r.lcFirst((i=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"")]=function(e,t,r){return function(n,i){return s.Service.prototype.rpcCall.call(this,e,t,r,n,i)}}(i,i.resolvedRequestType.ctor,i.resolvedResponseType.ctor)}return o},Qa}function uc(){if(ec)return Xa;ec=1,Xa=t;var e=ga();function t(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r){var s=t[r];"__proto__"!==s&&(this[s]=e[s])}}return t.create=function(e){return this.$type.create(e)},t.encode=function(e,t){return this.$type.encode(e,t)},t.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},t.decode=function(e){return this.$type.decode(e)},t.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},t.verify=function(e){return this.$type.verify(e)},t.fromObject=function(e){return this.$type.fromObject(e)},t.toObject=function(e,t){return this.$type.toObject(e,t)},t.prototype.toJSON=function(){return this.$type.toObject(this,e.toJSONOptions)},Xa}function lc(){if(rc)return tc;rc=1,tc=function(n){for(var i=r.codegen(["r","l","e","n"],n.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("if(n===undefined)n=0")("if(n>Reader.recursionLimit)")('throw Error("maximum nesting depth exceeded")')("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(n.fieldsArray.filter(function(e){return e.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),o=0;o<n.fieldsArray.length;++o){var a=n._fieldsArray[o].resolve(),c=a.resolvedType instanceof e?"int32":a.type,d="m"+r.safeProp(a.name);i("case %i: {",a.id),a.map?(i("if(%s===util.emptyObject)",d)("%s={}",d)("var c2 = r.uint32()+r.pos"),void 0!==t.defaults[a.keyType]?i("k=%j",t.defaults[a.keyType]):i("k=null"),void 0!==t.defaults[c]?i("value=%j",t.defaults[c]):i("value=null"),i("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===t.basic[c]?i("value=types[%i].decode(r,r.uint32(),undefined,n+1)",o):i("value=r.%s()",c),i("break")("default:")("r.skipType(tag2&7,n)")("break")("}")("}"),void 0!==t.long[a.keyType]?i('%s[typeof k==="object"?util.longToHash(k):k]=value',d):("string"===a.keyType&&i('if(k==="__proto__")')("util.makeProp(%s,k)",d),i("%s[k]=value",d))):a.repeated?(i("if(!(%s&&%s.length))",d,d)("%s=[]",d),void 0!==t.packed[c]&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",d,c)("}else"),void 0===t.basic[c]?i(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4),n+1))":"%s.push(types[%i].decode(r,r.uint32(),undefined,n+1))",d,o):i("%s.push(r.%s())",d,c)):void 0===t.basic[c]?i(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4),n+1)":"%s=types[%i].decode(r,r.uint32(),undefined,n+1)",d,o):i("%s=r.%s()",d,c),i("break")("}")}for(i("default:")("r.skipType(t&7,n)")("break")("}")("}"),o=0;o<n._fieldsArray.length;++o){var u=n._fieldsArray[o];u.required&&i("if(!Object.hasOwnProperty.call(m,%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",s(u))}return i("return m")};var e=Kc(),t=Fc(),r=$c();function s(e){return"missing required '"+e.name+"'"}return tc}function hc(){if(nc)return sc;nc=1,sc=function(e){var i=t.codegen(["m","n"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")("return%j","maximum nesting depth exceeded"),o=e.oneofsArray,a={};o.length&&i("var p={}");for(var c=0;c<e.fieldsArray.length;++c){var d=e._fieldsArray[c].resolve(),u="m"+t.safeProp(d.name);if(d.optional&&i("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",u,d.name),d.map)i("if(!util.isObject(%s))",u)("return%j",r(d,"object"))("var k=Object.keys(%s)",u)("for(var i=0;i<k.length;++i){"),n(i,d,"k[i]"),s(i,d,c,u+"[k[i]]")("}");else if(d.repeated)i("if(!Array.isArray(%s))",u)("return%j",r(d,"array"))("for(var i=0;i<%s.length;++i){",u),s(i,d,c,u+"[i]")("}");else{if(d.partOf){var l=t.safeProp(d.partOf.name);1===a[d.partOf.name]&&i("if(p%s===1)",l)("return%j",d.partOf.name+": multiple values"),a[d.partOf.name]=1,i("p%s=1",l)}s(i,d,c,u)}d.optional&&i("}")}return i("return null")};var e=Kc(),t=$c();function r(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function s(t,s,n,i){if(s.resolvedType)if(s.resolvedType instanceof e){t("switch(%s){",i)("default:")("return%j",r(s,"enum value"));for(var o=Object.keys(s.resolvedType.values),a=0;a<o.length;++a)t("case %i:",s.resolvedType.values[o[a]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s,n+1);",n,i)("if(e)")("return%j+e",s.name+".")("}");else switch(s.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",i)("return%j",r(s,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",r(s,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",r(s,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",r(s,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",r(s,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",r(s,"buffer"))}return t}function n(e,t,s){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",s)("return%j",r(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",s)("return%j",r(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",s)("return%j",r(t,"boolean key"))}return e}return sc}var pc,mc={};function fc(){return pc||(pc=1,function(e){var t=e,r=Kc(),s=$c();function n(e,t,s,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof r){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c<a.length;++c)o[a[c]]!==t.typeDefault||i||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),i=!0),e("case%j:",a[c])("case %i:",o[a[c]])("m%s=%j",n,o[a[c]])("break");e("}")}else e("if(!util.isObject(d%s))",n)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s,n+1)",n,s,n);else{var d=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",n,n);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":case"fixed64":d=!0;case"int64":case"sint64":case"sfixed64":e("if(util.Long)")("m%s=util.Long.fromValue(d%s,%j)",n,n,d)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,d?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function i(e,t,s,n){if(t.resolvedType)t.resolvedType instanceof r?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,s,n,n,s,n,n):e("d%s=types[%i].toObject(m%s,o,q+1)",n,s,n);else{var i=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":case"fixed64":i=!0;case"int64":case"sint64":case"sfixed64":e('if(typeof BigInt!=="undefined"&&o.longs===BigInt)')('d%s=typeof m%s==="number"?BigInt(m%s):util.Long.fromBits(m%s.low>>>0,m%s.high>>>0,%j).toBigInt()',n,n,n,n,n,i)('else if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,i?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}t.fromObject=function(e){var t=e.fieldsArray,i=s.codegen(["d","n"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return i("return new this.ctor");i("if(!util.isObject(d))")("throw TypeError(%j)",e.fullName+": object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")('throw Error("maximum nesting depth exceeded")'),i("var m=new this.ctor");for(var o=0;o<t.length;++o){var a=t[o].resolve(),c=s.safeProp(a.name);a.map?(i("if(d%s){",c)("if(!util.isObject(d%s))",c)("throw TypeError(%j)",a.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),i('if(ks[i]==="__proto__")')("util.makeProp(m%s,ks[i])",c),n(i,a,o,c+"[ks[i]]")("}")("}")):a.repeated?(i("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),n(i,a,o,c+"[i]")("}")("}")):(a.resolvedType instanceof r||i("if(d%s!=null){",c),n(i,a,o,c),a.resolvedType instanceof r||i("}"))}return i("return m")},t.toObject=function(e){var t=e.fieldsArray.slice().sort(s.compareFieldsById);if(!t.length)return s.codegen()("return {}");for(var n=s.codegen(["m","o","q"],e.name+"$toObject")("if(!o)")("o={}")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")')("var d={}"),o=[],a=[],c=[],d=0;d<t.length;++d)t[d].partOf||(t[d].resolve().repeated?o:t[d].map?a:c).push(t[d]);if(o.length){for(n("if(o.arrays||o.defaults){"),d=0;d<o.length;++d)n("d%s=[]",s.safeProp(o[d].name));n("}")}if(a.length){for(n("if(o.objects||o.defaults){"),d=0;d<a.length;++d)n("d%s={}",s.safeProp(a[d].name));n("}")}if(c.length){for(n("if(o.defaults){"),d=0;d<c.length;++d){var u=c[d],l=s.safeProp(u.name);if(u.resolvedType instanceof r)n("d%s=o.enums===String?%j:%j",l,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)('d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():typeof BigInt!=="undefined"&&o.longs===BigInt?n.toBigInt():n',l)("}else")('d%s=o.longs===String?%j:typeof BigInt!=="undefined"&&o.longs===BigInt?BigInt(%j):%i',l,u.typeDefault.toString(),u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var h=Array.prototype.slice.call(u.typeDefault);n("if(o.bytes===String)d%s=%j",l,String.fromCharCode.apply(String,u.typeDefault))("else{")("d%s=%j",l,h)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",l,l)("}")}else n("d%s=%j",l,u.typeDefault)}n("}")}var p=!1;for(d=0;d<t.length;++d){u=t[d];var m=e._fieldsArray.indexOf(u);l=s.safeProp(u.name);u.map?(p||(p=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",l,l)("d%s={}",l)("for(var j=0;j<ks2.length;++j){"),n('if(ks2[j]==="__proto__")')("util.makeProp(d%s,ks2[j])",l),i(n,u,m,l+"[ks2[j]]")("}")):u.repeated?(n("if(m%s&&m%s.length){",l,l)("d%s=[]",l)("for(var j=0;j<m%s.length;++j){",l),i(n,u,m,l+"[j]")("}")):(n("if(m%s!=null&&Object.hasOwnProperty.call(m,%j)){",l,u.name),i(n,u,m,l),u.partOf&&n("if(o.oneofs)")("d%s=%j",s.safeProp(u.partOf.name),u.name)),n("}")}return n("return d")}}(mc)),mc}var gc,yc,vc,bc,Ic,wc,Cc,Sc,Tc,_c,Rc,Ac,Mc,Ec,Uc,Nc,kc,Oc,xc,Lc,Pc={};function Dc(){return gc||(gc=1,e=Pc,t=uc(),r=ga(),e[".google.protobuf.Any"]={fromObject:function(e,t){if(e&&e["@type"]){var r=e["@type"].substring(e["@type"].lastIndexOf("/")+1),s=this.lookup(r);if(s){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:s.encode(s.fromObject(e,void 0===t?1:t+1)).finish()})}}return this.fromObject(e,t)},toObject:function(e,s,n){if(void 0===n&&(n=0),n>r.recursionLimit)throw Error("max depth exceeded");var i="",o="";if(s&&s.json&&e.type_url&&e.value){o=e.type_url.substring(e.type_url.lastIndexOf("/")+1),i=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var a=this.lookup(o);a&&(e=a.decode(e.value,void 0,void 0,n+1))}if(!(e instanceof this.ctor)&&e instanceof t){var c=e.$type.toObject(e,s,n+1);return""===i&&(i="type.googleapis.com/"),o=i+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),c["@type"]=o,c}return this.toObject(e,s,n)}}),Pc;var e,t,r}function qc(){if(vc)return yc;vc=1,yc=f;var e=oc();((f.prototype=Object.create(e.prototype)).constructor=f).className="Type";var t=Kc(),r=jc(),s=Gc(),n=ac(),i=dc(),o=uc(),a=va(),c=ya(),d=$c(),u=Hc(),l=lc(),h=hc(),p=fc(),m=Dc();function f(t,r){t=t.replace(/\W/g,""),e.call(this,t,r),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function g(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}return Object.defineProperties(f.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],s=r.id;if(this._fieldsById[s])throw Error("duplicate id "+s+" in "+this);this._fieldsById[s]=r}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=f.generateConstructor(this)())},set:function(e){var t=e.prototype;t instanceof o||((e.prototype=new o).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,o,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var s={};for(r=0;r<this.oneofsArray.length;++r)s[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,s)}}}),f.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),s=0;s<e.fieldsArray.length;++s)(t=e._fieldsArray[s]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r('if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null&&ks[i]!=="__proto__")')("this[ks[i]]=p[ks[i]]")},f.fromJSON=function(o,a,c){if(void 0===c&&(c=0),c>d.nestingLimit)throw Error("max depth exceeded");var u=new f(o,a.options);u.extensions=a.extensions,u.reserved=a.reserved;for(var l=Object.keys(a.fields),h=0;h<l.length;++h)u.add((void 0!==a.fields[l[h]].keyType?n.fromJSON:s.fromJSON)(l[h],a.fields[l[h]]));if(a.oneofs)for(l=Object.keys(a.oneofs),h=0;h<l.length;++h)u.add(r.fromJSON(l[h],a.oneofs[l[h]]));if(a.nested)for(l=Object.keys(a.nested),h=0;h<l.length;++h){var p=a.nested[l[h]];u.add((void 0!==p.id?s.fromJSON:void 0!==p.fields?f.fromJSON:void 0!==p.values?t.fromJSON:void 0!==p.methods?i.fromJSON:e.fromJSON)(l[h],p,c+1))}return a.extensions&&a.extensions.length&&(u.extensions=a.extensions),a.reserved&&a.reserved.length&&(u.reserved=a.reserved),a.group&&(u.group=!0),a.comment&&(u.comment=a.comment),a.edition&&(u._edition=a.edition),u._defaultEdition="proto3",u},f.prototype.toJSON=function(t){var r=e.prototype.toJSON.call(this,t),s=!!t&&Boolean(t.keepComments);return d.toObject(["edition",this._editionToJSON(),"options",r&&r.options||void 0,"oneofs",e.arrayToJSON(this.oneofsArray,t),"fields",e.arrayToJSON(this.fieldsArray.filter(function(e){return!e.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",r&&r.nested||void 0,"comment",s?this.comment:void 0])},f.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolveAll.call(this);var t=this.oneofsArray;for(s=0;s<t.length;)t[s++].resolve();for(var r=this.fieldsArray,s=0;s<r.length;)r[s++].resolve();return this},f.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.oneofsArray.forEach(e=>{e._resolveFeatures(t)}),this.fieldsArray.forEach(e=>{e._resolveFeatures(t)}),this):this},f.prototype.get=function(e){return Object.prototype.hasOwnProperty.call(this.fields,e)?this.fields[e]:this.oneofs&&Object.prototype.hasOwnProperty.call(this.oneofs,e)?this.oneofs[e]:this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)?this.nested[e]:null},f.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof s&&void 0===t.extend){if(this._fieldsById?this._fieldsById[t.id]:this.fieldsById[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name)||"$"===t.name.charAt(0))throw Error("name '"+t.name+"' is reserved in "+this);return"__proto__"===t.name?this:(t.parent&&t.parent.remove(t),this.fields[t.name]=t,t.message=this,t.onAdd(this),g(this))}if(t instanceof r){if("$"===t.name.charAt(0))throw Error("name '"+t.name+"' is reserved in "+this);return"__proto__"===t.name?this:(this.oneofs||(this.oneofs={}),this.oneofs[t.name]=t,t.onAdd(this),g(this))}return e.prototype.add.call(this,t)},f.prototype.remove=function(t){if(t instanceof s&&void 0===t.extend){if(!this.fields||this.fields[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.fields[t.name],t.parent=null,t.onRemove(this),g(this)}if(t instanceof r){if(!this.oneofs||this.oneofs[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),g(this)}return e.prototype.remove.call(this,t)},f.prototype.isReservedId=function(t){return e.isReservedId(this.reserved,t)},f.prototype.isReservedName=function(t){return e.isReservedName(this.reserved,t)},f.prototype.create=function(e){return new this.ctor(e)},f.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this._fieldsArray[r].resolve().resolvedType);this.encode=u(this)({Writer:c,types:t,util:d}),this.decode=l(this)({Reader:a,types:t,util:d}),this.verify=h(this)({types:t,util:d}),this.fromObject=p.fromObject(this)({types:t,util:d}),this.toObject=p.toObject(this)({types:t,util:d});var s=m[e];if(s){var n=Object.create(this);n.fromObject=this.fromObject,this.fromObject=s.fromObject.bind(n),n.toObject=this.toObject,this.toObject=s.toObject.bind(n)}return this},f.prototype.encode=function(e,t){return this.setup().encode.apply(this,arguments)},f.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},f.prototype.decode=function(e,t,r,s){return this.setup().decode(e,t,r,s)},f.prototype.decodeDelimited=function(e){return e instanceof a||(e=a.create(e)),this.decode(e,e.uint32())},f.prototype.verify=function(e,t){return this.setup().verify(e,t)},f.prototype.fromObject=function(e,t){return this.setup().fromObject(e,t)},f.prototype.toObject=function(e,t){return this.setup().toObject.apply(this,arguments)},f.d=function(e){return function(t){d.decorateType(t,e)}},yc}function Bc(){if(Ic)return bc;Ic=1,bc=c;var e=oc();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=Gc(),i=Kc(),o=jc(),a=$c();function c(t){e.call(this,"",t),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}function d(){}c.fromJSON=function(e,t,r){return r=a.checkDepth(r),t||(t=new c),e.options&&t.setOptions(e.options),t.addJSON(e.nested,r).resolveAll()},c.prototype.resolvePath=a.path.resolve,c.prototype.fetch=a.fetch,c.prototype.load=function e(t,n,i){"function"==typeof n&&(i=n,n=void 0);var o=this;if(!i)return a.asPromise(e,o,t,n);var c=i===d;function u(e,t){if(i){if(c)throw e;t&&t.resolveAll();var r=i;i=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in s)return r}return null}function h(e,t,s){void 0===s&&(s=0);try{if(s>a.recursionLimit)throw Error("max depth exceeded");if(a.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),a.isString(t)){r.filename=e;var i,d=r(t,o,n),h=0;if(d.imports)for(;h<d.imports.length;++h)(i=l(d.imports[h])||o.resolvePath(e,d.imports[h]))&&p(i,!1,s+1);if(d.weakImports)for(h=0;h<d.weakImports.length;++h)(i=l(d.weakImports[h])||o.resolvePath(e,d.weakImports[h]))&&p(i,!0,s+1)}else o.setOptions(t.options).addJSON(t.nested)}catch(f){u(f)}c||m||u(null,o)}function p(e,t,r){if(void 0===r&&(r=0),e=l(e)||e,!(o.files.indexOf(e)>-1))if(o.files.push(e),e in s)c?h(e,s[e],r):(++m,setTimeout(function(){--m,h(e,s[e],r)}));else if(c){var n;try{n=a.fs.readFileSync(e).toString("utf8")}catch(d){return void(t||u(d))}h(e,n,r)}else++m,o.fetch(e,function(s,n){--m,i&&(s?t?m||u(null,o):u(s):h(e,n,r))})}var m=0;a.isString(t)&&(t=[t]);for(var f,g=0;g<t.length;++g)(f=o.resolvePath("",t[g]))&&p(f);return c?(o.resolveAll(),o):(m||u(null,o),o)},c.prototype.loadSync=function(e,t){if(!a.isNode)throw Error("not supported");return this.load(e,t,d)},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return e.prototype.resolveAll.call(this)};var u=/^[A-Z]/;function l(e,t){var r=t.parent.lookup(t.extend);if(r){var s=new n(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(s.name)||(s.declaringField=t,t.extensionField=s,r.add(s)),!0}return!1}return c.prototype._handleAdd=function(e){if(e instanceof n)void 0===e.extend||e.extensionField||l(0,e)||this.deferred.push(e);else if(e instanceof i)u.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof o)){if(e instanceof t)for(var r=0;r<this.deferred.length;)l(0,this.deferred[r])?this.deferred.splice(r,1):++r;for(var s=0;s<e.nestedArray.length;++s)this._handleAdd(e._nestedArray[s]);u.test(e.name)&&(e.parent[e.name]=e)}(e instanceof t||e instanceof i||e instanceof n)&&(this._fullyQualifiedObjects[e.fullName]=e)},c.prototype._handleRemove=function(t){if(t instanceof n){if(void 0!==t.extend)if(t.extensionField)t.extensionField.parent.remove(t.extensionField),t.extensionField=null;else{var r=this.deferred.indexOf(t);r>-1&&this.deferred.splice(r,1)}}else if(t instanceof i)u.test(t.name)&&delete t.parent[t.name];else if(t instanceof e){for(var s=0;s<t.nestedArray.length;++s)this._handleRemove(t._nestedArray[s]);u.test(t.name)&&delete t.parent[t.name]}delete this._fullyQualifiedObjects[t.fullName]},c._configure=function(e,n,i){t=e,r=n,s=i},bc}function $c(){if(wc)return ka.exports;wc=1;var e,t,r,s,n,i,o=ka.exports=ga(),a=Aa();o.codegen=Oa(),o.fetch=Ba(),o.path=($a||($a=1,s=(r=Fa).isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},n=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=s(e),n="";r&&(n=t.shift()+"/");for(var i=0;i<t.length;)".."===t[i]?i>0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return n+t.join("/")},r.resolve=function(e,t,r){return r||(t=n(t)),s(t)?t:(r||(e=n(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?n(e+"/"+t):t)}),Fa),o.patterns=(Ga||(Ga=1,(i=ic).numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,i.typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,i.reservedRe=/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/),ic);var c=o.patterns.reservedRe;o.fs=function(){if(za)return ja;za=1;var e=null;try{(e=xa)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return ja=e}(),o.checkDepth=function(e){if(void 0===e&&(e=0),e>o.recursionLimit)throw Error("max depth exceeded");return e},o.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),s=0;s<t.length;)r[s]=e[t[s++]];return r}return[]},o.toObject=function(e){for(var t={},r=0;r<e.length;){var s=e[r++],n=e[r++];void 0!==n&&(t[s]=n)}return t},o.isReserved=function(e){return c.test(e)},o.safeProp=function(e){return!/^[$\w_]+$/.test(e)||c.test(e)?"["+JSON.stringify(e)+"]":"."+e},o.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var d=/_([a-z])/g;o.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(d,function(e,t){return t.toUpperCase()})},o.compareFieldsById=function(e,t){return e.id-t.id},o.decorateType=function(t,r){if(t.$type)return r&&t.$type.name!==r&&(o.decorateRoot.remove(t.$type),t.$type.name=r,o.decorateRoot.add(t.$type)),t.$type;e||(e=qc());var s=new e(r||t.name);return o.decorateRoot.add(s),s.ctor=t,Object.defineProperty(t,"$type",{value:s,enumerable:!1}),Object.defineProperty(t.prototype,"$type",{value:s,enumerable:!1}),s};var u=0;return o.decorateEnum=function(e){if(e.$type)return e.$type;t||(t=Kc());var r=new t("Enum"+u++,e);return o.decorateRoot.add(r),Object.defineProperty(e,"$type",{value:r,enumerable:!1}),r},o.setProperty=function(e,t,r,s){if("object"!=typeof e)throw TypeError("dst must be an object");if(!t)throw TypeError("path must be specified");if((t=t.split(".")).length>o.recursionLimit)throw Error("max depth exceeded");return function e(t,r,n){var i=r.shift();if(o.isUnsafeProperty(i))return t;if(r.length>0)t[i]=e(t[i]||{},r,n);else{var a=t[i];if(a&&s)return t;a&&(n=[].concat(a).concat(n)),t[i]=n}return t}(e,t,r)},Object.defineProperty(o,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(Bc()))}}),ka.exports}function Fc(){return Cc||(Cc=1,function(e){var t=e,r=$c(),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function n(e,t){var r=0,n=Object.create(null);for(t|=0;r<e.length;)n[s[r+t]]=e[r++];return n}t.basic=n([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),t.defaults=n([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",r.emptyArray,null]),t.long=n([0,0,0,1,1],7),t.mapKey=n([0,0,0,5,5,0,0,0,1,1,0,2],2),t.packed=n([1,5,0,0,0,5,5,0,0,0,1,1,0])}(Na)),Na}function Gc(){if(Tc)return Sc;Tc=1,Sc=o;var e=zc();((o.prototype=Object.create(e.prototype)).constructor=o).className="Field";var t,r=Kc(),s=Fc(),n=$c(),i=/^required|optional|repeated$/;function o(t,r,o,a,c,d,u){if(n.isObject(a)?(u=c,d=a,a=c=void 0):n.isObject(c)&&(u=d,d=c,c=void 0),e.call(this,t,d),!n.isInteger(r)||r<0)throw TypeError("id must be a non-negative integer");if(!n.isString(o))throw TypeError("type must be a string");if(void 0!==a&&!i.test(a=a.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==c&&!n.isString(c))throw TypeError("extend must be a string");"proto3_optional"===a&&(a="optional"),this.rule=a&&"optional"!==a?a:void 0,this.type=o,this.id=r,this.extend=c||void 0,this.repeated="repeated"===a,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!n.Long&&void 0!==s.long[o],this.bytes="bytes"===o,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=u}return o.fromJSON=function(e,t){var r=new o(e,t.id,t.type,t.rule,t.extend,t.options,t.comment);return t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},Object.defineProperty(o.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this._features.field_presence}}),Object.defineProperty(o.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(o.prototype,"delimited",{get:function(){return this.resolvedType instanceof t&&"DELIMITED"===this._features.message_encoding}}),Object.defineProperty(o.prototype,"packed",{get:function(){return"PACKED"===this._features.repeated_field_encoding}}),Object.defineProperty(o.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this._features.field_presence)}}),o.prototype.setOption=function(t,r,s){return e.prototype.setOption.call(this,t,r,s)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return n.toObject(["edition",this._editionToJSON(),"rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=s.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof t?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof r&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof r||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=n.Long.fromNumber(this.typeDefault,"uint64"===this.type||"fixed64"===this.type),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var i;n.base64.test(this.typeDefault)?n.base64.decode(this.typeDefault,i=n.newBuffer(n.base64.length(this.typeDefault)),0):n.utf8.write(this.typeDefault,i=n.newBuffer(n.utf8.length(this.typeDefault)),0),this.typeDefault=i}return this.map?this.defaultValue=n.emptyObject:this.repeated?this.defaultValue=n.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof t&&(this.parent.ctor.prototype[this.name]=this.defaultValue),e.prototype.resolve.call(this)},o.prototype._inferLegacyProtoFeatures=function(e){if("proto2"!==e&&"proto3"!==e)return{};var r={};if("required"===this.rule&&(r.field_presence="LEGACY_REQUIRED"),this.parent&&void 0===s.defaults[this.type]){var n=this.parent.get(this.type.split(".").pop());n&&n instanceof t&&n.group&&(r.message_encoding="DELIMITED")}return!0===this.getOption("packed")?r.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(r.repeated_field_encoding="EXPANDED"),r},o.prototype._resolveFeatures=function(t){return e.prototype._resolveFeatures.call(this,this._edition||t)},o.d=function(e,t,r,s){return"function"==typeof t?t=n.decorateType(t).name:t&&"object"==typeof t&&(t=n.decorateEnum(t).name),function(i,a){n.decorateType(i.constructor).add(new o(a,e,t,r,{default:s}))}},o._configure=function(e){t=e},Sc}function jc(){if(Rc)return _c;Rc=1,_c=s;var e=zc();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=Gc(),r=$c();function s(t,r,s,n){if(Array.isArray(r)||(s=r,r=void 0),e.call(this,t,s),void 0!==r&&!Array.isArray(r))throw TypeError("fieldNames must be an Array");this.oneof=r||[],this.fieldsArray=[],this.comment=n}function n(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}return s.fromJSON=function(e,t){return new s(e,t.oneof,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},s.prototype.add=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),e.partOf=this,n(this),this},s.prototype.remove=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");var r=this.fieldsArray.indexOf(e);if(r<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(r,1),(r=this.oneof.indexOf(e.name))>-1&&this.oneof.splice(r,1),e.partOf=null,this},s.prototype.onAdd=function(t){e.prototype.onAdd.call(this,t);for(var r=0;r<this.oneof.length;++r){var s=t.get(this.oneof[r]);s&&!s.partOf&&(s.partOf=this,this.fieldsArray.push(s))}n(this)},s.prototype.onRemove=function(t){for(var r,s=0;s<this.fieldsArray.length;++s)(r=this.fieldsArray[s]).parent&&r.parent.remove(r);e.prototype.onRemove.call(this,t)},Object.defineProperty(s.prototype,"isProto3Optional",{get:function(){if(null==this.fieldsArray||1!==this.fieldsArray.length)return!1;var e=this.fieldsArray[0];return null!=e.options&&!0===e.options.proto3_optional}}),s.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,n){r.decorateType(t.constructor).add(new s(n,e)),Object.defineProperty(t,n,{get:r.oneOfGetter(e),set:r.oneOfSetter(e)})}},_c}function zc(){if(Mc)return Ac;Mc=1,Ac=o,o.className="ReflectionObject";const e=jc();var t,r=$c(),s={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},n={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},i={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function o(e,t){if(!r.isString(e))throw TypeError("name must be a string");if(t&&!r.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}return Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var r=e.root;r instanceof t&&r._handleAdd(this)},o.prototype.onRemove=function(e){var r=e.root;r instanceof t&&r._handleRemove(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof t&&(this.resolved=!0),this},o.prototype._resolveFeaturesRecursive=function(e){return this._resolveFeatures(this._edition||e)},o.prototype._resolveFeatures=function(t){if(!this._featuresResolved){var o={};if(!t)throw new Error("Unknown edition for "+this.fullName);var a=r.merge({},this.options&&this.options.features,this._inferLegacyProtoFeatures(t));if(this._edition){if("proto2"===t)o=Object.assign({},n);else if("proto3"===t)o=Object.assign({},i);else{if("2023"!==t)throw new Error("Unknown edition: "+t);o=Object.assign({},s)}return this._features=r.merge(o,a),void(this._featuresResolved=!0)}if(this.partOf instanceof e){var c=r.merge({},this.partOf._features);this._features=r.merge(c,a)}else if(this.declaringField);else{if(!this.parent)throw new Error("Unable to find a parent for "+this.fullName);var d=r.merge({},this.parent._features);this._features=r.merge(d,a)}this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},o.prototype._inferLegacyProtoFeatures=function(){return{}},o.prototype.getOption=function(e){if(this.options)return this.options[e]},o.prototype.setOption=function(e,t,s){return"__proto__"===e||(this.options||(this.options={}),/^features\./.test(e)?r.setProperty(this.options,e,t,s):s&&void 0!==this.options[e]||(this.getOption(e)!==t&&(this.resolved=!1),this.options[e]=t)),this},o.prototype.setParsedOption=function(e,t,s){if("__proto__"===e)return this;this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(s){var i=n.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)});if(i){var o=i[e];r.setProperty(o,s,t)}else(i={})[e]=r.setProperty({},s,t),n.push(i)}else{var a={};a[e]=t,n.push(a)}return this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),s=0;s<r.length;++s)this.setOption(r[s],e[r[s]],t);return this},o.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},o.prototype._editionToJSON=function(){if(this._edition&&"proto3"!==this._edition)return this._edition},o._configure=function(e){t=e},Ac}function Kc(){if(Uc)return Ec;Uc=1,Ec=s;var e=zc();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=oc(),r=$c();function s(t,r,s,n,i,o){if(e.call(this,t,s),r&&"object"!=typeof r)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=n,this.comments=i||{},this.valuesOptions=o,this._valuesFeatures={},this.reserved=void 0,r)for(var a=Object.keys(r),c=0;c<a.length;++c)"__proto__"!==a[c]&&"number"==typeof r[a[c]]&&(this.valuesById[this.values[a[c]]=r[a[c]]]=a[c])}return s.prototype._resolveFeatures=function(t){return t=this._edition||t,e.prototype._resolveFeatures.call(this,t),Object.keys(this.values).forEach(e=>{var t=r.merge({},this._features);this._valuesFeatures[e]=r.merge(t,this.valuesOptions&&this.valuesOptions[e]&&this.valuesOptions[e].features||{})}),this},s.fromJSON=function(e,t){var r=new s(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},s.prototype.add=function(e,t,s,n){if(!r.isString(e))throw TypeError("name must be a string");if(!r.isInteger(t))throw TypeError("id must be an integer");if("__proto__"===e)return this;if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=s||null,this},s.prototype.remove=function(e){if(!r.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},s.prototype.isReservedId=function(e){return t.isReservedId(this.reserved,e)},s.prototype.isReservedName=function(e){return t.isReservedName(this.reserved,e)},Ec}function Hc(){if(kc)return Nc;kc=1,Nc=function(n){for(var i,o=r.codegen(["m","w","q"],n.name+"$encode")("if(!w)")("w=Writer.create()")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")'),a=n.fieldsArray.slice().sort(r.compareFieldsById),c=0;c<a.length;++c){var d=a[c].resolve(),u=n._fieldsArray.indexOf(d),l=d.resolvedType instanceof e?"int32":d.type,h=t.basic[l];i="m"+r.safeProp(d.name),d.map?(o("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",i,d.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",i)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(d.id<<3|2)>>>0,8|t.mapKey[d.keyType],d.keyType),void 0===h?o("types[%i].encode(%s[ks[i]],w.uint32(18).fork(),q+1).ldelim().ldelim()",u,i):o(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|h,l,i),o("}")("}")):d.repeated?(o("if(%s!=null&&%s.length){",i,i),d.packed&&void 0!==t.packed[l]?o("w.uint32(%i).fork()",(d.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",l,i)("w.ldelim()"):(o("for(var i=0;i<%s.length;++i)",i),void 0===h?s(o,d,u,i+"[i]"):o("w.uint32(%i).%s(%s[i])",(d.id<<3|h)>>>0,l,i)),o("}")):(d.optional&&o("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,d.name),void 0===h?s(o,d,u,i):o("w.uint32(%i).%s(%s)",(d.id<<3|h)>>>0,l,i))}return o("return w")};var e=Kc(),t=Fc(),r=$c();function s(e,t,r,s){return t.delimited?e("types[%i].encode(%s,w.uint32(%i),q+1).uint32(%i)",r,s,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork(),q+1).ldelim()",r,s,(t.id<<3|2)>>>0)}return Nc}var Vc=Lc?xc:(Lc=1,xc=function(){if(Oc)return Go.exports;Oc=1;var e=Go.exports=Ma();return e.build="light",e.load=function(t,r,s){return"function"==typeof r?(s=r,r=new e.Root):r||(r=new e.Root),r.load(t,s)},e.loadSync=function(t,r){return r||(r=new e.Root),r.loadSync(t)},e.encoder=Hc(),e.decoder=lc(),e.verifier=hc(),e.converter=fc(),e.ReflectionObject=zc(),e.Namespace=oc(),e.Root=Bc(),e.Enum=Kc(),e.Type=qc(),e.Field=Gc(),e.OneOf=jc(),e.MapField=ac(),e.Service=dc(),e.Method=cc(),e.Message=uc(),e.wrappers=Dc(),e.types=Fc(),e.util=$c(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),Go.exports}());const Wc={nested:{easemob:{nested:{pb:{nested:{MessageBody:{fields:{type:{type:"Type",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},contents:{rule:"repeated",type:"Content",id:4},ext:{rule:"repeated",type:"KeyValue",id:5},ackMessageId:{type:"uint64",id:6},msgConfig:{type:"MessageConfig",id:7},ackContent:{type:"string",id:8},meta:{type:"string",id:9},editMessageId:{type:"uint64",id:11},editScope:{type:"EditScope",id:12},stream:{type:"Stream",id:13},userInfoUpdateTime:{type:"int32",id:14},namecardUpdateTime:{type:"int32",id:15},sendToPeer:{type:"bool",id:16},ackMessageIds:{rule:"repeated",type:"uint64",id:17},clearAllUnreadMessageCount:{type:"bool",id:18}},nested:{Content:{fields:{type:{type:"Type",id:1},text:{type:"string",id:2},latitude:{type:"double",id:3},longitude:{type:"double",id:4},address:{type:"string",id:5},displayName:{type:"string",id:6},remotePath:{type:"string",id:7},secretKey:{type:"string",id:8},fileLength:{type:"int32",id:9},action:{type:"string",id:10},params:{rule:"repeated",type:"KeyValue",id:11},duration:{type:"int32",id:12},size:{type:"Size",id:13},thumbnailRemotePath:{type:"string",id:14},thumbnailSecretKey:{type:"string",id:15},thumbnailDisplayName:{type:"string",id:16},thumbnailFileLength:{type:"int32",id:17},thumbnailSize:{type:"Size",id:18},customEvent:{type:"string",id:19},customExts:{rule:"repeated",type:"KeyValue",id:20},buildingName:{type:"string",id:21},subType:{type:"SubType",id:22},title:{type:"string",id:23},summary:{type:"string",id:24},combineLevel:{type:"int32",id:25},imageType:{type:"int32",id:26}},nested:{Type:{values:{TEXT:0,IMAGE:1,VIDEO:2,LOCATION:3,VOICE:4,FILE:5,COMMAND:6,CUSTOM:7,COMBINE:8}},Size:{fields:{width:{type:"double",id:1},height:{type:"double",id:2}}},SubType:{values:{COMBINE:0,GIF:1,SUB_STREAM:10}}}},Type:{values:{NORMAL:0,CHAT:1,GROUPCHAT:2,CHATROOM:3,READ_ACK:4,DELIVER_ACK:5,RECALL:6,CHANNEL_ACK:7,EDIT:8}},EditScope:{values:{BODY:1,BODY_AND_EXT:2}},MessageConfig:{fields:{allowGroupAck:{type:"bool",id:1}}},Stream:{fields:{streamType:{type:"string",id:1},streamSeq:{type:"uint64",id:2},streamStatus:{type:"StreamStatus",id:3},streamError:{type:"uint32",id:4},streamFinishReason:{type:"int32",id:5}},nested:{StreamStatus:{values:{STREAM_START:0,STREAM_START_COMPLETED:1,STREAM_IN_PROGRESS:2,STREAM_COMPLETED:3,STREAM_FULL:4}}}}}},KeyValue:{oneofs:{value:{oneof:["varintValue","floatValue","doubleValue","stringValue"]}},fields:{key:{type:"string",id:1},type:{type:"ValueType",id:2},varintValue:{type:"int64",id:3},floatValue:{type:"float",id:4},doubleValue:{type:"double",id:5},stringValue:{type:"string",id:6}},nested:{ValueType:{values:{BOOL:1,INT:2,UINT:3,LLINT:4,FLOAT:5,DOUBLE:6,STRING:7,JSON_STRING:8}}}},JID:{fields:{appKey:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},clientResource:{type:"string",id:4}}},ConferenceBody:{fields:{sessionId:{type:"string",id:1},operation:{type:"Operation",id:2},conferenceId:{type:"string",id:3},type:{type:"Type",id:4},content:{type:"string",id:5},network:{type:"string",id:6},version:{type:"string",id:7},identity:{type:"Identity",id:8},duration:{type:"string",id:9},peerName:{type:"string",id:10},endReason:{type:"EndReason",id:11},status:{type:"Status",id:12},isDirect:{type:"bool",id:13},controlType:{type:"StreamControlType",id:14},routeFlag:{type:"int32",id:15},routeKey:{type:"string",id:16}},nested:{Status:{fields:{errorCode:{type:"int32",id:1}}},Operation:{values:{JOIN:0,INITIATE:1,ACCEPT_INITIATE:2,ANSWER:3,TERMINATE:4,REMOVE:5,STREAM_CONTROL:6,MEDIA_REQUEST:7}},Type:{values:{VOICE:0,VIDEO:1}},Identity:{values:{CALLER:0,CALLEE:1}},EndReason:{values:{HANGUP:0,NORESPONSE:1,REJECT:2,BUSY:3,FAIL:4,UNSUPPORTED:5,OFFLINE:6}},StreamControlType:{values:{PAUSE_VOICE:0,RESUME_VOICE:1,PAUSE_VIDEO:2,RESUME_VIDEO:3}}}},MSync:{fields:{version:{type:"Version",id:1,options:{default:"MSYNC_V1"}},guid:{type:"JID",id:2},auth:{type:"string",id:3},compressAlgorimth:{type:"uint32",id:4},crypto:{type:"uint32",id:5},userAgent:{type:"string",id:6},pov:{type:"uint64",id:7},command:{type:"Command",id:8},deviceId:{type:"uint32",id:10},encryptType:{rule:"repeated",type:"EncryptType",id:11,options:{packed:!1}},encryptKey:{type:"string",id:12},payload:{type:"bytes",id:9},traceId:{type:"uint64",id:20}},nested:{Version:{values:{MSYNC_V1:0,MSYNC_V2:1}},Command:{values:{SYNC:0,UNREAD:1,NOTICE:2,PROVISION:3,LOGOUT:4}}}},EncryptType:{values:{ENCRYPT_NONE:0,ENCRYPT_AES_128_CBC:1,ENCRYPT_AES_256_CBC:2}},CommSyncUL:{fields:{meta:{type:"Meta",id:1},key:{type:"uint64",id:2},queue:{type:"JID",id:3},isRoam:{type:"bool",id:4},lastFullRoamKey:{type:"uint64",id:5}}},CommSyncDL:{fields:{status:{type:"Status",id:1},metaId:{type:"uint64",id:2},serverId:{type:"uint64",id:3},metas:{rule:"repeated",type:"Meta",id:4},nextKey:{type:"uint64",id:5},queue:{type:"JID",id:6},isLast:{type:"bool",id:7},timestamp:{type:"uint64",id:8},isRoam:{type:"bool",id:9}}},CommNotice:{fields:{queue:{type:"JID",id:1}}},CommUnreadUL:{fields:{}},CommUnreadDL:{fields:{status:{type:"Status",id:1},unread:{rule:"repeated",type:"MetaQueue",id:2},timestamp:{type:"uint64",id:3}}},MetaQueue:{fields:{queue:{type:"JID",id:1},n:{type:"uint32",id:2}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},timestamp:{type:"uint64",id:4},ns:{type:"NameSpace",id:5},payload:{type:"bytes",id:6},routetype:{type:"RouteType",id:7},ext:{rule:"repeated",type:"KeyValue",id:8},meta:{type:"bytes",id:9},directedUsers:{rule:"repeated",type:"string",id:10},env:{type:"string",id:13}},nested:{NameSpace:{values:{STATISTIC:0,CHAT:1,MUC:2,ROSTER:3,CONFERENCE:4,NOTIFY:5,QUERY:6}},RouteType:{values:{ROUTE_ALL:0,ROUTE_ONLINE:1,ROUTE_DIRECT:2}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},reason:{type:"string",id:2},redirectInfo:{rule:"repeated",type:"RedirectInfo",id:3}},nested:{ErrorCode:{values:{OK:0,FAIL:1,UNAUTHORIZED:2,MISSING_PARAMETER:3,WRONG_PARAMETER:4,REDIRECT:5,TOKEN_EXPIRED:6,PERMISSION_DENIED:7,NO_ROUTE:8,UNKNOWN_COMMAND:9,PB_PARSER_ERROR:10,BIND_ANOTHER_DEVICE:11,IM_FORBIDDEN:12,TOO_MANY_DEVICES:13,PLATFORM_LIMIT:14,USER_MUTED:15,ENCRYPT_DISABLE:16,ENCRYPT_ENABLE:17,DECRYPT_FAILURE:18,PERMISSION_DENIED_EXTERNAL:19}}}},RedirectInfo:{fields:{host:{type:"string",id:1},port:{type:"uint32",id:2}}},Provision:{fields:{osType:{type:"OsType",id:1},version:{type:"string",id:2},networkType:{type:"NetworkType",id:3},appSign:{type:"string",id:4},compressType:{rule:"repeated",type:"CompressType",id:5,options:{packed:!1}},encryptType:{rule:"repeated",type:"EncryptType",id:6,options:{packed:!1}},encryptKey:{type:"string",id:7},status:{type:"Status",id:8},deviceUuid:{type:"string",id:9},isManualLogin:{type:"bool",id:10},password:{type:"string",id:11},deviceName:{type:"string",id:12},resource:{type:"string",id:13},auth:{type:"string",id:14},serviceId:{type:"string",id:16},actionVersion:{type:"string",id:17},authToken:{type:"string",id:18},osCustomValue:{type:"uint32",id:19},sessionId:{type:"string",id:20},reason:{type:"string",id:21},protocolCompressType:{rule:"repeated",type:"CompressType",id:22},protocolCompressDirection:{type:"CompressDirection",id:23}},nested:{OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}},CompressType:{values:{COMPRESS_NONE:0,COMPRESS_ZLIB:1,COMPRESS_LZ4:2}},CompressDirection:{values:{ONLY_UP:0,ONLY_DOWN:1,BI:2}}}},Logout:{fields:{sessionId:{type:"string",id:1},reason:{type:"string",id:2},status:{type:"Status",id:3}}},MUCBody:{fields:{mucId:{type:"JID",id:1},operation:{type:"Operation",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},setting:{type:"Setting",id:5},reason:{type:"string",id:6},isChatroom:{type:"bool",id:7},status:{type:"Status",id:8},isThread:{type:"bool",id:9},mucParentId:{type:"JID",id:10},mucName:{type:"string",id:11},eventInfo:{type:"EventInfo",id:12},mucMemberCount:{type:"int32",id:13},ext:{type:"string",id:14},leaveOtherRooms:{type:"bool",id:15},members:{rule:"repeated",type:"string",id:16}},nested:{Operation:{values:{CREATE:0,DESTROY:1,JOIN:2,LEAVE:3,APPLY:4,APPLY_ACCEPT:5,APPLY_DECLINE:6,INVITE:7,INVITE_ACCEPT:8,INVITE_DECLINE:9,KICK:10,GET_BLACKLIST:11,BAN:12,ALLOW:13,UPDATE:14,BLOCK:15,UNBLOCK:16,PRESENCE:17,ABSENCE:18,DIRECT_JOINED:19,ASSIGN_OWNER:20,ADD_ADMIN:21,REMOVE_ADMIN:22,ADD_MUTE:23,REMOVE_MUTE:24,UPDATE_ANNOUNCEMENT:25,DELETE_ANNOUNCEMENT:26,UPLOAD_FILE:27,DELETE_FILE:28,ADD_USER_WHITE_LIST:29,REMOVE_USER_WHITE_LIST:30,BAN_GROUP:31,REMOVE_BAN_GROUP:32,THREAD_CREATE:33,THREAD_DESTROY:34,THREAD_JOIN:35,THREAD_LEAVE:36,THREAD_KICK:37,THREAD_UPDATE:38,THREAD_PRESENCE:39,THREAD_ABSENCE:40,DISABLE_GROUP:41,ABLE_GROUP:42,SET_METADATA:43,DELETE_METADATA:44,GROUP_MEMBER_METADATA_UPDATE:45}},Setting:{fields:{name:{type:"string",id:1},desc:{type:"string",id:2},type:{type:"Type",id:3},maxUsers:{type:"int32",id:4},owner:{type:"string",id:5}},nested:{Type:{values:{PRIVATE_OWNER_INVITE:0,PRIVATE_MEMBER_INVITE:1,PUBLIC_JOIN_APPROVAL:2,PUBLIC_JOIN_OPEN:3,PUBLIC_ANONYMOUS:4}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2},chatroomInfo:{type:"string",id:3}},nested:{ErrorCode:{values:{OK:0,PERMISSION_DENIED:1,WRONG_PARAMETER:2,MUC_NOT_EXIST:3,USER_NOT_EXIST:4,UNKNOWN:5}}}},EventInfo:{fields:{eventType:{type:"EventType",id:1,options:{default:"EVENT_NONE"}},ext:{type:"string",id:2}},nested:{EventType:{values:{EVENT_NONE:0,CIRCLE_CHANNEL:1}}}}}},RosterBody:{fields:{operation:{type:"Operation",id:1},status:{type:"Status",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},reason:{type:"string",id:5},rosterVer:{type:"string",id:6},biDirection:{type:"bool",id:7}},nested:{Operation:{values:{GET_ROSTER:0,GET_BLACKLIST:1,ADD:2,REMOVE:3,ACCEPT:4,DECLINE:5,BAN:6,ALLOW:7,REMOTE_ACCEPT:8,REMOTE_DECLINE:9}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2}},nested:{ErrorCode:{values:{OK:0,USER_NOT_EXIST:1,USER_ALREADY_FRIEND:2,USER_ALREADY_BLACKLIST:3}}}}}},StatisticsBody:{fields:{operation:{type:"Operation",id:1},os:{type:"OsType",id:2},version:{type:"string",id:3},network:{type:"NetworkType",id:4},imTime:{type:"uint32",id:5},chatTime:{type:"uint32",id:6},location:{type:"string",id:7},reason:{type:"string",id:10}},nested:{Operation:{values:{INFORMATION:0,USER_REMOVED:1,USER_LOGIN_ANOTHER_DEVICE:2,USER_KICKED_BY_CHANGE_PASSWORD:3,USER_KICKED_BY_OTHER_DEVICE:4}},OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}}}}}}}}}},Jc=e=>{if(!e||0===e.trim().length)throw Fi("Proto type name is required.",{code:$i,stage:Oi,retryable:!1,details:{typeName:e}})};class Zc{constructor(){this.codecMap=new Map}register(e,t){Jc(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:r=>{const s=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw Fi("Proto payload must be an object.",{code:$i,stage:Oi,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(r,e),n=t.fromObject(s);return t.encode(n).finish()},decode:e=>{const r=t.decode(e);return t.toObject(r,{longs:String,enums:Number,defaults:!1})}})}get(e){return Jc(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Fi("Proto codec not found.",{code:$i,stage:Oi,retryable:!1,details:{typeName:e}})}}const Qc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Yc=e=>{class t extends Vc.Message{constructor(e){super(),((e,t)=>{if(t)for(const r of Object.keys(t)){const s=t[r];null!=s&&(e[r]=s)}})(this,e)}}const r=t;return r.$type=e,r.prototype.$type=e,r},Xc=e=>mo.isLong(e),ed=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,td=e=>Object.prototype.hasOwnProperty.call(Vc.types.packed,e),rd=e=>{const t=e.resolve();return t.resolvedType instanceof Vc.Enum||td(t.type)},sd=(e,t)=>t in e?e[t]:void 0,nd=e=>{const t=e.resolve();return t.resolvedType instanceof Vc.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(Vc.types.basic,r)?Vc.types.basic[t.type]:2);var r},id=(e,t)=>Xc(e)||"number"==typeof e||"string"==typeof e?e:Qc(e)&&"number"==typeof e.low&&"number"==typeof e.high?new mo(e.low,e.high,t):t?mo.UZERO:mo.ZERO,od=(e,t,r)=>{switch(t){case"double":return e.double(Number(r));case"float":return e.float(Number(r));case"int32":return e.int32(Number(r));case"uint32":return e.uint32(Number(r));case"sint32":return e.sint32(Number(r));case"fixed32":return e.fixed32(Number(r));case"sfixed32":return e.sfixed32(Number(r));case"int64":return e.int64(id(r,!1));case"uint64":return e.uint64(id(r,!0));case"sint64":return e.sint64(id(r,!1));case"fixed64":return e.fixed64(id(r,!0));case"sfixed64":return e.sfixed64(id(r,!1));case"bool":return e.bool(Boolean(r));case"string":return e.string(String(r));case"bytes":return e.bytes((e=>"string"==typeof e?e:ed(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array)(r));default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}},ad=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},cd=(e,t)=>{const r=e.uint32();return ad(e,r,t),r},ud=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return ad(e,8,r),void e.skip(8);case 2:{const t=cd(e,r);return void e.skip(t)}case 5:return ad(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},ld=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof Vc.Type){const t=e.fork();return pd(n,Qc(r)?r:{},t),t.ldelim(),e}return n instanceof Vc.Enum?(e.int32("number"==typeof r?r:Number(r)),e):od(e,s.type,r)},hd=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(td(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)ld(e,t,s);return e.ldelim(),e}const n=nd(t);for(const i of r)e.uint32(t.id<<3|n),ld(e,t,i);return e},pd=(e,t,r=Vc.Writer.create())=>{const s=e.fieldsArray.slice().sort(Vc.util.compareFieldsById);for(const n of s){const e=sd(t,n.name);null!=e&&(n.repeated?hd(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|nd(n)),ld(r,n,e)))}return r},md=(e,t,r,s)=>{const n=t.resolve(),i=n.resolvedType;return i instanceof Vc.Type?2!==r?void ud(e,r,s):fd(i,e,cd(e,s)):i instanceof Vc.Enum?e.int32():((e,t)=>{switch(t){case"double":return e.double();case"float":return e.float();case"int32":return e.int32();case"uint32":return e.uint32();case"sint32":return e.sint32();case"fixed32":return e.fixed32();case"sfixed32":return e.sfixed32();case"int64":return e.int64();case"uint64":return e.uint64();case"sint64":return e.sint64();case"fixed64":return e.fixed64();case"sfixed64":return e.sfixed64();case"bool":return e.bool();case"string":return e.string();case"bytes":return e.bytes();default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}})(e,n.type)},fd=(e,t,r)=>{const s=t instanceof Vc.Reader?t:Vc.Reader.create(t),n=void 0===r?s.len:s.pos+r,i=(e=>{const t={};for(const r of e.fieldsArray)r.repeated&&(t[r.name]=[]);return t})(e),o=e.fieldsById;for(;s.pos<n;){const t=s.pos,r=s.uint32(),c=o[r>>>3],d=7&r;try{if(!c){ud(s,d,n);continue}if(c.repeated){const e=Array.isArray(i[c.name])?i[c.name]:[];if(rd(c)&&2===d){const t=cd(s,n)+s.pos;for(;s.pos<t;)e.push(md(s,c,0,t))}else{const t=md(s,c,d,n);void 0!==t&&e.push(t)}i[c.name]=e;continue}const e=md(s,c,d,n);void 0!==e&&(i[c.name]=e)}catch(a){if(a instanceof RangeError){const i=c?`${c.name}#${c.id}`:`unknown#${r>>>3}`;throw new RangeError(`${a.message}; protobufType=${e.fullName}; field=${i}; tag=${r}; wireType=${d}; tagPosition=${t}; readerPosition=${s.pos}; messageEnd=${n}`)}throw a}}return i},gd=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,yd=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof Vc.Type)return null;if(r.resolvedType instanceof Vc.Enum){if(t?.enums===String){return r.resolvedType.valuesById[r.typeDefault]??r.typeDefault}return r.typeDefault}return"bytes"===r.type?t?.bytes===String?"":t?.bytes===Array?[]:new Uint8Array:r.long&&Xc(r.typeDefault)?gd(r.typeDefault,t):r.typeDefault},vd=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof Vc.Type?Qc(t)?bd(s.resolvedType,t,r):t:s.resolvedType instanceof Vc.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&Xc(t)?gd(t,r):"bytes"===s.type&&ed(t)?((e,t)=>t?.bytes===String?Vc.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},bd=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(Vc.util.compareFieldsById)){const e=sd(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>vd(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=yd(n,r)):s[n.name]=vd(n,e,r)}return s},Id=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>pd(e,Qc(t)?t:{},r),e.decode=(t,r)=>fd(e,t,r),e.fromObject=e=>Qc(e)?e:{},e.toObject=(t,r)=>bd(e,Qc(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},wd=e=>{Id(e);for(const t of e.nestedArray)if(t instanceof Vc.Type)wd(t);else if(t instanceof Vc.Namespace)for(const e of t.nestedArray)e instanceof Vc.Type&&wd(e)},Cd=e=>{for(const t of e.nestedArray)t instanceof Vc.Type?wd(t):t instanceof Vc.Namespace&&Cd(t)},Sd=()=>{const e=Vc.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>Yc(e),Vc.Type.prototype.setup=function(){return Id(this),this},Vc.Type.prototype.create=function(e){return e?{...e}:{}},Vc.Type.prototype.encode=function(e,t){return pd(this,Qc(e)?e:{},t)},Vc.Type.prototype.decode=function(e,t){return fd(this,e,t)},Vc.Type.prototype.fromObject=function(e){return Qc(e)?e:{}},Vc.Type.prototype.toObject=function(e,t){return bd(this,Qc(e)?e:{},t)},Vc.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let Td=!1,_d=null,Rd=null,Ad=null;const Md=e=>e.startsWith(".")?e.slice(1):e,Ed=e=>e instanceof Vc.Namespace,Ud=e=>e instanceof Vc.Type,Nd=e=>{for(const t of e.nestedArray)Ud(t)?wd(t):Ed(t)&&Nd(t)},kd=()=>{Td||(Vc.util.Long=mo,Vc.configure(),Td=!0),Sd();const e=Vc.Root.fromJSON(Wc);return Nd(e),e},Od=(e,t)=>{const r=e.nestedArray;for(const s of r){if(Ud(s)){const e=Md(s.fullName);wd(s),t.registerType(e,s);continue}Ed(s)&&Od(s,t)}},xd=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return Fi(`Static proto ${r} failed.`,{code:$i,stage:Oi,retryable:!1,details:{typeName:e,operation:r,cause:s}})},Ld=()=>_d||(_d=kd(),_d),Pd=()=>{if(Ad)return Ad;const e=(()=>{if(Rd)return Rd;const e=new Zc,t=Ld();return Od(t,e),Rd=e,e})();return Ad={encode(t,r){try{return e.getOrThrow(Md(t)).encode(r)}catch(s){throw xd(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(Md(t)).decode(r)}catch(s){throw xd(t,s,"decode")}}},Ad},Dd=e=>{const t={};if("function"==typeof e.forEach)return e.forEach((e,r)=>{t[r]=e}),t;const r=e.get?.("content-type");return r&&(t["content-type"]=r),t},qd=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(r){const s=r.method??"GET",n={...r.headers??{}},i=new AbortController,o=r.timeoutMs??e?.timeoutMs??15e3,a=setTimeout(()=>{i.abort()},o),c=((e,t,r)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==r)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(r,n,s);try{const e=await t(r.url,{method:s,headers:n,body:c,signal:r.signal??i.signal});let o;if("arraybuffer"===r.responseType)o=await e.arrayBuffer();else if("text"===r.responseType)o=await e.text();else{const t=e.headers.get("content-type")??"",r=await e.text();o=t.includes("application/json")&&r?JSON.parse(r):r}return{status:e.status,headers:Dd(e.headers),data:o}}catch(d){throw Fi("Request adapter execution failed.",{code:Di,stage:Ui,retryable:!0,details:{url:r.url,method:s,cause:d instanceof Error?d.message:String(d)}})}finally{clearTimeout(a)}}}},Bd=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,$d=e=>"function"==typeof e.on&&"function"==typeof e.off,Fd=(e,t,r)=>{if(Bd(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if($d(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw Fi("Socket event listener API is unsupported.",{code:Bi,stage:ki,retryable:!1,details:{event:t}})},Gd=(e,t,r)=>{if(Bd(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if($d(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=Fd(e,t,(...e)=>{n(),r(...e)}),n}throw Fi("Socket one-time listener API is unsupported.",{code:Bi,stage:ki,retryable:!1,details:{event:t}})},zd=e=>{return"string"==typeof e||(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))||"undefined"!=typeof Blob&&e instanceof Blob?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e&&"object"==typeof e&&"data"in e?zd(e.data):null;var t},Kd=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return Fd(e,"open",()=>{t.forEach(e=>{e()})}),Fd(e,"message",(...e)=>{const t=zd(e[0]);null!==t&&r.forEach(e=>{e(t)})}),Fd(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),Fd(e,"close",(...e)=>{const t=(e=>{const[t,r]=e;if(t&&"object"==typeof t){const e=t;return{code:"number"==typeof e.code?e.code:void 0,reason:"string"==typeof e.reason?e.reason:void 0}}return{code:"number"==typeof t?t:void 0,reason:"string"==typeof r?r:ArrayBuffer.isView(r)?(new TextDecoder).decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)):void 0}})(e);n.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==ji)throw Fi("Socket is not open.",{code:Bi,stage:ki,retryable:!0,details:{readyState:e.readyState}});return e.send(t),Promise.resolve()},close(t,r){e.close(t,r)},onOpen:e=>(t.add(e),()=>{t.delete(e)}),onMessage:e=>(r.add(e),()=>{r.delete(e)}),onError:e=>(s.add(e),()=>{s.delete(e)}),onClose:e=>(n.add(e),()=>{n.delete(e)})}},Hd=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((r,s)=>{let n;try{n=new t(e.url,e.protocols);try{n.binaryType="arraybuffer"}catch{}}catch(l){return void s(Fi("Socket creation failed.",{code:Bi,stage:ki,retryable:!0,details:{cause:l instanceof Error?l.message:String(l)}}))}let i,o=()=>{},a=()=>{},c=!1;const d=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},u=()=>{c||(c=!0,o(),a(),d(),n.close(),s(Fi("Socket connection timed out.",{code:Bi,stage:ki,retryable:!0,details:{url:e.url,reason:"timeout"}})))};o=Gd(n,"open",()=>{c||(c=!0,o(),a(),d(),r(Kd(n)))}),a=Gd(n,"error",e=>{if(c)return;c=!0,o(),a(),d();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;s(Fi("Socket connection failed before open.",{code:Bi,stage:ki,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(u,e.timeoutMs))})}},Vd=(e,t)=>{throw Fi("Upload adapter execution failed.",{code:qi,stage:Ni,retryable:"abort"!==e,details:{reason:e,url:t.url}})},Wd=e=>{const t=new FormData;return Object.entries(e.fields??{}).forEach(([e,r])=>{t.append(e,r)}),((e,t)=>{if("web-file"!==t.source.sourceType)throw Fi("Web upload adapter only supports web-file source.",{code:qi,stage:Ni,retryable:!1,details:{sourceType:t.source.sourceType}});const r=t.source.file;if(!r)throw Fi("Upload source file is required for web-file uploads.",{code:qi,stage:Ni,retryable:!1,details:{sourceType:t.source.sourceType}});const s="undefined"!=typeof Blob&&r instanceof Blob,n=t.source.name??"upload.bin";s?e.append("file",r,n):e.append("file",r)})(t,e),t},Jd=(e,t,r)=>new Promise((s,n)=>{const i=e(),o=r.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const r=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:r})})})(i,r),i.addEventListener("abort",()=>{try{Vd("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{Vd("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{Vd("network",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{s({status:i.status,body:i.responseText})});try{const e=Wd(r);i.timeout=o,i.open("POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,r])=>{e.setRequestHeader(t,r)})})(i,r.headers),i.send(e)}catch(a){n(Fi("Upload adapter execution failed.",{code:qi,stage:Ni,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),Zd=(e,t)=>e?"timeout":"abort",Qd=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,r=e?.fetchImpl;if("function"==typeof t||"function"==typeof r)return{upload(s){if("function"==typeof t)return Jd(t,e,s);if("function"==typeof r)return(async(e,t,r)=>{const s=r.timeoutMs??t?.timeoutMs??3e4;let n=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,o=i&&Number.isFinite(s)?setTimeout(()=>{n=!0,i.abort()},s):void 0,a=((e,t)=>e??t?.signal)(r.signal,i);try{const t=Wd(r),s=await e(r.url,{method:"POST",headers:r.headers,body:t,signal:a}),n=await s.text(),i=r.source.size;return"number"==typeof i&&r.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:s.status,body:n}}catch(c){const e=c instanceof Error&&"AbortError"===c.name;throw Fi("Upload adapter execution failed.",{code:qi,stage:Ni,retryable:!e,details:{reason:e?Zd(n):"network",url:r.url,cause:c instanceof Error?c.message:String(c)}})}finally{o&&clearTimeout(o)}})(r,e,s);throw Fi("Upload adapter execution failed.",{code:qi,stage:Ni,retryable:!1,details:{reason:"missing-upload-runtime",url:s.url}})}}},Yd=(e,t)=>{const r=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append("file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw Fi("React Native upload adapter only supports rn-uri source.",{code:qi,stage:Ni,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),r},Xd=e=>{const t=e?.fetchImpl,r=e?.formDataCtor;if("function"==typeof t&&"function"==typeof r)return{async upload(s){const n=s.timeoutMs??e?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let o=!1;const a=i&&Number.isFinite(n)?setTimeout(()=>{o=!0,i.abort()},n):void 0;try{const e=Yd(r,s),n=await t(s.url,{method:"POST",headers:s.headers,body:e,signal:s.signal??i?.signal}),o=await n.text(),a=s.source.size;return"number"==typeof a&&s.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:n.status,body:o}}catch(c){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===qi&&t.stage===Ni})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw Fi("React Native upload adapter execution failed.",{code:qi,stage:Ni,retryable:!e||o,details:{url:s.url,reason:e?o?"timeout":"abort":"network",cause:c instanceof Error?c.message:String(c)}})}finally{void 0!==a&&clearTimeout(a)}}}},eu=(e,t)=>e+t&4294967295,tu=(e,t,r,s,n,i)=>{return eu((o=eu(eu(t,e),eu(s,i)))<<(a=n)|o>>>32-a,r);var o,a},ru=(e,t,r,s,n,i,o)=>tu(t&r|~t&s,e,t,n,i,o),su=(e,t,r,s,n,i,o)=>tu(t&s|r&~s,e,t,n,i,o),nu=(e,t,r,s,n,i,o)=>tu(t^r^s,e,t,n,i,o),iu=(e,t,r,s,n,i,o)=>tu(r^(t|~s),e,t,n,i,o),ou=(e,t)=>{let[r,s,n,i]=e;r=ru(r,s,n,i,t[0]??0,7,-680876936),i=ru(i,r,s,n,t[1]??0,12,-389564586),n=ru(n,i,r,s,t[2]??0,17,606105819),s=ru(s,n,i,r,t[3]??0,22,-1044525330),r=ru(r,s,n,i,t[4]??0,7,-176418897),i=ru(i,r,s,n,t[5]??0,12,1200080426),n=ru(n,i,r,s,t[6]??0,17,-1473231341),s=ru(s,n,i,r,t[7]??0,22,-45705983),r=ru(r,s,n,i,t[8]??0,7,1770035416),i=ru(i,r,s,n,t[9]??0,12,-1958414417),n=ru(n,i,r,s,t[10]??0,17,-42063),s=ru(s,n,i,r,t[11]??0,22,-1990404162),r=ru(r,s,n,i,t[12]??0,7,1804603682),i=ru(i,r,s,n,t[13]??0,12,-40341101),n=ru(n,i,r,s,t[14]??0,17,-1502002290),s=ru(s,n,i,r,t[15]??0,22,1236535329),r=su(r,s,n,i,t[1]??0,5,-165796510),i=su(i,r,s,n,t[6]??0,9,-1069501632),n=su(n,i,r,s,t[11]??0,14,643717713),s=su(s,n,i,r,t[0]??0,20,-373897302),r=su(r,s,n,i,t[5]??0,5,-701558691),i=su(i,r,s,n,t[10]??0,9,38016083),n=su(n,i,r,s,t[15]??0,14,-660478335),s=su(s,n,i,r,t[4]??0,20,-405537848),r=su(r,s,n,i,t[9]??0,5,568446438),i=su(i,r,s,n,t[14]??0,9,-1019803690),n=su(n,i,r,s,t[3]??0,14,-187363961),s=su(s,n,i,r,t[8]??0,20,1163531501),r=su(r,s,n,i,t[13]??0,5,-1444681467),i=su(i,r,s,n,t[2]??0,9,-51403784),n=su(n,i,r,s,t[7]??0,14,1735328473),s=su(s,n,i,r,t[12]??0,20,-1926607734),r=nu(r,s,n,i,t[5]??0,4,-378558),i=nu(i,r,s,n,t[8]??0,11,-2022574463),n=nu(n,i,r,s,t[11]??0,16,1839030562),s=nu(s,n,i,r,t[14]??0,23,-35309556),r=nu(r,s,n,i,t[1]??0,4,-1530992060),i=nu(i,r,s,n,t[4]??0,11,1272893353),n=nu(n,i,r,s,t[7]??0,16,-155497632),s=nu(s,n,i,r,t[10]??0,23,-1094730640),r=nu(r,s,n,i,t[13]??0,4,681279174),i=nu(i,r,s,n,t[0]??0,11,-358537222),n=nu(n,i,r,s,t[3]??0,16,-722521979),s=nu(s,n,i,r,t[6]??0,23,76029189),r=nu(r,s,n,i,t[9]??0,4,-640364487),i=nu(i,r,s,n,t[12]??0,11,-421815835),n=nu(n,i,r,s,t[15]??0,16,530742520),s=nu(s,n,i,r,t[2]??0,23,-995338651),r=iu(r,s,n,i,t[0]??0,6,-198630844),i=iu(i,r,s,n,t[7]??0,10,1126891415),n=iu(n,i,r,s,t[14]??0,15,-1416354905),s=iu(s,n,i,r,t[5]??0,21,-57434055),r=iu(r,s,n,i,t[12]??0,6,1700485571),i=iu(i,r,s,n,t[3]??0,10,-1894986606),n=iu(n,i,r,s,t[10]??0,15,-1051523),s=iu(s,n,i,r,t[1]??0,21,-2054922799),r=iu(r,s,n,i,t[8]??0,6,1873313359),i=iu(i,r,s,n,t[15]??0,10,-30611744),n=iu(n,i,r,s,t[6]??0,15,-1560198380),s=iu(s,n,i,r,t[13]??0,21,1309151649),r=iu(r,s,n,i,t[4]??0,6,-145523070),i=iu(i,r,s,n,t[11]??0,10,-1120210379),n=iu(n,i,r,s,t[2]??0,15,718787259),s=iu(s,n,i,r,t[9]??0,21,-343485551),e[0]=eu(r,e[0]),e[1]=eu(s,e[1]),e[2]=eu(n,e[2]),e[3]=eu(i,e[3])},au=(e,t)=>{const r=new Array(16).fill(0);for(let s=0;s<16;s+=1){const n=t+4*s;r[s]=(e[n]??0)|(e[n+1]??0)<<8|(e[n+2]??0)<<16|(e[n+3]??0)<<24}return r},cu=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},du=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)ou(t,au(e,r));const s=new Array(16).fill(0);let n=0;for(;r<e.length;r+=1){const t=n>>2;s[t]=(s[t]??0)|(e[r]??0)<<n%4*8,n+=1}const i=n>>2;s[i]=(s[i]??0)|128<<n%4*8,n>55&&(ou(t,s),s.fill(0));const o=8*e.length;return s[14]=4294967295&o,s[15]=Math.floor(o/4294967296),ou(t,s),t.map(cu).join("")},uu=async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{image:t,width:t.width,height:t.height,cleanup:()=>{t.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw Fi("Image decode capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,r)=>{const s=new Image;s.onload=()=>{e({image:s,width:s.naturalWidth||s.width,height:s.naturalHeight||s.height,cleanup:()=>{URL.revokeObjectURL(t)}})},s.onerror=()=>{URL.revokeObjectURL(t),r(Fi("Image decode failed",{code:qi,stage:xi,retryable:!1,details:{reason:"image load error"}}))},s.src=t})},lu=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw Fi("Web image processor only supports web file source",{code:Pi,stage:xi,retryable:!1,details:{sourceType:e.sourceType}});return e.file},hu=()=>({async getImageInfo(e){const t=lu(e),r=await uu(t);try{return{width:r.width,height:r.height,mimeType:e.mimeType,fileSize:e.size,isGif:"image/gif"===e.mimeType}}finally{r.cleanup()}},async generateBigImage(e,t){const r=lu(e),s=await uu(r);try{const r=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(s.width,s.height,t.maxShortEdge),i=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const r=document.createElement("canvas");return r.width=e,r.height=t,r}throw Fi("Canvas capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),o=i.getContext("2d");if(!o)throw Fi("Canvas 2d context is missing",{code:Pi,stage:xi,retryable:!1});o.drawImage(s.image,0,0,r.width,r.height);const a="image/png"===(n=e.mimeType)||"image/webp"===n?n:"image/jpeg",c=await(async(e,t,r)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:r});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((s,n)=>{e.toBlob(e=>{e?s(e):n(Fi("Image encode failed",{code:qi,stage:xi,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,r)});throw Fi("Canvas encode capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,a,t.quality),d=(e=>e.name??"image")(e),u="undefined"!=typeof File?new File([c],d,{type:a,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:u??c,name:d,mimeType:a,size:u?.size??c.size},width:r.width,height:r.height,fileName:d,fileType:a,fileSize:u?.size??c.size,webFile:u}}finally{s.cleanup()}var n},async computeMd5(e){const t=lu(e),r=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw Fi("Binary read capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,r)=>{const s=new FileReader;s.onerror=()=>{r(Fi("Binary read failed",{code:qi,stage:xi,retryable:!1}))},s.onload=()=>{s.result instanceof ArrayBuffer?t(s.result):r(Fi("Binary read returned invalid result",{code:qi,stage:xi,retryable:!1}))},s.readAsArrayBuffer(e)})})(t);return du(new Uint8Array(r))}}),pu=e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"errMsg"in e){const t=e.errMsg;if("string"==typeof t)return t}return String(e)},mu=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw Fi("Miniapp image processor only supports miniapp path source",{code:Pi,stage:xi,retryable:!1,details:{sourceType:e.sourceType}});return e.path},fu=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw Fi("Miniapp file system capability is missing",{code:Pi,stage:xi,retryable:!1,details:{capability:"getFileSystemManager"}})},gu=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},yu=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(pu(e)))}})}).catch(e=>{throw Fi("Miniapp image info read failed",{code:qi,stage:xi,retryable:!1,details:{src:t,cause:pu(e)}})}),vu=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,bu=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await yu(e,t);return vu(t,r)},Iu=e=>({async getImageInfo(t){const r=mu(t),s=await yu(e,r),n=gu(s.type)??t.mimeType;return{width:s.width,height:s.height,mimeType:n,fileSize:t.size,isGif:"image/gif"===n}},async generateBigImage(t,r){const s=mu(t);if("function"!=typeof e.compressImage)throw Fi("Miniapp image compress capability is missing",{code:Pi,stage:xi,retryable:!1,details:{capability:"compressImage"}});const n=await yu(e,s),i=vu(s,n),o=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(n.width,n.height,r.maxShortEdge),a=await new Promise((t,s)=>{e.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*r.quality))),compressedWidth:o.width,compressedHeight:o.height,success:e=>{e.tempFilePath?t(e.tempFilePath):s(new Error("compressImage missing tempFilePath"))},fail:e=>{s(e instanceof Error?e:new Error(pu(e)))}})}).catch(e=>{throw Fi("Miniapp image compress failed",{code:qi,stage:xi,retryable:!1,details:{src:i,cause:pu(e)}})}),c=await bu(e,a),d=await yu(e,c),u=gu(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=fu(e);return s.getFileInfo?new Promise((e,r)=>{s.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{r(e instanceof Error?e:new Error(pu(e)))}})}).catch(e=>{throw Fi("Miniapp file info read failed",{code:qi,stage:xi,retryable:!1,details:{filePath:t,cause:pu(e)}})}):r})(e,c,t.size);return{source:{sourceType:"miniapp-path",path:c,name:t.name,mimeType:u,size:l},width:d.width,height:d.height,fileName:t.name,fileType:u,fileSize:l}},async computeMd5(t){const r=mu(t),s=await bu(e,r),n=await(async(e,t)=>{const r=fu(e),s=await new Promise((e,s)=>{r.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{s(e instanceof Error?e:new Error(pu(e)))}})}).catch(e=>{throw Fi("Miniapp file read failed",{code:qi,stage:xi,retryable:!1,details:{filePath:t,cause:pu(e)}})});return s instanceof ArrayBuffer?new Uint8Array(s):"function"==typeof TextEncoder?(new TextEncoder).encode(s):Uint8Array.from(Array.from(s).map(e=>255&e.charCodeAt(0)))})(e,s);return du(n)}}),wu=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),Cu=[/\bquota\b/i,/\bexceed(?:ed)?\s+storage\s+max(?:imum)?\s+size\b/i,/\b(?:storage\s+)?max(?:imum)?\s+size\b.*\bexceed(?:ed)?\b/i,/\bstorage\b.*\blimit\b.*\b(?:exceed(?:ed)?|reach(?:ed)?)\b/i],Su=(e,t)=>{if("object"!=typeof e||null===e)return null;const r=e[t];return"string"==typeof r?r:null},Tu=e=>{if(!e)return!1;const t=Su(e,"name");if(t&&wu.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Su(e,"message"),Su(e,"errMsg")].some(e=>null!==e&&Cu.some(t=>t.test(e)))},_u=e=>{if(e instanceof Error)return e;const t=Su(e,"message")??Su(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},Ru="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Au=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Mu=e=>e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP,Eu=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=t.endsWith("==")?2:t.endsWith("=")?1:0,s=Math.max(0,Math.floor(3*t.length/4)-r),n=new Uint8Array(s);let i=0;for(let o=0;o<t.length;o+=4){const e=Ru.indexOf(t[o]??""),r=Ru.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:Ru.indexOf(a),u="="===c?0:Ru.indexOf(c);if(e<0||r<0||d<0||u<0)return new ArrayBuffer(0);const l=e<<18|r<<12|d<<6|u;for(const t of[16,8,0])i<s&&(n[i]=l>>t&255,i+=1)}return n.buffer},Uu=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Nu=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},ku=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Uu(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?ku(r.data,t+1):e},Ou=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Nu(e);if(Uu(e))try{return Nu(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Nu(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e))return e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)?Uint8Array.from(e):void 0;if("object"!=typeof e)return;const r=e;if("data"in r&&r.data!==e){const e=Ou(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=Ou(r.buffer,t+1);if(!e)return;const s="number"==typeof r.byteOffset&&Number.isInteger(r.byteOffset)?r.byteOffset:0,n="number"==typeof r.byteLength&&Number.isInteger(r.byteLength)?r.byteLength:e.byteLength-s;if(s<0||n<0||s+n>e.byteLength)return;return e.slice(s,s+n)}},xu=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(Mu(t)){const s=(e=>{let t="";for(let r=0;r<e.length;r+=3){const s=e[r]??0,n=e[r+1],i=e[r+2],o=s<<16|(n??0)<<8|(i??0);t+=Ru[o>>18&63],t+=Ru[o>>12&63],t+=void 0===n?"=":Ru[o>>6&63],t+=void 0===i?"=":Ru[63&o]}return t})(r);return Si("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:r.byteLength,encodedCharacters:s.length,sourcePrefixHex:Au(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},Lu=(e,t)=>"string"!=typeof e&&Mu(t),Pu=(e,t)=>{const r=ku(e.data);if("string"==typeof r){if(!Mu(t))return r;const s=Eu(r),n=new Uint8Array(s);return Si("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:r===e.data?"string":"wrapped-string",sourceCharacters:r.length,decodedBytes:s.byteLength,decodedPrefixHex:Au(n.subarray(0,8)),decodedSuffixHex:Au(n.subarray(Math.max(0,n.length-8)))}),s}const s=Ou(r);if(!s){const s="object"==typeof e.data&&null!==e.data?e.data:void 0;return void Si("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof r,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:s?Object.keys(s).slice(0,10):[],isBuffer:e.isBuffer})}if(!Mu(t))return s.buffer;const n=(e=>{let t="";for(const s of e){if(9!==s&&10!==s&&13!==s&&32!==s&&!(s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||43===s||45===s||47===s||61===s||95===s))return;t+=String.fromCharCode(s)}const r=t.replace(/\s/g,"");if(0!==r.length&&r.length%4!=1&&/^[A-Za-z0-9+/_-]+={0,2}$/.test(r))return r})(s);if(!n)return Si("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,sourcePrefixHex:Au(s.subarray(0,8))}),s.buffer;const i=Eu(n),o=new Uint8Array(i);return Si("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:Au(o.subarray(0,8)),decodedSuffixHex:Au(o.subarray(Math.max(0,o.length-8)))}),i},Du=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qu=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],Bu=e=>e instanceof Error?e.message:Du(e)&&"string"==typeof e.errMsg?e.errMsg:Du(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),$u=e=>e?{...e}:{},Fu=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,Gu=e=>Fu(e.statusCode)?e.statusCode:Fu(e.status)?e.status:void 0,ju=e=>{if(!Du(e))return{};const t={};return Object.entries(e).forEach(([e,r])=>{"string"==typeof r&&(t[e]=r)}),t},zu=e=>({...ju(e.headers),...ju(e.header)}),Ku=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},Hu=e=>{try{e.close()}catch{}},Vu=(e,t)=>new Promise((r,s)=>{let n=!1,i=()=>{};const o=(e,r,o)=>{n||(n=!0,i(),s(Fi(e,{code:Di,stage:Ui,retryable:o,details:{url:t.url,method:"GET",cause:Bu(r)}})))},a=e.downloadFile?.({url:t.url,header:$u(t.headers),timeout:t.timeoutMs??15e3,success:s=>{const a=s.tempFilePath??s.apFilePath;a?((e,t)=>new Promise((r,s)=>{const n=e.getFileSystemManager?.();n?n.readFile({filePath:t,success:e=>{const t=Ou(e.data);t?r(t.buffer):s(new Error("downloaded file response is not binary"))},fail:s}):s(new Error("getFileSystemManager returned no file system manager"))}))(e,a).then(e=>{n||(n=!0,i(),Si("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:s.apFilePath?"apFilePath":"tempFilePath",status:s.statusCode??200,bytes:e.byteLength}),r({status:s.statusCode??200,headers:s.header??{},data:e}))}).catch(e=>{o("Mini program downloaded file read failed.",e,!1)}):o("Mini program download did not return a file path.",s,!1)},fail:e=>{o("Mini program file download failed.",e,!0)}});i=Ku(t.signal,()=>{a?.abort(),o("Mini program file download aborted.","abort",!1)})}),Wu=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((r,s)=>{let n=()=>{};const i=e.request({url:t.url,method:t.method??"GET",header:$u(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{n();const i=Gu(e);void 0!==i?r({status:i,headers:zu(e),data:e.data}):s(Fi("Mini program request response status is invalid.",{code:Di,stage:Ui,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{n(),s(Fi("Mini program request failed.",{code:Di,stage:Ui,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:Bu(e)}}))}});n=Ku(t.signal,()=>{i.abort(),s(Fi("Mini program request aborted.",{code:Di,stage:Ui,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):Vu(e,t)}),Ju=(e,t)=>({connect:r=>new Promise((s,n)=>{let i,o,a=!1;const c=()=>{void 0!==o&&(clearTimeout(o),o=void 0)},d=(e,t,s)=>{a||(a=!0,c(),i&&Hu(i),n(Fi(t,{code:Bi,stage:ki,retryable:s,details:{url:r.url,cause:Bu(e)}})))},u=e=>{if(!(qu(r=e,"send")&&qu(r,"close")&&qu(r,"onOpen")&&qu(r,"onMessage")&&qu(r,"onError")&&qu(r,"onClose")))return void d(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var r;const n=e;if(a)return void Hu(n);i=n;const o=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?Hu(n):(a=!0,c(),o(),s(((e,t,r=Gi)=>{const s=new Set,n=new Set,i=new Set,o=new Set;let a=r;return e.onOpen(()=>{a=ji,s.forEach(e=>{e()})}),e.onMessage(e=>{const r=Pu(e,t);void 0!==r&&n.forEach(e=>{e(r)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{a=Ki,o.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(r){if(a!==ji)throw Fi("Mini program socket is not open.",{code:Bi,stage:ki,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:xu(r,t),...Lu(r,t)?{isBuffer:!0}:{},success:s,fail:e=>{n(Fi("Mini program socket send failed.",{code:Bi,stage:ki,retryable:!0,details:{cause:Bu(e)}}))}})})},close(t,r){a=zi,e.close({code:t,reason:r})},onOpen:e=>(s.add(e),()=>{s.delete(e)}),onMessage:e=>(n.add(e),()=>{n.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}})(n,t,ji)))},l=e=>{o(),d(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};n.onOpen(u),n.onError(l)};let l;"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(o=setTimeout(()=>{d("timeout","Mini program socket connection timed out.",!0)},r.timeoutMs));try{l=e.connectSocket({url:r.url,...t===Mi.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(r.protocols)?[...r.protocols]:"string"==typeof r.protocols?[r.protocols]:void 0,fail:e=>{d(e,"Mini program socket connect failed.",!0)}})}catch(p){return void d(p,"Mini program socket creation failed.",!0)}var h;"object"!=typeof(h=l)||null===h||"function"!=typeof h.then?u(l):Promise.resolve(l).then(e=>u(e),e=>d(e,"Mini program socket connect failed.",!0))})}),Zu=e=>({upload:t=>new Promise((r,s)=>{const n=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw Fi("Mini program upload only supports miniapp-path source.",{code:qi,stage:Ni,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const o=e.uploadFile({url:t.url,filePath:n.path,name:"file",header:$u(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i();const o=Gu(e);void 0!==o?r({status:o,body:e.data}):s(Fi("Mini program upload response status is invalid.",{code:qi,stage:Ni,retryable:!1,details:{url:t.url,path:n.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{i(),s(Fi("Mini program upload failed.",{code:qi,stage:Ni,retryable:!0,details:{url:t.url,path:n.path,cause:Bu(e)}}))}});o.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=Ku(t.signal,()=>{o.abort(),s(Fi("Mini program upload aborted.",{code:qi,stage:Ni,retryable:!1,details:{url:t.url,path:n.path,reason:"abort"}}))})})}),Qu=(e,t)=>{const r=(e=>e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP)(t);return{async getItem(t){if(qu(e,"getStorageSync"))try{const s=(e=>Du(e)&&"data"in e?e.data:e)(e.getStorageSync(r?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return qu(e,"getStorage")?new Promise(r=>{e.getStorage({key:t,success:e=>{r("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{r(null)}})}):null},async setItem(t,s){if(qu(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(Tu(n))throw _u(n)}else if(qu(e,"setStorage"))return new Promise((r,i)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{Tu(e)?i(_u(e)):r()}})}catch(n){if(Tu(n))return void i(_u(n));r()}})},async removeItem(t){if(qu(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(qu(e,"removeStorage"))return new Promise(r=>{try{e.removeStorage({key:t,success:r,fail:()=>{r()}})}catch{r()}})}}},Yu=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>qu(e,"getNetworkType")?new Promise(t=>{e.getNetworkType?.({success:e=>{t(e.networkType??"unknown")},fail:()=>{t("unknown")}})}):Promise.resolve("unknown"),onNetworkChange(t){const r=e=>{t(e.isConnected)};return qu(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),qu(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{qu(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return qu(e,"onAppShow")&&e.onAppShow(r),qu(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{qu(e,"offAppShow")&&e.offAppShow(r),qu(e,"offAppHide")&&e.offAppHide(s)}}}),Xu=(e,t=Mi.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(qu(e,"request")&&qu(e,"connectSocket")&&qu(e,"uploadFile"))return e;throw Fi("Mini program platform capability is missing.",{code:Pi,stage:Ei,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),n="function"==typeof s.getImageInfo?Iu(s):void 0;return{request:Wu(s),socket:Ju(s,r),upload:Zu(s),runtime:Yu(s,t),storage:Qu(s,r),imageProcessor:n}},el=[Mi.WEB,Mi.ELECTRON_RENDERER,Mi.REACT_NATIVE],tl=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},rl=e=>el.includes(e),sl=(e,t)=>e!==Mi.UNIAPP?rl(e):!io(t)&&!il(t)&&to(t),nl=e=>tl(e,"getImageInfo")&&tl(e,"getFileSystemManager"),il=e=>!io(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),ol=(e,t)=>{if(rl(e)&&e!==Mi.REACT_NATIVE)return hu();if(uo(e)&&nl(t))return Iu(t);if(e===Mi.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(to(e))return hu();if(nl(e.uni))return Iu(e.uni);if(nl(e.wx))return Iu(e.wx)}},al=e=>{const t=e.localStorage;if(t)return{getItem:e=>Promise.resolve(t.getItem(e)),setItem:(e,r)=>(t.setItem(e,r),Promise.resolve()),removeItem:e=>(t.removeItem(e),Promise.resolve())};const r=new Map;return{getItem(e){const t=r.has(e)?r.get(e)??null:null;return Promise.resolve(t)},setItem:(e,t)=>(r.set(e,t),Promise.resolve()),removeItem:e=>(r.delete(e),Promise.resolve())}},cl=(e,t,r,s)=>{if(e===Mi.UNIAPP&&il(r)&&void 0!==r.uni&&Zi(r.uni))return{...Xu(r.uni,e,t),proto:Pd()};if(((e,t)=>!sl(e,t)&&uo(e))(e,r)&&Zi(s))return{...Xu(s,e,t),proto:Pd()};const n=r.XMLHttpRequest,i=sl(e,r),o=i?qd({fetchImpl:r.fetch}):void 0,a=i?Hd({webSocketCtor:r.WebSocket}):void 0,c=e===Mi.REACT_NATIVE?Xd({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?Qd({xhrFactory:"function"==typeof n?()=>new n:void 0,fetchImpl:r.fetch}):void 0,d=i&&e!==Mi.REACT_NATIVE?(u={platform:e,windowRef:r.window,documentRef:r.document,navigatorRef:r.navigator},{getPlatform:()=>u.platform,getNetworkType:()=>!1===u.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(u.navigatorRef?.connection?.type??u.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=u.windowRef;if(!t)return()=>{};const r=()=>{e(!0)},s=()=>{e(!1)};return t.addEventListener("online",r),t.addEventListener("offline",s),"boolean"==typeof u.navigatorRef?.onLine&&e(u.navigatorRef.onLine),()=>{t.removeEventListener("online",r),t.removeEventListener("offline",s)}},onAppVisibilityChange(e){const t=u.documentRef;if(!t)return()=>{};const r=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",r),r(),()=>{t.removeEventListener("visibilitychange",r)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var u;return{request:o,upload:c,socket:a,runtime:d,proto:Pd(),storage:al(r),imageProcessor:i&&e!==Mi.REACT_NATIVE?hu():ol(e,s)}},dl=(e,t)=>{if(void 0!==e)return e;throw Fi("Platform adapter initialization failed.",{code:Li,stage:Ei,retryable:!1,details:{capability:t}})},ul=e=>{const t=Vi(e?.runtimeInput),r=co(t,e?.prefer),s=r.platform,n=cl(s,r.hostPlatform,t,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,n),o={...n,...i},a=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(o);ho(a);return{platform:s,platformId:s,capability:a,request:dl(o.request,"request"),upload:dl(o.upload,"upload"),socket:dl(o.socket,"socket"),runtime:dl(o.runtime,"runtime"),proto:dl(o.proto,"proto"),storage:dl(o.storage,"storage"),imageProcessor:o.imageProcessor}},ll=e=>{if(e instanceof rs)return e;if((e=>"object"==typeof e&&null!==e)(e)){const t=e.details;if(e.code===Pi){const r=t?.capability;if(e.stage===xi&&"string"==typeof r&&r.includes("FileSystem")){const r=e instanceof Error?e.message:"Upload failed";return new rs(r,{code:qr,details:t})}return new rs("Upload capability is missing for current platform",{code:Lr,details:t})}if(e.stage===Ni)return(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("abort"))})(t)?new rs("Upload canceled",{code:$r,details:t}):(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("timeout"))})(t)?new rs("Upload timeout",{code:Br,details:t}):new rs("Upload failed",{code:qr,details:t})}const t=e instanceof Error?e.message:"Upload failed";return new rs(t,{code:qr,details:{cause:e}})},hl={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class pl{constructor(e={}){this.attemptCount=0,this.config={...hl,...e}}getRetryDelay(){const e=Math.max(this.attemptCount-1,0),t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),r=Math.min(t,this.config.maxDelay);return r/2+r/2*Math.min(1,Math.max(0,this.config.randomSource()))}recordAttempt(){this.attemptCount++}reset(){this.attemptCount=0}shouldRetry(){return this.attemptCount<this.config.maxAttempts}getAttemptCount(){return this.attemptCount}async waitForRetry(){const e=this.getRetryDelay();return Ci(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const ml={interval:3e4,timeout:6e4},fl="function"==typeof TextDecoder?new TextDecoder:null;class gl{constructor(e={}){this.websocket=null,this.heartbeatTimer=null,this.timeoutTimer=null,this.lastPongTime=0,this.onTimeoutCallback=null,this.sendPing=null,this.probeResolvers=[],this.messageDisposer=null,this.handlePong=e=>{const t=this.extractMessageText(e);if(!t)return;const r=this.parseJson(t);if(!gl.isRecord(r))return;"pong"===gl.readString(r.type)&&(this.markAlive(),Ci("Pong received"))},this.config={...ml,...e}}start(e,t,r){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=r??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),Ci("Heartbeat started",{interval:this.config.interval})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.timeoutTimer&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.messageDisposer?.(),this.messageDisposer=null,this.websocket=null,this.sendPing=null,this.resolveProbe(!1),Ci("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===ji)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{Ti("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),Ci("Ping sent")}catch(e){Ti("Failed to send ping:",e),this.resolveProbe(!1)}else this.resolveProbe(!1)}extractMessageText(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return(e=>{for(const t of e)if(32!==t&&9!==t&&10!==t&&13!==t)return 123===t;return!1})(t)?fl?.decode(t)??Ri(t):null}return null}parseJson(e){try{return JSON.parse(e)}catch{return null}}static isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static readString(e){return"string"==typeof e?e:void 0}resetTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=setTimeout(()=>{Si("Heartbeat timeout"),this.onTimeoutCallback&&this.onTimeoutCallback()},this.config.timeout)}markAlive(){this.lastPongTime=Date.now(),this.resetTimeout(),this.resolveProbe(!0)}getLastPongTime(){return this.lastPongTime}async probeOnce(e,t){try{if(e.readyState!==ji)return!1;this.attachWebSocket(e);const r=t??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},r);this.probeResolvers.push(r=>{clearTimeout(t),e(r)}),this.sendPingInternal()})}catch(r){return Si("Heartbeat probe failed",r),!1}}attachWebSocket(e){this.websocket!==e&&(this.messageDisposer?.(),this.websocket=e,this.messageDisposer=e.onMessage(e=>{this.handlePong(e)}))}resolveProbe(e){if(0===this.probeResolvers.length)return;const t=[...this.probeResolvers];this.probeResolvers=[];for(const r of t)r(e)}removeProbeResolver(e){this.probeResolvers=this.probeResolvers.filter(t=>t!==e)}}let yl=null;function vl(){return yl||(yl=Ld()),yl}const bl="websdk2:device-info",Il="webim",wl="web",Cl=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,i=Vi().localStorage,o=()=>{if(!i)return null;try{const t=i.getItem(bl);if(!t)return null;const r=JSON.parse(t);if("object"==typeof(e=r)&&null!==e&&!Array.isArray(e)&&"string"==typeof r.deviceId&&"string"==typeof r.deviceName&&"string"==typeof r.deviceUuid)return{deviceId:r.deviceId,deviceName:r.deviceName,deviceUuid:r.deviceUuid}}catch{return null}var e;return null},a=e=>{if(i)try{i.setItem(bl,JSON.stringify(e))}catch{}},c=e=>void 0===s?e:{deviceId:`custom${s}_${e.deviceUuid}`,deviceName:n??r,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=o();if(e)return c(e);if(r===Il){const e=`${wl}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${wl}_${r}`,deviceName:r,deviceUuid:`${wl}_${t}`});return a(e),e}const n={deviceId:`webim_${wl}_${r}`,deviceName:`webim_${wl}_${r}`,deviceUuid:`webim_${wl}_${r}`};return a(n),n}if(r===Il){const e=`random_${wl}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${wl}_${r}`,deviceName:r,deviceUuid:`random_${wl}_${t}`})}return{deviceId:`webim_${wl}_${r}`,deviceName:`webim_${wl}_${r}`,deviceUuid:`webim_${wl}_${r}`}},Sl=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Tl=e=>{if("string"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?`${e}`:"";if("bigint"==typeof e)return e.toString();if(e&&"object"==typeof e&&"low"in e&&"high"in e&&"number"==typeof e.low&&"number"==typeof e.high){const t=e;return new mo(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},_l=e=>{const t=[];for(const[r,s]of Object.entries(e))if(void 0!==s)if("boolean"!=typeof s)if("number"!=typeof s)if("string"!=typeof s)try{t.push({key:r,type:vn,stringValue:JSON.stringify(s)})}catch{t.push({key:r,type:yn,stringValue:Object.prototype.toString.call(s)})}else t.push({key:r,type:yn,stringValue:s});else Number.isInteger(s)?t.push({key:r,type:hn,varintValue:s}):t.push({key:r,type:gn,doubleValue:s});else t.push({key:r,type:ln,varintValue:s?1:0});return t},Rl=e=>{if(!e||0===e.length)return{};const t={};for(const r of e){const e="string"==typeof r.key?r.key:"";if(!e)continue;const s="number"==typeof r.type?r.type:yn;if(s!==ln)if(s!==hn&&s!==pn&&s!==mn)if(s!==fn)if(s!==gn){if(s!==vn)t[e]="string"==typeof r.stringValue?r.stringValue:"";else if("string"==typeof r.stringValue)try{t[e]=JSON.parse(r.stringValue)}catch{t[e]=r.stringValue}}else t[e]=Number(r.doubleValue??0);else t[e]=Number(r.floatValue??0);else t[e]=Number(r.varintValue??0);else t[e]=Boolean(r.varintValue)}return t},Al=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,Ml="X-Request-Id",El=new Set(["mute"]),Ul={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},Nl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},kl=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Ol=(e,t)=>{const r=e?.map(e=>Nl(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},xl=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=kl(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},Ll=e=>{const t=kl(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Ul[s];if(!e)continue;let t=n;if(El.has(s))t=!0===n||"true"===n;else if("max_users"===s){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(r[e]=t)}return Object.keys(r).length>0?r:void 0},Pl=e=>{const t=kl(e);if(!t)return{attributes:{},keyList:[]};const r=t.result&&"object"==typeof t.result&&!Array.isArray(t.result)?t.result:{},s=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},n=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[];return{attributes:Object.fromEntries(n.map(e=>[e,s[e]]).filter(e=>"string"==typeof e[1])),keyList:n,from:Nl(t.operator)??Nl(t.username)}},Dl=(e,t)=>({eventName:e,payload:t}),ql=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=Nl(e.from?.name),s=(n=e.to,Nl(n?.[0]?.name));var n;switch(e.operation){case 1:return Dl(Be,t);case 10:return Dl(Ge,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return Dl($e,{...t,memberIds:Ol(e.members,r),ext:e.ext??e.eventExt});case 18:return Dl(Fe,{...t,memberIds:Ol(e.members,r)});case 20:return Dl(Ze,{...t,oldOwnerId:r,newOwnerId:s});case 21:return Dl(We,{...t,adminId:s??r});case 22:return Dl(Je,{...t,adminId:s??r});case 23:{const r=(e=>{const t=kl(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=Number(i);n&&Number.isFinite(e)&&(s[n]=e)}return Object.keys(s).length>0?s:null})(e.ext??e.eventExt),n=r?Object.keys(r):Ol(e.members,s),i=46388736e5;return Dl(je,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,i])),muteExpire:xl(e.reason,e.eventExt)??i})}case 24:return Dl(ze,{...t,userIds:Ol(e.members,s)});case 25:return Dl(Qe,{...t,announcement:e.reason??""});case 26:return Dl(Qe,{...t,announcement:""});case 29:return Dl(Ke,{...t,userIds:Ol(e.members,s)});case 30:return Dl(He,{...t,userIds:Ol(e.members,s)});case 31:return Dl(Ve,{...t,isMuted:!0});case 32:return Dl(Ve,{...t,isMuted:!1});case 14:return Dl(Ye,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Ll(e.eventExt)});case 43:{const s=Pl(e.eventExt);return Dl(Xe,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=Pl(e.eventExt);return Dl(et,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},Bl=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),$l=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},Fl=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Gl=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),jl=e=>({userId:e}),zl=(e,t,r)=>{const s={userId:r};for(const n of Fl){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Kl=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Gl(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,jl(o));return s},Hl=e=>Bl(e)?e:null,Vl=e=>{if("string"==typeof e)return e},Wl=e=>{const t=Vl(e)?.trim();return t||void 0},Jl=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}},Zl=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Ql=e=>{const t=Hl(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Yl=e=>{const t=Hl(e);return t?Hl(t.data)?t.data:t:null},Xl=(e,t)=>{const r=Hl(e),s=r&&Hl(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Jl(n[0])},eh=(e,t)=>{const r=(e=>{const t=Hl(e);return t?Jl(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},th=e=>Wl(e.groupId)??Wl(e.groupid)??Wl(e.id)??"",rh=e=>Vl(e.name)??Vl(e.groupname)??Vl(e.groupName)??"",sh=e=>{const t=Ql(e),r=Hl(t[0])??Yl(e)??{},s=(e=>{const t=Hl(e);if(!t)return null;const r=th(t);return r?{groupId:r,name:rh(t),description:Vl(t.description),memberCount:Jl(t.memberCount)??Jl(t.affiliations_count),public:Zl(t.public),joinApprovalRequired:Zl(t.joinApprovalRequired)??Zl(t.approval)??Zl(t.membersonly)??Zl(t.members_only),allowInvites:Zl(t.allowInvites)??Zl(t.allowinvites)??Zl(t.allow_user_invites),maxMembers:Jl(t.maxMembers)??Jl(t.maxusers),role:Wl(t.role)??Wl(t.permission),disabled:Zl(t.disabled)}:null})(r)??{groupId:th(r),name:rh(r)},n=Wl(r.owner)??Wl(r.admin)??Wl(r.member),i=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>Hl(e)).filter(e=>null!==e).map(e=>Jl(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?jl(n):void 0,inviteNeedConfirm:Zl(r.inviteNeedConfirm)??Zl(r.invite_need_confirm),muteAllMembers:Zl(r.mute),ext:Vl(r.ext)??Vl(r.custom),createdAt:Jl(r.createdAt)??Jl(r.created),joinedAt:i,avatarUrl:Vl(r.avatar),messageBlocked:Zl(r.messageBlocked)??Zl(r.isMessageBlocked)??Zl(r.shieldgroup)}},nh=e=>jl(e),ih=e=>Ql(e).map(e=>Wl(e)).filter(e=>Boolean(e)).map(e=>nh(e)),oh=e=>{const t=Hl(e);if(!t)return null;const r=Wl(t.fileId)??Wl(t.file_id);if(!r)return null;const s=Vl(t.fileName)??Vl(t.file_name)??r,n=Wl(t.fileOwner)??Wl(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?nh(n):void 0,fileSize:Jl(t.fileSize)??Jl(t.file_size),createdAt:Jl(t.createdAt)??Jl(t.created)}},ah=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),ch={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},dh=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},uh=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},lh=(e,t)=>{const r=e?.map(e=>dh(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},hh=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=uh(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},ph=e=>{const t=uh(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=ch[s];if(!e)continue;let t=n;if(ah.has(s))t=!0===n||"true"===n;else if("max_users"===s){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(r[e]=t)}return Object.keys(r).length>0?r:void 0},mh=(e,t)=>{const r=uh(t)??uh(e);return oh(r??void 0)??void 0},fh=(e,t)=>{const r=uh(t)??uh(e);return dh(r?.fileId)??dh(r?.file_id)??dh(e)??""},gh=(e,t)=>({eventName:e,payload:t}),yh=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=dh(e.from?.name),s=(n=e.to,dh(n?.[0]?.name));var n;switch(e.operation){case 4:return gh(Y,{...t,applicantId:r,reason:e.reason});case 5:return gh(X,{...t,accepterId:r});case 6:return gh(ee,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return gh(Q,{...t,inviterId:r,reason:e.reason});case 8:return gh(te,{...t,inviteeId:r,reason:e.reason});case 9:return gh(re,{...t,inviteeId:r,reason:e.reason});case 10:return gh(se,t);case 1:return gh(ne,t);case 19:return gh(ie,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=uh(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=dh(n),t=Number(i);e&&Number.isFinite(t)&&t>0&&(s[e]=t)}return Object.keys(s).length>0?s:null})(e.ext),n=r?Object.keys(r):lh(e.members,s);return gh(oe,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??hh(e.reason,e.eventExt)})}case 24:return gh(ae,{...t,userIds:lh(e.members,s)});case 29:return gh(ce,{...t,userIds:lh(e.members,s)});case 30:return gh(de,{...t,userIds:lh(e.members,s)});case 31:return gh(ue,{...t,isMuted:!0});case 32:return gh(ue,{...t,isMuted:!1});case 21:return gh(le,{...t,administratorId:s??r});case 22:return gh(he,{...t,administratorId:s??r});case 20:return gh(pe,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=lh(e.members,r);return gh(me,{...t,memberIds:s})}case 18:{const s=lh(e.members,r);return gh(fe,{...t,memberIds:s})}case 25:return gh(ge,{...t,announcement:e.reason??""});case 26:return gh(ge,{...t,announcement:""});case 27:return gh(ye,{...t,sharedFile:mh(e.reason,e.eventExt)});case 28:return gh(ve,{...t,fileId:fh(e.reason,e.eventExt)});case 14:return gh(be,{...t,shouldFetchGroupDetail:!0,groupPatch:ph(e.eventExt)});case 41:return gh(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return gh(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=uh(e);if(!t)return{attribute:{}};const r=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},s=Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]));return{userId:dh(t.username),attribute:s}})(e.eventExt);return gh(we,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},vh=new WeakMap,bh=(e,t)=>{vh.set(e,t)},Ih=e=>vh.get(e)??null,wh=(e,t)=>{const r=Ih(e);r&&bh(t,r)},Ch=new WeakMap,Sh=e=>Ch.get(e),Th=new WeakMap,_h=e=>Th.get(e),Rh=(e,t)=>{const r=Th.get(e);r&&Th.set(t,r)},Ah="singleChat",Mh="groupChat",Eh=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Uh=e=>{if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&e.trim().length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}},Nh=e=>{if(!Array.isArray(e))return;const t=e.map(e=>Eh(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},kh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Oh=(...e)=>{for(const t of e){const e=Eh(t);if(e)return e}},xh=(e,t)=>Boolean(e&&t&&e===t),Lh=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),Ph=(e,t,r)=>{const s=Nh(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>Eh(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const i=Eh(r?.name);return i?[i]:[]},Dh=e=>{const t=Uh(e);if(void 0!==t)return t;if("string"==typeof e){const t=e.match(/(\d+)/);if(t){const e=Number(t[1]);return Number.isFinite(e)?e:void 0}}},qh=(e,t)=>{const r=Oh(e.to?.[0]?.clientResource);if(1!==e.to?.length||Eh(e.to[0]?.name)!==t.userId||!Lh(t.userId,r,t))return null;const s=(n=e.from,Eh(n?.name)??"");var n;if(!s)return Si("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const i=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return Si("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:s,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Bh=(e,t)=>{if(!e.groupId)return Si("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=Oh(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Lh(Eh(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 0:return"GROUP_CREATE";case 1:return"GROUP_DESTROY";case 2:return"GROUP_JOIN";case 3:return"GROUP_LEAVE";case 4:return"GROUP_APPLY";case 5:return"GROUP_APPLY_ACCEPT";case 6:return"GROUP_APPLY_DECLINE";case 7:return"GROUP_INVITE";case 8:return"GROUP_INVITE_ACCEPT";case 9:return"GROUP_INVITE_DECLINE";case 10:return"GROUP_KICK";case 12:return"GROUP_BAN";case 13:return"GROUP_ALLOW";case 15:return"GROUP_BLOCK";case 16:return"GROUP_UNBLOCK";case 20:return"GROUP_ASSIGN_OWNER";case 21:return"GROUP_ADD_ADMIN";case 22:return"GROUP_REMOVE_ADMIN";case 23:return"GROUP_ADD_MUTE";case 24:return"GROUP_REMOVE_MUTE";case 29:return"GROUP_ADD_USER_WHITE_LIST";case 30:return"GROUP_REMOVE_USER_WHITE_LIST";case 31:return"GROUP_ALL_BAN";case 32:return"GROUP_REMOVE_ALL_BAN";case 45:return"GROUP_MEMBER_METADATA_CHANGED";case 14:return"GROUP_UPDATED";default:return Si("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Ph(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:Eh(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},$h=(e,t)=>{if(!e.threadId)return Si("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=Oh(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Lh(Eh(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 33:return"THREAD_CREATE";case 35:return"THREAD_JOIN";case 38:return"THREAD_UPDATE";case 36:return"THREAD_LEAVE";case 34:return"THREAD_DESTROY";case 37:return"THREAD_KICK";default:return Si("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Ph(e.members,e.to,e.from);return{category:"thread",operation:s,threadId:e.threadId,parentId:e.parentId,userIds:n.length>0?n:void 0,operatorId:Eh(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Fh=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=Oh(e.res,e.raw?.resource,e.raw?.clientResource);if(xh(r,t.clientResource))return Ci("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const s="chat"===(n=e.type)||"singleChat"===n?Ah:Mh;var n;const i=Eh(e.id)??(s===Ah?Eh(e.from):void 0);if(!i)return Si("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const o=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return Si("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"conversation",operation:o,conversationId:i,conversationType:s,mark:"mark"===e.operation||"mark_delete"===e.operation?Dh(e.ext):void 0,operatorId:Eh(e.from),deviceId:r,timestamp:Uh(e.ts),raw:e.raw}},Gh=(e,t)=>{const r=Oh(e.resource,e.raw?.resource,e.raw?.clientResource);if(xh(r,t.clientResource))return Ci("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=Eh(e.to);if(!s)return Si("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=Eh(e.lastMsgId),i=Nh(e.msgIdList)??(n?[n]:void 0),o=Uh(e.deleteTime);if(!i&&void 0===o)return Si("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:s}),null;const a=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(Si("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===a?null:{category:"messageRemoved",operation:a,conversationId:s,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?Mh:Ah,messageIds:i,beforeTimestamp:o,deviceId:r,raw:e.raw}},jh=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},zh=2147483647,Kh=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>zh?void 0:r},Hh=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>zh?Math.floor(e/1e3):Math.floor(e);return Kh(t)};var Vh=4096,Wh=65547,Jh=15,Zh=2113929216,Qh=65536,Yh=65536,Xh=10485760,ep={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},tp={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function rp(e){if(!(e>0))return Yh;if(e<=Yh)return Yh;if(e>1073741823)return e;for(var t=Yh;t<e;)t*=2;return t}var sp={byU16:0,byU32:1},np=0,ip=1,op=2,ap=0,cp=1;function dp(e,t){return e[t]|e[t+1]<<8}function up(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function lp(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var hp="fast";function pp(e){return 2654435761*(e>>>0)>>>20&4095}function mp(e){return 2654435761*(e>>>0)>>>19&8191}function fp(e,t,r){if("fast"===hp){var s=up(e,t);return r===sp.byU16?mp(s):pp(s)}throw new Error("Unsupported hash strategy: "+hp)}function gp(e,t,r,s,n){r[t]=e-n}function yp(e,t,r,s,n){gp(t,fp(e,t,s),r,0,n)}function vp(e,t,r,s){return t[e]+s}function bp(e,t,r,s,n){return vp(fp(e,t,s),r,0,n)}function Ip(e,t,r,s){for(var n=t;t<s-3;){if(up(e,t)!==up(e,r)){for(;t<s&&e[t]===e[r];)t++,r++;return t-n}t+=4,r+=4}for(;t<s&&e[t]===e[r];)t++,r++;return t-n}function wp(e,t,r,s,n,i,o,a,c,d){var u,l,h,p=e.hashTable,m=s,f=m-e.dictSize,g=e.dictionary,y=e.dictionaryStart,v=y+e.dictSize,b=e.dictSize>0?v-s:0,I=s,w=s+n,C=w-12,S=w-5,T=0,_=i>0?i:r.length,R=0;if(n>Zh)return 0;switch(c){case np:default:u=s,l=s;break;case ip:u=s-e.currentOffset,l=s-e.dictSize;break;case op:u=s-e.currentOffset,l=s}if(a===sp.byU16&&n>=Wh)return 0;if(n<13)return Tp(t,r,I,w,T,_,o);yp(t,m,p,a,u),h=fp(t,++m,a);e:for(;;){var A,M,E=m,U=1,N=64;do{var k=h;if(m=E,E+=U,U=N++>>>6,E>C)return Tp(t,r,I,w,T,_,o);A=vp(k,p,0,u),c===op&&(A<s?(R=b,l=y):(R=0,l=s)),h=fp(t,E,a),gp(m,k,p,0,u)}while(d===cp&&A<f||a!==sp.byU16&&A+65535<m||!Cp(t,g,m,A,R,c,s));for(;m>I&&A+R>l;){var O=A+R-1;if(t[m-1]!==(c===op&&A<s?g[O-y+e.dictionaryStart]:t[O]))break;m--,A--}var x=m-I;if(M=T++,o&&T+x+8+Math.floor(x/255)>_)return 0;if(x>=Jh){var L=x-Jh;for(r[M]=240;L>=255;)r[T++]=255,L-=255;r[T++]=L}else r[M]=x<<4;if(x>=16&&r.set&&t.subarray)r.set(t.subarray(I,I+x),T),T+=x;else for(var P=0;P<x;P++)r[T++]=t[I+P];t:for(;;){var D;if(lp(r,T,m-A),T+=2,c===op&&A<s){var q=m+(v-(A+R));if(q>S&&(q=S),(m+=4+(D=Sp(t,g,m+4,A+R+4-y+e.dictionaryStart,q,v-y)))===q&&q<S){var B=Ip(t,m,s,S);D+=B,m+=B}}else m+=4+(D=Ip(t,m+4,A+4,S));if(o&&T+6+(D>>>8)>_)return 0;if(D>=15){for(r[M]+=15,D-=15;D>=510;)r[T++]=255,r[T++]=255,D-=510;D>=255&&(D-=255,r[T++]=255),r[T++]=D}else r[M]+=D;if(I=m,m>C)break e;if(yp(t,m-2,p,a,u),A=bp(t,m,p,a,u),c===op&&(A<s?(R=b,l=y):(R=0,l=s)),yp(t,m,p,a,u),!((d!==cp||A>=f)&&A+65535>=m&&Cp(t,g,m,A,R,c,s)))break t;r[M=T++]=0}h=fp(t,++m,a)}return Tp(t,r,I,w,T,_,o)}function Cp(e,t,r,s,n,i,o){var a,c=up(e,r);i===op&&s+n<o?a=up(t,s+n):a=up(e,s+n);return c===a}function Sp(e,t,r,s,n,i,o){for(var a=r;s<i&&r<n&&t[s]===e[r];)s++,r++;return r-a}function Tp(e,t,r,s,n,i,o){var a=s-r;if(o&&n+a+1+Math.floor((a+255-Jh)/255)>i)return 0;if(a>=Jh){for(t[n++]=240,a-=Jh;a>=255;)t[n++]=255,a-=255;t[n++]=a}else t[n++]=a<<4;var c=r,d=s,u=d-c;if(u>=16&&t.set&&e.subarray)t.set(e.subarray(c,d),n),n+=u;else for(var l=c;l<d;l++)t[n++]=e[l];return n}function _p(e,t,r,s){var n,i=0;if(s&&t.ip>=r)return-1;do{if(i+=n=e[t.ip++],t.ip>r)return-1;if(i>2147483647)return-1}while(255===n);return i}function Rp(e,t,r,s,n,i,o,a,c,d,u,l,h){if(null==e)return-1;if(i<0)return-1;var p=r,m=r+s,f=n,g=n+i,y=u-h,v=l+h,b=h<65536;if(0===i)return 1===s&&0===e[p]?0:-1;if(0===s)return-1;for(;;){var I,w,C,S;if(p>=m)return-(p-r)-1;if((w=(I=e[p++])>>>4)===Jh){var T=_p(e,A={ip:p},m-Jh,!0);if(p=A.ip,-1===T)return-(p-r)-1;if(f+(w+=T)<f)return-(p-r)-1;if(p+w<p)return-(p-r)-1}if(C=f+w,o&&(C>g-12||p+w>m-8)||!o&&C>g-8){if(!o&&C!==g)return-(p-r)-1;if(o&&(p+w!==m||C>g))return-(p-r)-1;if(w>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+w),f);else for(var _=0;_<w;_++)t[f+_]=e[p+_];p+=w,f+=w;break}if(w>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+w),f);else for(_=0;_<w;_++)t[f+_]=e[p+_];if(f=C,(p+=w)+2>m)return-(p-r)-1;var R=dp(e,p);if(p+=2,S=C-R,b&&S+h<u)return-(p-r)-1;if(0===R)return-(p-r)-1;if(15===(w=15&I)){var A;T=_p(e,A={ip:p},m-5+1,!1);if(p=A.ip,-1===T)return-(p-r)-1;if(f+(w+=T)<f)return-(p-r)-1}if(w+=4,d===op&&S<u){if(f+w>g-5)return-(p-r)-1;if(w<=u-S){var M=v-(u-S);for(_=0;_<w;_++)t[f+_]=t[M+_];f+=w}else{var E=u-S;for(M=v-E,_=0;_<E;_++)t[f+_]=t[M+_];var U=w-E;if(U>(f+=E)-u)for(var N=u,k=f+U;f<k;)t[f++]=t[N++];else{for(_=0;_<U;_++)t[f+_]=t[u+_];f+=U}}}else{if(S<y)return-(p-r)-1;if(C=f+w,f-S<8)for(t[f]=t[S],t[f+1]=t[S+1],t[f+2]=t[S+2],t[f+3]=t[S+3],f+=4,S+=4;f<C;)t[f++]=t[S++];else for(;f<C;)t[f++]=t[S++]}}return o?f-n:p-r}function Ap(){return{hashTable:new Uint32Array(Vh),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function Mp(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function Ep(e,t,r,s,n,i,o,a){s=s||0;var c=e.dictionaryStart+e.dictSize,d=s;if(e.initCheck)return 0;e.dictSize>0&&d>c&&(d=c),function(e){if(e.currentOffset>2147483648){for(var t=e.currentOffset-65536,r=e.dictionaryStart+e.dictSize,s=0;s<e.hashTable.length;s++)e.hashTable[s]<t?e.hashTable[s]=0:e.hashTable[s]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=r-e.dictSize}}(e);var u,l=s+n;e.dictionary&&l>e.dictionaryStart&&l<c&&(e.dictSize=c-l,e.dictSize>65536&&(e.dictSize=65536),e.dictSize<4&&(e.dictSize=0),e.dictionaryStart=c-e.dictSize);var h=e.dictSize<65536&&e.dictSize<e.currentOffset?cp:ap;return e.dictionary&&c===s?(u=wp(e,t,r,s,n,o||0,a||!1,sp.byU32,ip,h),e.dictSize+=n,e.currentOffset+=n,u):(u=wp(e,t,r,s,n,o||0,a||!1,sp.byU32,op,h),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function Up(e,t,r,s){var n=e.dictionaryStart+e.dictSize;s>65536&&(s=65536),s>e.dictSize&&(s=e.dictSize);var i=n-s;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(i,i+s),r);else for(var o=0;o<s;o++)t[r+o]=e.dictionary[i+o];return e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,s}function Np(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function kp(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function Op(e,t,r,s,n,i,o){var a;if(e.prefixEnd===i){if((a=Rp(t,r,s,n,i,o,!0,0,0,op,e.prefixEnd-e.prefixSize,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize+=a,e.prefixEnd+=a}else{if(e.extDictSize=e.prefixSize,e.extDictStart=e.prefixEnd-e.extDictSize,(a=Rp(t,r,s,n,i,o,!0,0,0,op,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function xp(e){var t=(e=e||{}).minWorkArea||Yh,r=e.maxWorkArea||Xh,s=e.shrinkThreshold||t;t<Yh&&(t=Yh),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Qh+t,this.maxBufferSize=Qh+r,this.shrinkThreshold=Qh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:ep.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=Ap()}function Lp(e){var t=(e=e||{}).minWorkArea||Yh,r=e.maxWorkArea||Xh,s=e.shrinkThreshold||t;t<Yh&&(t=Yh),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Qh+t,this.maxBufferSize=Qh+r,this.shrinkThreshold=Qh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:ep.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}xp.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Qh?this.offset:Qh,n=this.offset>Qh?this.offset-Qh:0;t.set(this.ringBuffer.subarray(n,n+s),0),Up(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},xp.prototype.compress=function(e,t){var r=e.length;if(r<=0)return tp.PARAM_ERROR;if(r>this.maxBufferSize-Qh)return tp.PARAM_ERROR;if(r>this.ringBufferSize-Qh){var s=rp(r),n=Qh+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return tp.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(Up(this.stream,this.ringBuffer,0,Qh),this.offset=Qh);var i=this.offset;this.ringBuffer.set(e,i);var o=Ep(this.stream,this.ringBuffer,t,i,r,0,t.length,!0);return o<=0?tp.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),o)},xp.prototype.reset=function(){this.offset=0,Mp(this.stream)},xp.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},xp.prototype._tryAutoShrink=function(){this.shrinkMode!==ep.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===ep.AUTO_IMMEDIATE||this.shrinkMode===ep.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},xp.prototype.getWorkArea=function(){return this.ringBufferSize-Qh},xp.prototype.getRingBufferSize=function(){return this.ringBufferSize},xp.prototype.getBaseBufferSize=function(){return this.minBufferSize},xp.prototype.getMaxBufferSize=function(){return this.maxBufferSize},xp.prototype.getCurrentOffset=function(){return this.offset},xp.prototype.getShrinkMode=function(){return this.shrinkMode},xp.prototype.setShrinkMode=function(e){this.shrinkMode=e},xp.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},xp.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Qh,r=this.maxBufferSize-Qh;if(e<t||e>r)return tp.PARAM_ERROR;this.shrinkThreshold=Qh+e},Lp.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Qh?this.offset:Qh,n=this.offset>Qh?this.offset-Qh:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,kp(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},Lp.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return tp.PARAM_ERROR;if(r>this.maxBufferSize-Qh)return tp.PARAM_ERROR;if(r>this.ringBufferSize-Qh){var n=rp(r),i=Qh+n;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return tp.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var o=this.offset-Qh;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+Qh),0),kp(this.streamDecode,this.ringBuffer,0,Qh),this.offset=Qh}var a=Op(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?tp.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},Lp.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},Lp.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Lp.prototype._tryAutoShrink=function(){this.shrinkMode!==ep.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===ep.AUTO_IMMEDIATE||this.shrinkMode===ep.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Lp.prototype.getWorkArea=function(){return this.ringBufferSize-Qh},Lp.prototype.getRingBufferSize=function(){return this.ringBufferSize},Lp.prototype.getBaseBufferSize=function(){return this.minBufferSize},Lp.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Lp.prototype.getCurrentOffset=function(){return this.offset},Lp.prototype.getShrinkMode=function(){return this.shrinkMode},Lp.prototype.setShrinkMode=function(e){this.shrinkMode=e},Lp.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Lp.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Qh,r=this.maxBufferSize-Qh;if(e<t||e>r)return tp.PARAM_ERROR;this.shrinkThreshold=Qh+e};const Pp={LZ4_MAX_INPUT_SIZE:Zh,BLOCK_MAX_SIZE:65536,DICT_SIZE:Qh,DEFAULT_WORK_AREA:Yh,DEFAULT_MAX_WORK:Xh,SHRINK_MODE:ep,LZ4_ERROR:tp,alignToPowerOf2:rp,calcDefaultBufferSize:function(){return 131072},calcDefaultMaxBufferSize:function(){return 10551296},setHashStrategy:function(e){if("fast"!==e&&"compatible"!==e)throw new Error("Invalid hash strategy: "+e+'. Use "fast" or "compatible".');hp=e},getHashStrategy:function(){return hp},compress:function(e,t,r,s,n){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0)return 0;if(r+s>e.length)return 0;if(s>Zh)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var i=s<Wh?sp.byU16:sp.byU32;return wp({hashTable:new Uint32Array(i===sp.byU16?8192:Vh),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,i,np,ap)},compressLimited:function(e,t,r,s,n,i){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0||i<0)return 0;if(r+s>e.length)return 0;if(s>Zh)return 0;if(i<1)return 0;if(0===s)return t[n]=0,1;var o=s<Wh?sp.byU16:sp.byU32;return wp({hashTable:new Uint32Array(o===sp.byU16?8192:Vh),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,i,!0,o,np,ap)},compressBound:function(e){return e<0||e>Zh?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,r,s,n,i){return null==e||null==t?-1:(n=n||0,(r=r||0)<0||n<0||s<0||i<0||r+s>e.length||n+i>t.length?-1:Rp(e,t,r,s,n,i,!0,0,0,np,n,null,0))},decompressFast:function(e,t,r,s,n){return Rp(e,t,r=r||0,0,s=s||0,n,!1,0,0,ip,s-65536,0,65536)},createStream:Ap,resetStream:Mp,loadDict:function(e,t,r,s){if(e.initCheck&&Mp(e),s<4)return e.dictionary=null,e.dictSize=0,0;s>65536&&(r=r+s-65536,s=65536);var n=r-e.currentOffset;e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,e.currentOffset+=s;for(var i=r,o=r+s;i<=o-4;)yp(t,i,e.hashTable,sp.byU32,n),i+=3;return s},compressContinue:Ep,saveDict:Up,createStreamDecode:Np,setStreamDecode:kp,decompressSafeContinue:Op,RingBufferEncoder:xp,RingBufferDecoder:Lp,_hashU16:mp,_hashU32:pp,_TABLE_TYPE:sp},Dp=268435455,qp=new Uint32Array(256);let Bp=!1;function $p(e){!function(){if(!Bp){for(let e=0;e<256;e+=1){let t=e;for(let e=0;e<8;e+=1)t=1&t?3988292384^t>>>1:t>>>1;qp[e]=t>>>0}Bp=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(qp[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var Fp=(e=>(e[e.NONE=-1]="NONE",e[e.UPLINK_ONLY=0]="UPLINK_ONLY",e[e.DOWNLINK_ONLY=1]="DOWNLINK_ONLY",e[e.BIDIRECTIONAL=2]="BIDIRECTIONAL",e))(Fp||{});const Gp=268435455;class jp{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Pp.DEFAULT_WORK_AREA,maxWorkArea:Pp.DEFAULT_MAX_WORK,shrinkMode:Pp.SHRINK_MODE.MANUAL};this.encoder=new Pp.RingBufferEncoder(e),this.decoder=new Pp.RingBufferDecoder(e)}compress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length>Gp)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=Pp.compressBound(t.length),s=new Uint8Array(r),n=this.encoder.compress(t,s);if(n<0)throw new Error(`LZ4 compression failed with error code: ${n}`);const i=s.subarray(0,n),o=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>Dp)throw new Error("encodeLength: Length exceeds maximum: 268435455");if(0===e)return new Uint8Array([0]);const t=[];let r=e;for(;r>0;){let e=127&r;r>>>=7,r>0&&(e|=128),t.push(e)}return new Uint8Array(t)}(t.length),a=$p(t),c=new Uint8Array(o.length+4+n);let d=0;c.set(o,d),d+=o.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(i,d),c}decompress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length<5)throw new Error("Compressed data is too short: must contain at least length and CRC32");const r={offset:0},s=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let r=0,s=0;for(;t.offset<e.length;){const n=e[t.offset]??0;if(t.offset+=1,r|=(127&n)<<s,!(128&n))return r>>>0;if(s+=7,s>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,r);if(s>Gp)throw new Error(`Original size exceeds maximum allowed: ${s}`);if(t.length<r.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const n=new DataView(t.buffer,t.byteOffset+r.offset,4).getUint32(0,!1);r.offset+=4;const i=t.subarray(r.offset),o=new Uint8Array(s),a=this.decoder.decompress(i,o,s);if(a<0||a!==s)throw new Error(`LZ4 decompression failed: expected ${s}, got ${a}`);const c=$p(o);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const zp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Kp=(e,t)=>pd(e,t).finish();class Hp{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Cl({useFixedDeviceId:e.useFixedDeviceId??!0,deviceId:e.deviceId??"webim",customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform}),r=`${Date.now()}:`;return{appKey:e.appKey,userId:e.userId,token:e.token,domain:e.domain??"easemob.com",version:e.version??"4.11.0",uiKitVersion:e.uiKitVersion,osType:void 0!==e.customOSPlatform?5:e.osType??16,deviceId:t.deviceId,deviceName:t.deviceName,deviceUuid:t.deviceUuid,clientResource:t.deviceId,customOSPlatform:e.customOSPlatform,loginExtensionInfo:e.loginExtensionInfo,encryptType:[$s],compressType:[Fs],sessionId:r,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.useCustomAttachmentUpload=e.useCustomAttachmentUpload??!1}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=vl(),t=e.lookupType("easemob.pb.Provision"),r=e.lookupType("easemob.pb.MSync"),s={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[Fs],encryptType:[$s],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},n=Kp(t,s),i={version:0,guid:Sl({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:os,deviceId:0,encryptType:[$s],payload:n,traceId:Al()};return Kp(r,i)}encodeHeartbeat(){const e=vl(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Kp(t,{}),n={version:0,encryptType:[$s],command:ns,payload:s,traceId:Al()};return Kp(r,n)}encodeStatisticRebuild(){const e=vl(),t=e.lookupType("easemob.pb.StatisticsBody"),r=e.lookupType("easemob.pb.Meta"),s=e.lookupType("easemob.pb.CommSyncUL"),n=e.lookupType("easemob.pb.MSync"),i=Kp(t,{operation:0}),o=r.decode(new Uint8Array);o.id=Date.now(),o.ns=Ns,o.payload=i;const a=s.decode(new Uint8Array);a.meta=o;const c=Kp(s,a);return Kp(n,{version:0,encryptType:[$s],command:ss,payload:c,traceId:Al()})}decodeProvision(e){const t=vl().lookupType("easemob.pb.Provision").decode(e),r=t.status??{},s="number"==typeof r.errorCode?r.errorCode:zs,n="string"==typeof r.reason?r.reason:void 0,i="string"==typeof t.resource?t.resource:void 0,o="string"==typeof t.authToken?t.authToken:void 0,a=Array.isArray(t.protocolCompressType)?t.protocolCompressType:void 0,c="number"==typeof t.protocolCompressDirection?t.protocolCompressDirection:void 0;return this.configureCompression(a,c),{ok:s===js,statusCode:s,reason:n,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=vl().lookupType("easemob.pb.Logout").decode(e),r=t.status&&"object"==typeof t.status?t.status:void 0;return{sessionId:"string"==typeof t.sessionId?t.sessionId:void 0,reason:"string"==typeof t.reason?t.reason:void 0,statusCode:"number"==typeof r?.errorCode?r.errorCode:void 0}}decodeSyncStatisticOperations(e){const t=vl().lookupType("easemob.pb.CommSyncDL").decode(e),r=Array.isArray(t.metas)?t.metas:[],s=[];for(const n of r){const e=this.decodeStatisticMeta(n);e&&s.push(e)}return s}decodeMsync(e){const t=vl().lookupType("easemob.pb.MSync").decode(e);return{command:"number"==typeof t.command?t.command:-1,payload:this.normalizeBinaryPayload(t.payload)}}normalizeBinaryPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array}decodeSync(e){const t=vl(),r=t.lookupType("easemob.pb.CommSyncDL"),s=t.lookupType("easemob.pb.MessageBody"),n=r.decode(e);Ci("decodeSync commSyncDl",{hasMetas:Array.isArray(n.metas)});const i=Array.isArray(n.metas)?n.metas:[],o=this.decodeAck(n);o?.ok&&(o.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const a=Tl(n.metaId),c=Tl(n.nextKey),d=n.queue??void 0,u="boolean"==typeof n.isLast?n.isLast:void 0,l=[],h=[];if(a&&"0"!==a){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(i,s):void 0;for(const t of i){const e=this.decodeNotifyMeta(t);e.length>0&&h.push(...e)}return{ack:o,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u,replacedMessage:e}}for(const p of i){const e=this.decodeChatMeta(p,s);e&&l.push(e);const t=this.decodeChatActionMeta(p,s);t&&h.push(t);const r=this.decodeNotifyMeta(p);r.length>0&&h.push(...r)}return{ack:o,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u}}decodeReplacedMessage(e,t){for(const r of e){const e=this.decodeChatMeta(r,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Os)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e;return this.decodeMessage(r,s)}catch{return null}}decodeChatActionMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Os)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e,i="number"==typeof s.type?s.type:cs;if(i!==hs&&i!==ms&&i!==fs&&i!==gs&&i!==ps)return null;const o=this.readJid(r.to),a=Number(Tl(r.timestamp))||Date.now(),c=this.resolveActionConversationType(o.domain,s.meta,s),{senderId:d,receiverId:u}=this.resolveIncomingMessageParties(r,s,c),l=this.resolveActionConversationId(d,u,c);if(i===fs)return!0===s.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:a}}:l?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a}}:null;if(i===hs){Ci("Received READ_ACK MessageBody",s);const e=(Array.isArray(s.ackMessageIds)?s.ackMessageIds:[]).map(e=>Tl(e)).filter(e=>Boolean(e)),t=Tl(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=Rl(Array.isArray(s.ext)?s.ext.filter(zp):void 0),n=zp(r.group_ack_count)?r.group_ack_count:{},i=e.flatMap(e=>{const t=n[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a,..."groupChat"===c?{receiptDetails:i}:{}}}}if(i===ps){const e=Tl(s.ackMessageId);return e&&l?{type:"message_delivered",data:{messageId:e,from:d,to:u,conversationId:l,conversationType:"singleChat"}}:null}if(i===ms){const e=Tl(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const h=Tl(s.editMessageId),p=(Array.isArray(s.contents)?s.contents:[])[0],m=p?this.decodeContent(p):null;if(!h||!l||!m)return null;const f=this.resolveModifiedInfo(s.meta);return{type:"message_updated",data:{messageId:h,conversationId:l,conversationType:c,timestamp:a,message:{type:m.type,body:m.body,ext:Rl(s.ext),...f?{modifiedInfo:f}:{}}}}}catch{return null}}decodeNotifyMeta(e){if(!e||"object"!=typeof e)return[];const t=e,r="number"==typeof t.ns?t.ns:void 0;if(r!==Ps&&r!==Ls&&r!==xs&&r!==Ns)return[];const s=t.payload;let n=null;return s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),n?r===Ls?this.decodeRosterMeta(t,n):r===xs?this.decodeMucMeta(t,n):r===Ns?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const r=vl(),s=r.lookupType("easemob.pb.StatisticsBody").decode(t);if("string"!=typeof s.location||0===s.location.length)return[];const n=JSON.parse(s.location);if(!zp(n)||!Array.isArray(n.group_ack))return[];const i=this.readMetaTimestamp(e)??Date.now(),o=new Map;for(const e of n.group_ack){if(!zp(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[r,s]of Object.entries(e)){if("groupId"===r)continue;const e="number"==typeof s?s:"string"==typeof s&&s.trim().length>0?Number(s):Number.NaN;!r||!Number.isInteger(e)||e<0||o.set(r,{conversationId:t,count:e})}}return Ci("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(o,([e,{conversationId:t,count:r}])=>({messageId:e,conversationId:t,count:r}))}),Array.from(o,([e,{conversationId:t,count:r}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:i,receiptDetails:[{messageId:e,count:r}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==Ns)return null;const r=t.payload;let s=null;if(r instanceof Uint8Array?s=r:r instanceof ArrayBuffer?s=new Uint8Array(r):ArrayBuffer.isView(r)&&(s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!s)return null;try{const e=vl(),t=e.lookupType("easemob.pb.StatisticsBody").decode(s);return{operation:"number"==typeof t.operation?t.operation:-1,reason:"string"==typeof t.reason?t.reason:void 0}}catch{return null}}decodeRosterMeta(e,t){try{const r=vl(),s=r.lookupType("easemob.pb.RosterBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=this.readRosterJid(s.from),o=this.readRosterJidList(s.to),a="string"==typeof s.reason?s.reason:"",c="string"==typeof s.rosterVer&&s.rosterVer.trim().length>0?s.rosterVer:void 0,d=i.name??"",u=o[0]?.name??"";if(!d&&!u)return[];const l=qh({operation:n,from:i,to:o,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(l)return[this.createMultiDeviceNotify(l)];const h=this.mapRosterOperationToEvent(n,{from:d,to:u,message:a,rosterVersion:c});return h?[{type:"contact",eventName:h.eventName,data:h.payload}]:[]}catch{return[]}}readRosterJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0}}readRosterJidList(e){return Array.isArray(e)&&0!==e.length?e.map(e=>this.readRosterJid(e)):[]}readJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0,domain:"string"==typeof t.domain?t.domain:void 0}}decodeMucMeta(e,t){try{const r=vl(),s=r.lookupType("easemob.pb.MUCBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=!0===s.isChatroom,o=!0===s.isThread,a=this.readJid(s.from),c=Array.isArray(s.to)?s.to.map(e=>this.readJid(e)):[],d=s.eventInfo&&"object"==typeof s.eventInfo?s.eventInfo:void 0,u=Array.isArray(s.members)?s.members.filter(e=>"string"==typeof e):[],l=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(o){const t=$h({operation:n,threadId:this.readJid(s.mucId).name??"",threadName:"string"==typeof s.mucName?s.mucName:void 0,parentId:this.readJid(s.mucParentId).name??void 0,from:a,to:c,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const r=37===n&&c.some(e=>e.name===this.context.userId),i=this.readJid(s.mucId).name??"",o=this.readJid(s.mucParentId).name??"";return r&&i&&o?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:i,name:"string"==typeof s.mucName?s.mucName:void 0,muc_parent_id:o,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!i){const t=Bh({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=i?ql({operation:n,chatRoomId:this.readJid(s.mucId).name??"",chatRoomName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u}):yh({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u,source:l});return h?[{type:i?"chatroom":"group",eventName:i?"onChatRoomNotify":"onGroupNotify",data:h}]:[]}catch{return[]}}mapRosterOperationToEvent(e,t){const r={from:t.from,to:t.to,message:t.message,userInfo:{userId:t.from||t.to}};switch(((e,t)=>{t&&Ch.set(e,t)})(r,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:r};case 3:return{eventName:"onContactDeleted",payload:r};case 4:return{eventName:"onContactAdded",payload:r};case 5:case 9:return{eventName:"onContactRefuse",payload:r};case 8:return{eventName:"onContactAgreed",payload:r};default:return null}}decodeNotifyPayload(e){try{let t="";for(let i=0;i<e.length;i+=1){const r=e[i];if(void 0===r)return[];t+=`%${r.toString(16)}`}const r=decodeURIComponent(t),s=JSON.parse(r);Ci("Decoded MSync notify payload",{payload:s});const n="string"==typeof s.type?s.type:"";if(!n)return[];if("thread"===n){return[{type:n,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:zp(s.data)?s.data:s}}]}if("conv"===n){const e=zp(s.data)?s.data:s,t=[],r="string"==typeof e.op?e.op:"";if("pin"===r||"pin_delete"===r)return[{type:n,eventName:"onPinnedMessageChanged",data:e}];const i=Fh({operation:r,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return i&&t.push(this.createMultiDeviceNotify(i)),t}if("roaming_delete"===n){const e=zp(s.data)?s.data:s,t=Gh({chatType:"string"==typeof e.chatType?e.chatType:void 0,to:"string"==typeof e.to?e.to:void 0,resource:"string"==typeof e.resource?e.resource:void 0,msgIdList:Array.isArray(e.msgIdList)?e.msgIdList.filter(e=>"string"==typeof e):void 0,deleteTime:e.deleteTime,lastMsgId:"string"==typeof e.lastMsgId?e.lastMsgId:void 0,messageRoamingType:"string"==typeof e.messageRoamingType?e.messageRoamingType:void 0,raw:e},this.msyncCodecContext());return t?[this.createMultiDeviceNotify(t)]:[]}if("user_notification_mute"===n){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const r=[];for(const s of e){if(!kh(s))continue;const e=Oh(s.operator_resource,s.resource,s.clientResource);if(xh(e,t.clientResource))continue;const n=Eh(s.group)??Eh(s.user);if(!n||!kh(s.data))continue;const i=Eh(s.group)?Mh:Ah,o=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:i,remindType:Eh(o.type),silentMode:o,deviceId:e,raw:s})}return r})(zp(s.data)&&Array.isArray(s.data.values)?s.data.values:Array.isArray(s.values)?s.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:n,data:s.data??s}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,r=Number(Tl(t));if(Number.isFinite(r)&&r>0)return r}msyncCodecContext(){return{userId:this.context.userId,clientResource:this.context.clientResource}}createMultiDeviceNotify(e){return{type:"multiDevice",eventName:jh(e.category),data:e}}decodeNotice(e){const t=vl().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=vl().lookupType("easemob.pb.CommUnreadDL").decode(e);return{queues:(Array.isArray(t.unread)?t.unread:[]).map(e=>e&&"object"==typeof e?e:null).map(e=>e?.queue&&"object"==typeof e.queue?e.queue:null).filter(e=>Boolean(e))}}encodeBackQueue(e){const t=vl(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=Kp(r,{queue:e}),i={version:0,encryptType:[$s],command:ss,payload:n,traceId:Al()};return Kp(s,i)}encodeLastSession(e,t){const r=vl(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=Kp(s,{queue:e,key:t}),o={version:0,encryptType:[$s],command:ss,payload:i,traceId:Al()};return Kp(n,o)}encodeChatMessage(e,t){const r=vl(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o=this.buildContent(e),a=this.resolveMessageProfileVersionFields(e),c=this.buildMessageMeta(e),d=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),u={type:this.resolveChatType(e),from:{name:this.context.userId},to:{name:d.name},contents:[o],ext:_l(e.ext??{}),...c?{meta:c}:{},...a,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=Kp(s,u),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e),f={id:t,to:Sl({appKey:this.context.appKey,name:d.name,domain:h,clientResource:d.clientResource}),ns:Os,payload:l,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}},g=Kp(n,{meta:f}),y={version:0,encryptType:[$s],command:ss,payload:g,traceId:Al()};return Kp(i,y)}encodeActionMessage(e,t){const r=vl(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o=r.lookupEnum("easemob.pb.MessageBody.EditScope"),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:t,from:this.context.userId,to:e.conversationId,sender:{userId:this.context.userId},conversationId:e.conversationId,conversationType:e.conversationType,type:e.messageType,sendStatus:"sending",ext:e.ext??{},timestamp:Date.now(),body:e.body})]:[],d={type:this.resolveActionMessageType(e),from:{name:this.context.userId},to:{name:a.name},contents:c,ext:_l(e.ext??{})};"recall"!==e.kind&&"deliveryAck"!==e.kind||(d.ackMessageId=e.messageId),"sendMessageReadReceipts"===e.kind&&(d.ackMessageIds=e.messageIds,"groupChat"===e.conversationType&&(d.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1,d.clearAllUnreadMessageCount=e.clearAllUnreadMessageCount??!0),"update"===e.kind&&(d.editMessageId=e.messageId,d.editScope=e.ext&&Object.keys(e.ext).length>0?o.values.BODY_AND_EXT:o.values.BODY);const u=Kp(s,d);if("clearAllConversationUnreadMessageCount"===e.kind){const e=s.decode(u),r=s.fields.clearAllUnreadMessageCount;Ci("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:d.type,fieldId:r?.id,requestedValue:d.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(e,"clearAllUnreadMessageCount"),decodedValue:e.clearAllUnreadMessageCount,messageBodyBytes:u.byteLength,wireTailHex:Array.from(u.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const l={id:t,to:Sl({appKey:this.context.appKey,name:a.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:a.clientResource}),ns:Os,payload:u,routetype:Ds,directedUsers:[],ext:[]},h=Kp(n,{meta:l}),p={version:0,encryptType:[$s],command:ss,payload:h,traceId:Al()};return Kp(i,p)}encodeChatRoomOperation(e,t){const r=vl(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o={mucId:Sl({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(o.ext=e.ext),void 0!==e.leaveOtherRooms&&(o.leaveOtherRooms=e.leaveOtherRooms));const a=Kp(s,o),c={id:t,from:Sl({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:xs,payload:a},d=Kp(n,{meta:c}),u={version:0,encryptType:[$s],command:ss,payload:d,traceId:Al()};return Kp(i,u)}decodeServerMessageMeta(e){const t=vl(),r=t.lookupType("easemob.pb.Meta"),s=t.lookupType("easemob.pb.MessageBody");try{const t=r.decode(e);return this.decodeChatMeta(t,s)}catch{return null}}async normalizeIncoming(e){if(e instanceof Uint8Array)return e;if(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))return new Uint8Array(e);var t;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if((e=>"undefined"!=typeof Blob&&e instanceof Blob||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e)){const t=await e.arrayBuffer();return new Uint8Array(t)}return"string"==typeof e?_i(e):e&&"object"==typeof e&&"data"in e?this.normalizeIncoming(e.data):new Uint8Array}decompressIncoming(e){if(!this.compressor||!this.compressor.enableDownlinkCompression)return e;try{return this.compressor.decompress(e)}catch{return this.compressionFailureCount+=1,null}}prepareOutgoing(e){if(!this.compressor||!this.compressor.enableUplinkCompression)return e;try{return this.compressor.compress(e)}catch{throw this.compressionFailureCount+=1,new Error("compress outgoing message failed")}}resetCompressionNegotiation(){this.compressor?.reset(),this.disableCompression()}toProtocolId(e){return(e=>{if(/^\d+$/.test(e))return e;const t=mo.fromString("1099511628211",!0);let r=mo.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(mo.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()})(e)}decodeChatRoomJoinInfo(e){const t=vl().lookupType("easemob.pb.MUCBody");for(const s of e){if(!zp(s)||s.ns!==xs)continue;const e=s.payload,n=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(n)try{const e=t.decode(n);if(!zp(e)||!zp(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!zp(s))continue;const i=s[this.context.userId];if(!zp(i))continue;const o=i;return{..."boolean"==typeof o.is_all_mute?{isAllMembersMuted:o.is_all_mute}:{},..."number"==typeof o.create_timestamp?{createTimestamp:o.create_timestamp}:{},..."boolean"==typeof o.is_in_white_list?{isInAllowlist:o.is_in_white_list}:{},..."number"==typeof o.member_count?{memberCount:o.member_count}:{},muteExpireTimestamp:"number"==typeof o.mute_duration&&0!==o.mute_duration?o.mute_duration:-1}}catch(r){Ti("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=Tl(e.metaId);if(!t||"0"===t)return;const r=e.status??{},s="number"==typeof r.errorCode?r.errorCode:zs,n="string"==typeof r.reason?r.reason:void 0;return{protocolId:t,serverId:Tl(e.serverId),ok:s===js,statusCode:s,reason:n}}decodeMessage(e,t){const r="number"==typeof t.type?t.type:ds;if(!this.isPublicMessageType(r))return null;const s=(Array.isArray(t.contents)?t.contents:[])[0];if(!s)return null;const n=this.resolveConversationType(r),{senderUserId:i,senderId:o,receiverId:a}=this.resolveIncomingMessageParties(e,t,n),c=o===this.context.userId?"SEND":"RECEIVE",d="singleChat"===n?"SEND"===c?a:o:a,u=this.decodeContent(s);if(!u)return null;const l=Rl(t.ext),h=Rl(e.ext),p=Number(Tl(e.timestamp))||Date.now(),m=Tl(e.id),f=this.resolveBroadcast(h),g=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),v=this.resolveContentReplaced(y),b=this.resolveReactions(y),I=this.resolveModifiedInfo(y),w=this.resolveChatThreadMessageContext(y),C=this.resolveChatThreadOverview(y),S=this.resolveProfileVersionTime(t.userInfoUpdateTime),T=this.resolveProfileVersionTime(t.namecardUpdateTime),_={msgServerId:m,msgLocalId:"",from:o,to:a,sender:{userId:i},conversationId:d,conversationType:n,type:u.type,sendStatus:"sent",ext:l,timestamp:p,body:u.body,direct:c,isOnline:this.resolveMessageIsOnline(r,h)};bh(_,{userInfoUpdateTime:S,namecardUpdateTime:T});const R=this.decodeStreamMeta(t.stream,s);R&&(_.type="text",_.body={content:R.fullText},_.stream=R),void 0!==f&&(_.isBroadcast=f),void 0!==g&&(_.priority=g),void 0!==v&&(_.isContentReplaced=v),b&&(_.reactions=b),I&&(_.modifiedInfo=I),w&&(_.isChatThread=!0,_.chatThread=w);const A=this.resolvePeerRead(y,n,c);void 0!==A&&(_.isPeerRead=A);const M=this.resolveGroupReadCount(y,n);void 0!==M&&(_.groupReadCount=M),C&&(_.chatThreadOverview=C);const E=t.msgConfig;return E?.allowGroupAck&&(_.needReadReceipt=!0),_}resolveMessageProfileVersionFields(e){const t=Ih(e),r={};return"number"==typeof t?.userInfoUpdateTime&&(r.userInfoUpdateTime=t.userInfoUpdateTime),"groupChat"===e.conversationType&&"number"==typeof t?.namecardUpdateTime&&(r.namecardUpdateTime=t.namecardUpdateTime),r}buildMessageMeta(e){const t={};return e.isChatThread&&(t.thread={}),Object.keys(t).length>0?JSON.stringify(t):""}resolveProfileVersionTime(e){return Kh(Tl(e))}isPublicMessageType(e){return e===ds||e===us||e===ls}resolveMessageIsOnline(e,t){if(e===ls)return!0;const r=t.is_online;return"boolean"==typeof r?r:"number"==typeof r?0!==r:"string"!=typeof r||"0"!==r}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const r=e,s=Number(Tl(r.streamSeq));if(!Number.isFinite(s))return;const n="number"==typeof r.streamStatus?r.streamStatus:Ms,i="number"==typeof r.streamError?r.streamError:0,o="number"==typeof r.streamFinishReason?r.streamFinishReason:void 0,a=this.resolveContentText(t),c=a;return{customType:"string"==typeof r.streamType?r.streamType:void 0,seq:s,status:this.mapStreamStatus(n,i),errorType:i,finishReason:o,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?rt.ERROR:e===Rs?rt.START:e===As?rt.START_COMPLETED:e===Es?rt.COMPLETED:e===Us?rt.FULL:rt.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}buildContent(e){if("text"===e.type){const t=e.body;return{type:ys,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:Ss,action:t.action}}if("custom"===e.type){const t=e.body;return{type:Ts,customEvent:t.event,customExts:_l(t.params??{})}}if("location"===e.type){const t=e.body;return{type:Is,latitude:t.latitude,longitude:t.longitude,address:t.address,buildingName:t.buildingName}}if("image"===e.type){const r=e.body,s=r.isGif||r.isOriginalImage?"original":"large";return{type:vs,displayName:r.filename,remotePath:r.originalImageUrl??"",imageType:(t=s,t===Wn?1:2),secretKey:r.secret,fileLength:r.fileLength,size:{width:r.width,height:r.height},subType:r.isGif?1:void 0,thumbnailRemotePath:r.thumbnailUrl,thumbnailDisplayName:r.filename}}var t;if("video"===e.type){const t=e.body;return{type:bs,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,size:t.width&&t.height?{width:t.width,height:t.height}:void 0,thumbnailRemotePath:t.thumbnailUrl,thumbnailSecretKey:t.secret,thumbnailDisplayName:t.filename}}if("voice"===e.type){const t=e.body;return{type:ws,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,thumbnailDisplayName:t.filename}}if("combine"===e.type){const t=e.body;return{type:ys,subType:0,text:_h(e)??"版本过低",displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,title:t.title,summary:t.summary,combineLevel:t.combineLevel}}const r=e.body;return{type:Cs,displayName:r.filename,remotePath:r.url,secretKey:r.secret,fileLength:r.fileLength,thumbnailDisplayName:r.filename}}decodeContent(e){const t="number"==typeof e.type?e.type:ys,r="string"==typeof e.remotePath&&e.remotePath.length>0||"string"==typeof e.title&&e.title.length>0||"string"==typeof e.summary&&e.summary.length>0||"number"==typeof e.combineLevel&&e.combineLevel>0,s=Object.prototype.hasOwnProperty.call(e,"subType")&&0===e.subType;if(t===_s||t===ys&&(s||r)){return{type:"combine",body:{title:"string"==typeof e.title?e.title:"",summary:"string"==typeof e.summary?e.summary:"",filename:"string"==typeof e.displayName?e.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof e.remotePath?e.remotePath:void 0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,combineLevel:"number"==typeof e.combineLevel?e.combineLevel:0}}}if(t===ys)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===Ss)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===Ts){const t=Rl(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===Is)return{type:"location",body:{latitude:"number"==typeof e.latitude?e.latitude:0,longitude:"number"==typeof e.longitude?e.longitude:0,address:"string"==typeof e.address?e.address:void 0,buildingName:"string"==typeof e.buildingName?e.buildingName:void 0}};if(t===vs){const t=e.size??{},r="number"==typeof t.width?t.width:0,s="number"==typeof t.height?t.height:0,n=oi(e.imageType)===Wn,i="string"==typeof e.remotePath?e.remotePath:"",o=ni(i,{deriveVariants:!this.useCustomAttachmentUpload}),a="string"==typeof e.thumbnailRemotePath&&e.thumbnailRemotePath.length>0?e.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof e.displayName?e.displayName:"image",filetype:"application/octet-stream",width:r,height:s,isGif:1===e.subType,isOriginalImage:n,originalImageUrl:o.originalImageUrl,bigImageUrl:o.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:a??o.thumbnailUrl}}}if(t===bs){const t=e.size??{},r="number"==typeof t.width?t.width:void 0,s="number"==typeof t.height?t.height:void 0,n="string"==typeof e.thumbnailRemotePath?e.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,width:r,height:s,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:n}}}if(t===ws){return{type:"voice",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}if(t===Cs){return{type:"file",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}return null}resolveChatType(e){switch(e.conversationType){case"groupChat":return us;case"chatRoom":return ls;default:return ds}}resolveActionConversationType(e,t,r){const s=this.resolveConversationTypeFromMeta(t);if(s)return s;const n=r?.msgConfig&&"object"==typeof r.msgConfig?r.msgConfig:null;return!0===n?.allowGroupAck||"conference.easemob.com"===e?"groupChat":"singleChat"}resolveConversationTypeFromMeta(e){if("string"!=typeof e||0===e.length)return null;try{const t=JSON.parse(e),r=t.edit_msg&&"object"==typeof t.edit_msg?t.edit_msg:void 0,s=("string"==typeof t.chat_type?t.chat_type:void 0)??("string"==typeof t.chatType?t.chatType:void 0)??("string"==typeof t.type?t.type:void 0)??("string"==typeof r?.chat_type?r.chat_type:void 0);if("chat:user"===s||"singleChat"===s)return"singleChat";if("chat:group"===s||"groupChat"===s)return"groupChat";if("chat:room"===s||"chatRoom"===s)return"chatRoom"}catch{}return null}resolveActionConversationId(e,t,r){return"singleChat"===r?e===this.context.userId?t:e:t}resolveOutboundMessageTarget(e,t){if("singleChat"!==t)return{name:e};const r=`${this.context.userId}/`;if(!e.startsWith(r))return{name:e};const s=e.slice(r.length);return s?{name:this.context.userId,clientResource:s}:{name:e}}resolveIncomingMessageParties(e,t,r){const s=this.readJid(e.from),n=this.readJid(e.to),i=this.readJid(t.from),o=this.readJid(t.to),a=i.name??s.name??"",c=o.name??n.name??"";if(!("singleChat"===r&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:s.clientResource&&s.clientResource!==this.context.clientResource?`${a}/${s.clientResource}`:a,receiverId:n.clientResource?`${c}/${n.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return fs;case"sendMessageReadReceipts":return hs;case"deliveryAck":return ps;case"recall":return ms;case"update":return gs;default:return ds}}resolveConversationType(e){return e===us?"groupChat":e===ls?"chatRoom":"singleChat"}resolveDirectedUsers(e){return"singleChat"===e.conversationType?[]:Array.isArray(e.receiverList)?e.receiverList:[]}resolveDeliverOnlineOnly(e){if("boolean"==typeof e.deliverOnlineOnly)return e.deliverOnlineOnly;if("cmd"===e.type){const t=e.body;return Boolean(t.deliverOnlineOnly)}return!1}resolveMetaExt(e){return"chatRoom"!==e.conversationType?[]:e.priority?_l({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?Bs:this.resolveDeliverOnlineOnly(e)?qs:Ds}resolveBroadcast(e){if(!Object.prototype.hasOwnProperty.call(e,"is_broadcast"))return;const t=e.is_broadcast;return"boolean"==typeof t?t:"number"==typeof t?0!==t:"string"==typeof t?"1"===t||"true"===t.toLowerCase():Boolean(t)}resolvePriority(e){if(!Object.prototype.hasOwnProperty.call(e,"chatroom_msg_tag"))return;const t=Number(e.chatroom_msg_tag);return 0===t?"high":2===t?"low":"normal"}resolveContentReplaced(e){const t=this.parseMetaPayload(e);if(t&&Object.prototype.hasOwnProperty.call(t,"callback_replace"))return Boolean(t.callback_replace)}resolveMessageMetaPayload(e,t){const r=this.parseMetaPayload(e),s=this.parseMetaPayload(t);return r&&s?{...s,...r}:r??s??e??t}resolvePeerRead(e,t,r){if("singleChat"!==t||"SEND"!==r)return;const s=this.parseMetaPayload(e);return"boolean"==typeof s?.isRead?s.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const r=this.parseMetaPayload(e),s=r?.group_read_ack;return"number"==typeof s&&Number.isInteger(s)&&s>=0?s:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),r=t?.edit_msg;if(!zp(r))return;const s="string"==typeof r.operator?r.operator:"",n=this.toFiniteNumber(r.count),i=this.toFiniteNumber(r.edit_time);return s&&void 0!==n&&void 0!==i?{operatorId:s,operationCount:n,operationTime:i}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),r=t?.thread;if(!zp(r)||0===Object.keys(r).length)return;const s=this.readString(r.msg_parent_id??r.messageId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.thread_name??r.chatThreadName);return{messageId:s,parentId:n,...i?{chatThreadName:i}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),r=t?.thread_overview??t?.threadOverview;if(!zp(r)||0===Object.keys(r).length)return;const s=this.readString(r.id??r.thread_id??r.chatThreadId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.name),o=this.resolveChatThreadOverviewLastMessage(r.last_message??r.lastMessage,s);return{chatThreadId:s,parentId:n,...i?{name:i}:{},...void 0!==o?{lastMessage:o}:{},...this.numberField("createdAt",r.create_timestamp??r.createdAt),...this.numberField("updatedAt",r.update_timestamp??r.updatedAt),...this.numberField("messageCount",r.message_count??r.messageCount)}}resolveChatThreadOverviewLastMessage(e,t){if(!zp(e)||0===Object.keys(e).length)return null;const r=this.readString(e.msgId??e.msg_id??e.id);if(!r)return null;const s=this.toFiniteNumber(e.timestamp)??0,n=this.resolveThreadLastMessagePayload(e),i=this.readString(n?.from)??this.readString(e.from)??"",o=this.readString(n?.to)??this.readString(e.to)??t,a=Array.isArray(n?.bodies)?n.bodies:[],c=zp(a[0])?a[0]:null,d=this.readString(c?.type)??this.readString(e.type),u=this.mapThreadMessageType(d),l=this.normalizeThreadLastMessageBody(u,c,e),h=t,p=i===this.context.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:h,conversationType:"groupChat",type:u,sendStatus:"sent",ext:zp(n?.ext)?n.ext:{},timestamp:s,body:l,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(zp(t))return t;if("string"==typeof t){const e=this.parseMetaPayload(t);if(e)return e}return null}mapThreadMessageType(e){switch(e){case"txt":default:return"text";case"img":return"image";case"loc":return"location";case"audio":return"voice";case"video":return"video";case"file":return"file";case"cmd":return"cmd";case"custom":return"custom";case"combine":return"combine";case"text":case"image":case"voice":case"location":return e}}normalizeThreadLastMessageBody(e,t,r){if(!t){return{content:this.readString(r.msg??r.content??r.text)??""}}switch(e){case"text":default:return{content:this.readString(t.msg??t.content??t.text)??""};case"image":{const e=this.readString(t.url)??"",r=ni(e,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(t.filename)??"image",filetype:this.readString(t.filetype)??"application/octet-stream",width:this.toFiniteNumber(t.width)??0,height:this.toFiniteNumber(t.height)??0,isGif:!0===t.isGif,isOriginalImage:!1,originalImageUrl:r.originalImageUrl,bigImageUrl:r.bigImageUrl,thumbnailUrl:this.readString(t.thumb)??r.thumbnailUrl,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)}}case"voice":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"voice",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"video":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"video",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,width:this.toFiniteNumber(t.width),height:this.toFiniteNumber(t.height),thumbnailUrl:this.readString(t.thumb),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"file":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"file",filetype:this.readString(t.filetype)??"application/octet-stream",secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"location":return{latitude:this.toFiniteNumber(t.lat??t.latitude)??0,longitude:this.toFiniteNumber(t.lng??t.longitude)??0,address:this.readString(t.addr??t.address),buildingName:this.readString(t.buildingName)};case"cmd":return{action:this.readString(t.action)??""};case"custom":return{event:this.readString(t.event??t.customEvent)??"",params:zp(t.params??t.customExts)?t.params??t.customExts:{}};case"combine":return{title:this.readString(t.title)??"",summary:this.readString(t.summary)??"",filename:this.readString(t.filename)??"combine",filetype:"application/octet-stream",url:this.readString(t.url),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength),combineLevel:this.toFiniteNumber(t.combineLevel)??0}}}readString(e){return"string"==typeof e&&e.length>0?e:void 0}numberField(e,t){const r=this.toFiniteNumber(t);return void 0===r?{}:{[e]:r}}parseMetaPayload(e){const t=this.normalizeMetaPayload(e);if(t){if(0===t.length)return null;try{const e=JSON.parse(Ri(t));return zp(e)?e:null}catch{return null}}if(zp(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return zp(t)?t:null}catch{return null}return null}toFiniteNumber(e){const t="number"==typeof e?e:"string"==typeof e?Number(e):Number.NaN;return Number.isFinite(t)?t:void 0}resolveReactions(e){const t=this.parseMetaPayload(e),r=t?.reaction;if(Array.isArray(r)&&0!==r.length)return r.filter(zp).map(e=>({reaction:"string"==typeof e.reaction?e.reaction:"",count:"number"==typeof e.count?e.count:0,userList:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof e.state?e.state:void 0}))}normalizeMetaPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null}mapPriorityToTag(e){return"high"===e?0:"low"===e?2:1}getRequestedCompressTypes(){return this.compressionFailureCount>=this.maxCompressionFailures?[]:[Gs]}configureCompression(e,t){if(!e||!e.includes(Gs))return void this.disableCompression();this.compressor||(this.compressor=new jp);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===Fp.UPLINK_ONLY||r===Fp.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===Fp.DOWNLINK_ONLY||r===Fp.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?Fp.UPLINK_ONLY:1===e?Fp.DOWNLINK_ONLY:2===e?Fp.BIDIRECTIONAL:Fp.NONE}disableCompression(){this.compressor&&(this.compressor.mode=Fp.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Vp=1e3,Wp="direct";class Jp{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 r=0;r<this.events.length;r+=1){const s=this.events[r];s&&s.appKey===e&&(this.events[r]={appKey:t,wire:{...s.wire,body:{...s.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 r=0;r<this.events.length&&t.length<this.batchSize;){const s=this.events[r];s?.appKey===e.appKey?(t.push(s.wire),this.events.splice(r,1)):r+=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 Zp{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 r=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});(r.status<200||r.status>=300)&&this.onFailure?.({reason:"non-success-response",status:r.status})}catch(r){this.onFailure?.({reason:"transport-error",message:r instanceof Error?r.message:String(r)})}else this.onFailure?.({reason:"request-adapter-unavailable",eventCount:t.length})}}const Qp={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},Yp=()=>{const e=Vi(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class Xp{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??Yp;const t=new Zp({requestAdapter:e.requestAdapter,debug:e.debug,now:this.now,onFailure:t=>{e.onDiagnostic?.("DataReport transport failed",t)}}),r=e.send??((e,r)=>t.send(e,r));this.queue=new Jp({send:r,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:Qp[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 r=`opr_${this.randomId()}`,s=this.now();let n=!1,i=!1,o=`req_${this.randomId()}`,a=0,c="";const d=()=>!n&&!i&&this.session?.sessionId===t,u=(t,s,n,i,o)=>{d()&&(a=o.success?0:o.code,c=o.success?"":o.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:s,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(n),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:o.code,codeDesc:o.description??"",isLastApi:0,isSuccess:o.success?1:0,accessChannel:this.session?.accessChannel??Wp,msgId:e.msgId,messageType:e.messageType,resultCount:o.resultCount}))},l=(e,t,r,s)=>{const n=this.now();let i=!1;return{retry:()=>(s.next+=1,l(e,t,s.next,s)),finish:s=>{i||(i=!0,u(e,t,r,n,s))}}};return{startRequest:(e={})=>(o=`req_${this.randomId()}`,l(e,o,1,{next:1})),finish:t=>{d()&&(n=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:o,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-s),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??c,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??Wp,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 r=this.session;if(!r||"disabled"===this.currentState)return;const s={lts:this.now(),net:this.networkType,appkey:r.appKey,sdkServiceId:r.serviceId,sdkProduct:0,uikitVersion:r.uikitVersion??"",...t},n={eventId:e,body:Object.fromEntries(Object.entries(s).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:r.appKey,wire:n})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let em;const tm=e=>{em?.updateSession(e)},rm=e=>{em?.applyDnsSwitch(e)},sm=e=>{em?.updateNetworkType(e)},nm=e=>{if("disabled"!==em?.state)return em?.startOperation(e)},im=()=>{em?.reset(),em=void 0};class om{constructor(e,r){this.serverUrlIndex=0,this.websocket=null,this.provisionTimeoutId=null,this.reconnectAttempts=0,this.messageReceiver=null,this.provisionPromise=null,this.provisionResolve=null,this.provisionReject=null,this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames=new Set,this.offlineMessageQueueReports=new Map,this.offlineMessageQueueCounts=new Map,this.offlineMessageTotalCount=0,this.reconnectTimerId=null,this.reconnectInProgress=!1,this.reconnectPaused=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.hasEverConnected=!1,this.isOnline=!0,this.internalHandlerId="__internal:connection-manager",this.suppressNextCloseEvent=!1,this.socketDisposers=[],this.inboundMessageQueue=Promise.resolve(),this.socketGeneration=0,this.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:3e4,autoReconnectNumMax:10,connectTimeout:1e4,...e},this.eventHub=r,this.msyncCodec=new Hp({appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,userId:e.userId,token:e.token,useReplacedMessageContents:e.useReplacedMessageContents,useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,serviceId:e.serviceId}),this.serverUrls=this.normalizeServerUrls(e),this.config.serverUrl=this.serverUrls[0]??this.config.serverUrl,this.connection={status:t,serverUrl:this.config.serverUrl,userId:e.userId,token:e.token,reconnectAttempts:0},this.connectionRetry=new pl({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new gl({interval:this.config.heartBeatWait,timeout:6e4}),this.connectionEventNormalizer=new Ai,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[m]:e=>{this.handleSendTimeout(e)}})}getConnectionStatus(){return this.connection.status}getWebSocket(){return this.websocket}getMsyncCodec(){return this.msyncCodec}getClientResource(){return this.msyncCodec.getContext().clientResource}setMessageReceiver(e){this.messageReceiver=e}renewToken(e,t){const r=Date.now();if(t<=r)throw new Wr("Token is expired",{code:lt,details:{stage:"token"}});return this.config.token=e,this.connection.token=e,this.msyncCodec.updateToken(e),this.setupTokenLifecycle(e,t,r),Si("Connection token renewed",{userId:this.config.userId,expireAt:t}),{token:e,expireAt:t}}handleOnline(){Si("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0;const e=this.offlineRecoverPending?S:C;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){Si("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.stopHeartbeat(),this.closeWebSocket(E,!0),Si("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void Si("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const e=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(T,!0,!0),this.resumeReconnect(T)}}catch(t){if(Si("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(T,!0,!0),this.resumeReconnect(T)}}resumeReconnect(e){this.isLoggedIn&&(this.reconnectInProgress?Si("Reconnect recovery skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.connection.status===s&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),Si("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===_&&Si("Message send timeout received without reconnect",e))}resetReconnectState(){this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connectionRetry.reset()}getReconnectDiagnostic(){return{status:this.connection.status,isOnline:this.isOnline,isLoggedIn:this.isLoggedIn,isLoginPhase:this.isLoginPhase,reconnectInProgress:this.reconnectInProgress,reconnectPaused:this.reconnectPaused,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId}}normalizeServerUrls(e){const t=(e.serverUrls??[]).filter(e=>"string"==typeof e&&e.length>0);return t.length>0?[...t]:[e.serverUrl]}pickNextServerUrl(){if(0===this.serverUrls.length)return this.config.serverUrl;const e=this.serverUrlIndex%this.serverUrls.length,t=this.serverUrls[e]??this.config.serverUrl;return this.serverUrlIndex=(e+1)%this.serverUrls.length,this.config.serverUrl=t,this.connection.serverUrl=t,t}resolveEffectiveMaxAttempts(){return this.isLoginPhase&&0===this.config.autoReconnectNumMax?1:this.config.autoReconnectNumMax}isNonRetryableError(e){if(!(e instanceof Wr))return!1;const t=e.details;if(!t||"object"!=typeof t)return!1;return!1===t.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(Ri(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null)}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay();Si("Reconnect retry scheduled",{delayMs:Math.round(e),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise(t=>{this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,t()},e)})}buildConnectionEventPayload(e,t){const r=this.connection.error instanceof Wr?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:r?.code,errorMessage:r?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,r){if(e===t&&!this.hasEverConnected)return;if(e===i&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===t||e===i))return;const s=this.buildConnectionEventPayload(e,r),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,r,n=!1){const i=this.connection.status!==e;(i||n)&&(i&&(this.connection.status=e,this.connection.lastConnectedAt=e===s?Date.now():void 0),r&&this.dispatchConnectionEvent(e,t),Ci("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:n}))}clampTimerDelay(e){return e<=0?0:Math.min(e,2**31-1)}clearTokenTimers(){this.tokenWillExpireTimerId&&(clearTimeout(this.tokenWillExpireTimerId),this.tokenWillExpireTimerId=null),this.tokenExpiredTimerId&&(clearTimeout(this.tokenExpiredTimerId),this.tokenExpiredTimerId=null)}setupTokenLifecycle(e,t,r=Date.now()){this.clearTokenTimers();const s=Math.max(t-r,0),n=r+Math.floor(.8*s);this.tokenLifecycle={token:e,issuedAt:r,expireAt:t,willExpireAt:n,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(n-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(e){if(e&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return void Si("Provision auth token has invalid payload");const r=Number(t.expires_in);if(!Number.isFinite(r))return void Si("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(t){Si("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,Si("Token will expire"),this.eventHub.dispatch(u,void 0))}emitTokenExpired(){this.tokenLifecycle||(this.tokenLifecycle={token:this.connection.token??"",issuedAt:Date.now(),expireAt:Date.now(),willExpireAt:Date.now(),willExpireEmitted:!0,expiredEmitted:!1});const e=this.tokenLifecycle;e.expiredEmitted||(e.expiredEmitted=!0,Si("Token expired"),this.eventHub.dispatch(l,void 0))}isTokenExpiredConnectionError(e){return e instanceof Wr&&e.code===lt}handleTokenExpiredDisconnect(e){Si("Connection closing because token expired",{source:e}),this.connection.error=new Wr("Token expired",{code:lt,details:{stage:"token",source:e,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(U,!0,!0),this.updateStatus(t,U,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(T)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,6e4)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(){if(!this.reconnectInProgress)if(this.connection.status!==s&&this.connection.status!==r){this.isLoginPhase=!0,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(I,!0),this.isLoggedIn=!0}catch(e){throw this.isLoggedIn=!1,e}finally{this.isLoginPhase=!1}}else Si("Connection already established or connecting")}async connectWithRetry(e,o){if(Si("Reconnect flow requested",{reason:e,throwOnFailure:o,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void Si("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()});if(this.connection.status===s&&this.websocket)return;if(this.reconnectPaused)return void Si("Reconnect flow skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let a=null,c=null;const d=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),Si("Reconnect flow started",{reason:e,throwOnFailure:o,maxAttempts:d,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<d;){this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const t=this.isLoginPhase?r:n;Si("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:d,reason:e,nextStatus:t,...this.getReconnectDiagnostic()}),this.updateStatus(t,e,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(e)}catch(u){if(a=u,Si("Connection attempt failed",{attempt:this.reconnectAttempts,reason:e,error:a}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(a))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(a)){c=a;break}}if(this.connectionRetry.getAttemptCount()>=d)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){Si("Reconnect retry loop interrupted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:d,...this.getReconnectDiagnostic()});break}await this.waitForReconnectDelay()}if(c){if(this.connection.error=c,o)throw this.updateStatus(t,A,!1),c;return this.reconnectPaused=!0,void this.updateStatus(t,A,!0)}if(o)throw this.updateStatus(t,A,!1),a??new Wr("Connection failed",{code:gt,details:{stage:"ws"}});this.reconnectPaused=!0,Si("Reconnect attempts exhausted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:d,lastError:a,...this.getReconnectDiagnostic()}),this.updateStatus(i,M,!0)}finally{this.reconnectInProgress=!1,Si("Reconnect flow finished",{reason:e,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(w,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(s,e,!0),this.hasEverConnected=!0,this.connection.error=void 0,this.resetReconnectState(),this.offlineRecoverPending=!1,this.reconnectPaused=!1,this.sendPostProvisionInitialSync(),this.websocket&&this.startHeartbeat(this.websocket),Si("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}async triggerReconnect(e){Si("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.isLoggedIn?this.reconnectInProgress?Si("Reconnect trigger skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.reconnectPaused?Si("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}):(this.connection.status===s&&this.websocket&&this.closeWebSocket(e,!0,!0),await this.connectWithRetry(e,!1)):Si("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()})}handleDisconnection(e){Si("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t,e,!0),e!==U&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(e))}closeWebSocket(e,r,s=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),s&&this.updateStatus(t,e,r)):s&&this.updateStatus(t,e,r)}createWebSocketConnection(){return new Promise((e,t)=>{const r=this.pickNextServerUrl();Ci("WebSocket connecting",{url:r}),this.clearSocketListeners();let s=!1;const n=setTimeout(()=>{s=!0,Si("WebSocket connection attempt timed out",{url:r,connectTimeout:this.config.connectTimeout,...this.getReconnectDiagnostic()}),t(new Wr("Connection timeout",{code:ft,details:{stage:"ws"}}))},this.config.connectTimeout);this.socketAdapter.connect({url:r,timeoutMs:this.config.connectTimeout}).then(i=>{if(clearTimeout(n),s||this.reconnectPaused)return Si("WebSocket connection result discarded",{url:r,cancelled:s,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void i.close();this.websocket=i,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(i,this.socketGeneration),this.startProvision().then(()=>{if(this.resetProvisionHandlers(),s||this.reconnectPaused)return Si("Provision result discarded",{url:r,cancelled:s,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void this.closeWebSocket(A,!1,!1);e()}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(A,!1,!1),t(e instanceof Error?e:new Error(String(e)))})}).catch(e=>{if(clearTimeout(n),s)return;const r=e instanceof Wr?e:new Wr("Failed to create WebSocket",{code:gt,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});this.handleConnectionError(r,A),t(r)})}).catch(e=>{if(e instanceof Wr)throw e;const t=new Wr("Failed to create WebSocket",{code:gt,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});throw this.handleConnectionError(t,A),t})}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(Si("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(R))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new Wr("Provision interrupted",{code:It,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,t){if(Ti("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(t)}handleTerminalConnectionError(e,r){if(Si("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(t,r,!0,!0)}async handleWebSocketMessage(e,t){try{if(t!==this.socketGeneration)return;Ci("WebSocket message received",{dataType:typeof e});const s=await this.msyncCodec.normalizeIncoming(e);if(t!==this.socketGeneration)return;if(Ci("handleWebSocketMessage data",{length:s.length}),!s.length)return;const n=this.msyncCodec.decompressIncoming(s);if(!n){const e=null!==this.provisionReject;return Ti("Failed to decompress mSync payload, closing connection",{stage:e?"provision":"connected"}),void(e?(this.rejectPendingProvision(new Wr("Failed to decompress Provision payload",{code:gt,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(A,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(n))return void Ci("Ignore server normal close payload",{length:n.length});let i=null;try{i=this.msyncCodec.decodeMsync(n)}catch(r){const e=r instanceof Error?r:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void Si("Discard invalid mSync payload",{length:n.length,message:e.message,prefixHex:Array.from(n.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(n.subarray(Math.max(0,n.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw Si("Invalid mSync payload signature",{length:n.length,prefixHex:Array.from(n.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),Ci("handleWebSocketMessage decoded",{command:i.command}),i.command){case os:this.handleProvisionMessage(i.payload);break;case as:this.handleLogoutMessage(i.payload);break;case is:this.handleNoticeMessage(i.payload);break;case ns:this.handleUnreadMessage(i.payload);break;case ss:this.handleSyncMessage(i.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");Ti("Failed to handle mSync payload",e),this.handleConnectionError(e,A)}}startProvision(){this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(new Wr("Provision timeout",{code:vt,details:{stage:"provision",retryable:!0}}))},1e4);try{const e=this.msyncCodec.encodeProvision();Ci("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new Wr("Provision send failed",{code:gt,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(e){const t=this.msyncCodec.decodeProvision(e);if(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t.ok)this.msyncCodec.updateResource(t.resource),this.setupTokenLifecycleFromProvision(t.authToken),this.provisionResolve?.();else{Si("Provision rejected",{statusCode:t.statusCode,reason:t.reason});const e=kn(t.statusCode,t.reason),r=e.code===Gr?bt:e.code;this.provisionReject?.(new Wr("Provision rejected",{code:r,details:{stage:"provision",reason:t.reason,statusCode:t.statusCode,retryable:e.retryable}}))}}handleNoticeMessage(e){const{queue:t}=this.msyncCodec.decodeNotice(e),r=t?this.getQueueId(t):null,s=!!t&&this.isSelfQueue(t),n=!!t&&this.isQueueInList(t);t&&r&&(s||n||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(e){const{queues:t}=this.msyncCodec.decodeUnread(e),r=t.filter(e=>this.getQueueId(e));if(r.length){r.length!==t.length&&Si("Unread queues without usable identity were ignored",{ignoredCount:t.length-r.length}),this.startOfflineMessageSync(r);for(const e of r)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(e){const t=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(t)return void this.handleTerminalConnectionError(t,A);if(!this.messageReceiver)return;const r=this.messageReceiver.handleSyncPayload(e);if(Ci("handleSyncMessage result",{result:r}),!r)return;(void 0!==r.queue||void 0!==r.nextKey||void 0!==r.isLast)&&this.handleSyncQueueState(r)}handleSyncQueueState(e){Ci("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:r,queueId:s}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(s)){const t=this.offlineMessageQueueCounts.get(s)??0;this.offlineMessageQueueCounts.set(s,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const n=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(s),this.removeQueueEntry(r),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(n){if(n!==this.nextKey||!this.isSameQueue(r,this.currentQueue))return this.nextKey=n,this.currentQueueId=s,this.currentQueue=r,void this.sendLastSession(r,n);this.removeQueueEntry(r),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,r=t?this.getQueueName(t):null,s=t?this.getQueueId(t):null,n=void 0!==t&&null!==s&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&s&&n)return{queue:t,queueId:s};const i=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,o=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,a=i??o??this.queues[0],c=a?this.getQueueName(a):null,d=a?this.getQueueId(a):null;return a&&d?(Si("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:r,responseQueueId:s,fallbackQueueName:c,fallbackQueueId:d,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:e.isLast,hasNextKey:Boolean(e.nextKey)}),{queue:a,queueId:d}):null}handleLogoutMessage(e){const t=this.msyncCodec.decodeLogout(e);Si("Logout message received",t)}resolveStatisticDisconnectError(e){for(const t of e)switch(t.operation){case 1:return new Wr("User has been removed",{code:Ht,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 2:return new Wr("The user is already logged on another device",{code:Kt,details:{stage:"statistics",operation:t.operation,retryable:!1,...t.reason?{loginInfoCustomExt:t.reason}:{}}});case 3:return new Wr("The user was kicked by changing password",{code:Vt,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 4:return new Wr("The user was kicked by other device",{code:Wt,details:{stage:"statistics",operation:t.operation,retryable:!1}})}return null}resetProvisionHandlers(){this.provisionResolve=null,this.provisionReject=null,this.provisionPromise=null}rejectPendingProvision(e){const t=this.provisionReject;return!!t&&(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t(e),this.resetProvisionHandlers(),!0)}disconnect(){return this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.clearReconnectTimer(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.offlineRecoverPending=!1,this.closeWebSocket(R,!0,!0),this.updateStatus(t,R,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),Si("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){if(e.socketAdapter)return e.socketAdapter;const t=Hd({webSocketCtor:"function"==typeof WebSocket?WebSocket:void 0});if(t)return t;throw Fi("Socket capability is missing for current platform",{code:"PLATFORM_MISSING_CAPABILITY",stage:"socket",retryable:!1,details:{capability:"socket"}})}attachSocketListeners(e,t){this.clearSocketListeners(),this.socketDisposers=[e.onMessage(r=>{this.websocket===e&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(r,t)))}),e.onError(()=>{if(this.websocket!==e)return;Si("WebSocket error",{stage:"ws"});const t=new Wr("WebSocket connection error",{code:gt,details:{stage:"ws"}});this.handleConnectionError(t,A)}),e.onClose(t=>{this.websocket===e&&this.handleWebSocketClose(t)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===ji)try{const t=this.msyncCodec.prepareOutgoing(e);Ci("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{Ti("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){Ti("Failed to send mSync payload",t),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const t=this.msyncCodec.encodeBackQueue(e);Ci("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){Ci("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const r=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(r)}sendNextQueue(){Ci("sendNextQueue queues",{size:this.queues.length});const e=this.queues[0];e&&this.sendBackqueue(e)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(e){const t=new Set;for(const r of e){const e=this.getQueueId(r);e&&t.add(e)}if(0!==t.size){for(const e of t)this.offlineMessageQueueNames.add(e);if(!this.offlineMessageSyncing){this.offlineMessageSyncing=!0,this.offlineMessageSyncLifecycleActive=!this.offlineMessageSyncLifecycleDispatched,this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleDispatched=!0),this.offlineMessageTotalCount=0,this.offlineMessageQueueCounts.clear(),this.offlineMessageQueueReports.clear(),this.offlineMessageReport=nm({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of t){this.offlineMessageQueueCounts.set(e,0);const t=this.offlineMessageReport?.startRequest({requestName:"MSYNC_SYNCOFFLINEMESSAGE",method:"WS",url:e});t&&this.offlineMessageQueueReports.set(e,t)}this.offlineMessageSyncLifecycleActive&&this.eventHub.dispatch(h,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const t=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:t}),this.offlineMessageQueueReports.delete(e),this.offlineMessageQueueNames.delete(e),this.offlineMessageQueueNames.size>0||(this.offlineMessageSyncing=!1,this.offlineMessageReport?.finish({code:0,success:!0,resultCount:this.offlineMessageTotalCount}),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleActive=!1,this.eventHub.dispatch(p,void 0)))}isQueueInList(e){return this.queues.some(t=>this.isSameQueue(t,e))}isSelfQueue(e){const t=this.getQueueName(e),r=this.getQueueResource(e),s=this.msyncCodec.getContext();return t===s.userId&&r===s.clientResource}getQueueName(e){return"string"==typeof e.name&&e.name.trim().length>0?e.name:null}getQueueResource(e){return this.getQueueField(e,"clientResource")}getQueueId(e){const t=this.getQueueName(e);if(t)return`name:${t}`;const r=this.getQueueField(e,"domain"),s=this.getQueueResource(e);if(r)return`domain:${r}|resource:${s??""}`;if(s)return`resource:${s}`;const n=this.getQueueField(e,"appKey");return n?`appKey:${n}`:null}getQueueField(e,t){const r=e[t];return"string"==typeof r&&r.trim().length>0?r:null}isSameQueue(e,t){if(!e||!t)return!1;const r=this.getQueueId(e),s=this.getQueueId(t);return null!==r&&r===s}resetSyncState(){this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames.clear(),this.offlineMessageReport?.discard(),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageTotalCount=0}}const am=new class{constructor(){this.store=new Map}set(e,t){e&&this.store.set(e,t)}get(e){if(e)return this.store.get(e)}consume(e){const t=this.get(e);return t&&this.store.delete(e),t}delete(e){e&&this.store.delete(e)}clear(){this.store.clear()}},cm=e=>{if((e=>"undefined"!=typeof File&&e instanceof File)(e)){if("undefined"==typeof URL||"function"!=typeof URL.createObjectURL)return;return URL.createObjectURL(e)}return(e=>"object"==typeof e&&null!==e&&"path"in e&&"string"==typeof e.path)(e)?e.path:(e=>"object"==typeof e&&null!==e&&"uri"in e&&"string"==typeof e.uri)(e)?e.uri:void 0},dm=()=>{const e=Vi().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},um=new Uint8Array([99,109]),lm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),hm=e=>Array.isArray(e)&&e.every(lm),pm=e=>"string"==typeof e?e:void 0,mm=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,fm=e=>{const t=new Uint8Array(4);return t[0]=e>>>24&255,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=255&e,t},gm=(e,t)=>{const r=e[t],s=e[t+1],n=e[t+2],i=e[t+3];if("number"!=typeof r||"number"!=typeof s||"number"!=typeof n||"number"!=typeof i)throw new Yr("Combine payload length header is invalid",{code:lr});return r<<24|s<<16|n<<8|i},ym=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},vm=(e,t)=>{const r=vl().lookupType(e).decode(t);if(!lm(r))throw new Error(`${e} decoded result is invalid`);return r},bm=e=>lm(e)&&"string"==typeof e.name?e.name:"",Im=(e,t,r)=>{const s=(hm(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=mm(e.type)??ys,r=Boolean(pm(e.remotePath))||Boolean(pm(e.title))||Boolean(pm(e.summary))||(mm(e.combineLevel)??0)>0,s=t===ys&&0===e.subType&&r;if(t===_s||s){const t=mm(e.combineLevel)??0;return{type:"combine",body:{title:pm(e.title)??"",summary:pm(e.summary)??"",filename:pm(e.displayName)??"combine",filetype:"application/octet-stream",url:pm(e.remotePath),secret:pm(e.secretKey),fileLength:mm(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ys)return{type:"text",body:{content:pm(e.text)??""}};if(t===Ss)return{type:"cmd",body:{action:pm(e.action)??""}};if(t===Ts){const t=Rl(hm(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:pm(e.customEvent)??"",params:t}}}if(t===Is)return{type:"location",body:{latitude:mm(e.latitude)??0,longitude:mm(e.longitude)??0,address:pm(e.address),buildingName:pm(e.buildingName)}};if(t===vs){const t=lm(e.size)?e.size:{},r=pm(e.remotePath)??"",s=ni(r),n=pm(e.thumbnailRemotePath),i=oi(e.imageType)===Wn;return{type:"image",body:{localUrl:"",filename:pm(e.displayName)??"image",filetype:"application/octet-stream",width:mm(t.width)??0,height:mm(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:pm(e.secretKey),fileLength:mm(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===bs){const t=lm(e.size)?e.size:{};return{type:"video",body:{url:pm(e.remotePath)??"",filename:pm(e.displayName)??"video",filetype:"application/octet-stream",duration:mm(e.duration)??0,width:mm(t.width),height:mm(t.height),secret:pm(e.secretKey),fileLength:mm(e.fileLength),thumbnailUrl:pm(e.thumbnailRemotePath)}}}if(t===ws)return{type:"voice",body:{url:pm(e.remotePath)??"",filename:pm(e.displayName)??"voice",filetype:"application/octet-stream",duration:mm(e.duration)??0,secret:pm(e.secretKey),fileLength:mm(e.fileLength)}};if(t===Cs)return{type:"file",body:{url:pm(e.remotePath)??"",filename:pm(e.displayName)??"file",filetype:"application/octet-stream",secret:pm(e.secretKey),fileLength:mm(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const i=bm(e.from)||bm(r?.from)||`unknown-${t}`,o=bm(e.to)||bm(r?.to)||`unknown-${t}`,a=(c=e.type)===us?"groupChat":c===ls?"chatRoom":"singleChat";var c;const d=o||i,u=Number(Tl(r?.timestamp))||Date.now(),l=Rl(hm(e.ext)?e.ext:void 0),h={msgServerId:Tl(r?.id),msgLocalId:"",type:n.type,sender:{userId:i},conversationId:d,conversationType:a,timestamp:u,body:n.body,ext:l};return"number"==typeof n.combineLevel&&(h.body.combineLevel=n.combineLevel),h},wm=(e,t)=>{const r=[];try{const n=vm("easemob.pb.Meta",e),i=(s=n.payload)instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):void 0;if(i&&i.length>0){const e=vm("easemob.pb.MessageBody",i);return Im(e,t,n)}r.push("Meta payload is empty")}catch(n){r.push(n instanceof Error?n.message:String(n))}var s;try{const r=vm("easemob.pb.MessageBody",e);return Im(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=vm("easemob.pb.MessageBody.Content",e);return Im({type:ds,from:{name:`unknown-${t}`},to:{name:`unknown-${t}`},contents:[r],ext:[]},t)}catch(n){r.push(n instanceof Error?n.message:String(n))}throw new Error(r.join("; "))},Cm=(e,t)=>{const r=Ri(e);try{const e=JSON.parse(r);if(!lm(e))throw new Yr("Combine payload item is invalid",{code:lr,details:{index:t}});return e}catch(s){if(s instanceof Yr)throw s;try{return wm(e,t)}catch(n){throw new Yr("Combine payload item parse failed",{code:lr,details:{index:t,cause:s instanceof Error?s.message:String(s),protobufCause:n instanceof Error?n.message:String(n)}})}}},Sm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Tm=(e,t,r)=>{throw new Zr(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},_m=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:Sm(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},Rm=(e,t)=>{if(e.sender.userId||Tm(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,or),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||Tm(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,or),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&Tm(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,or),Sm(e.body)||Tm(`messageList[${t}] body must be object`,`messageList[${t}].body`,or),"combine"===e.type){const r=_m(e);(!Number.isInteger(r)||r<0)&&Tm(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,or),r>10&&Tm(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ar)}},Am=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&Tm("messageList must not be empty","messageList",or),(!Number.isInteger(t)||t<=0||t>300)&&Tm("max items is invalid","maxItems",or),e>t&&Tm(`messageList max length is ${t}`,"messageList",cr)},Mm=e=>{Am(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?Rm(r,t):Tm(`messageList[${t}] is required`,`messageList[${t}]`,or)}},Em=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=_m(r);e>t&&(t=e)}return t+1},Um=e=>{(!Number.isInteger(e)||e<=0)&&Tm("combineLevel must be positive integer","combineLevel",or),e>10&&Tm("combineLevel must be <= 10","combineLevel",ar)},Nm=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class km{constructor(e,t,r,s){this.websocket=null,this.pendingMessages=new Map,this.ackTimeout=15e3,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=t,this.eventHub=r,this.msyncCodec=e,this.attachmentUploader=s??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(e,t){const r=this.msyncCodec.toProtocolId(e.msgLocalId);if(st(e))throw new Qr("Stream message send is not supported",{code:ir,details:{msgLocalId:e.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==ji){const t=this.msyncCodec.toProtocolId(e.msgLocalId);throw new Qr("WebSocket is not connected",{code:St,details:{msgLocalId:e.msgLocalId,protocolId:t,retryable:!0}})}let s={...e,sendStatus:"sending"};wh(e,s),Ci("Message send queued",{msgLocalId:e.msgLocalId,protocolId:r,type:e.type,conversationType:e.conversationType,conversationId:e.conversationId});try{const e="combine"===s.type?this.prepareCombineMessage(s):s,r={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,t):e,sendStatus:"sending"};wh(s,r),s=r,t?.onSending?.(r);const n=await this.doSendMessage(r);return t?.onSuccess?.(n),n}catch(n){const e={...s,sendStatus:"failed"};throw wh(s,e),t?.onFailed?.(e,n instanceof Error?n:new Error(String(n))),n}}async sendAction(e,t){const r=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&Ci("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:r,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const s=this.msyncCodec.encodeActionMessage(e,r);"clearAllConversationUnreadMessageCount"===e.kind&&Ci("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:r,payloadBytes:s.byteLength});const n="recall"===e.kind?"MSYNC_RECALLMESSAGE":"update"===e.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${e.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"message",operationName:n,operationType:"MESSAGE",requestName:n,msgId:e.messageId,messageType:Nm(e.conversationType)}))}async sendChatRoomOperation(e,t){const r=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),s=this.msyncCodec.encodeChatRoomOperation(e,r),n="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"chatroom",operationName:n,operationType:"CHATROOM",requestName:n,msgId:e.chatRoomId}))}async doSendMessage(e){const t=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:e.msgLocalId,messageType:Nm(e.conversationType)});return new Promise((r,s)=>{const n=this.msyncCodec.toProtocolId(e.msgLocalId),i=setTimeout(()=>{this.pendingMessages.delete(n),this.finishPendingDataReport(t,{code:Tt,success:!1,description:"Message ACK timeout"}),s(new Qr("Message ACK timeout",{code:Tt,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(n,{kind:"message",message:e,protocolId:n,timeoutId:i,resolve:e=>{clearTimeout(i),r(e)},reject:e=>{clearTimeout(i),s(e)},report:t});try{if(!this.websocket||this.websocket.readyState!==ji)throw new Qr("WebSocket is not connected",{code:St,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(e,n),o=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(o)).catch(r=>{const o=r instanceof Error?r.message:String(r);this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:-1,success:!1,description:o}),Si("Message send socket failure",{msgLocalId:e.msgLocalId,protocolId:n,websocketReadyState:this.websocket?.readyState??null,cause:o}),s(new Qr(`WebSocket send failed: ${o}`,{code:St,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0,cause:o}}))}),Ci("Message sent",{msgLocalId:e.msgLocalId,protocolId:n})}catch(o){if(this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:o instanceof Qr?o.code:At,success:!1,description:o instanceof Error?o.message:String(o)}),o instanceof Qr)throw o;throw new Qr("Message encode failed",{code:At,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}})}})}async sendProtocolPayload(e,t,r,s){return new Promise((n,i)=>{const o=setTimeout(()=>{this.pendingMessages.delete(e),this.finishPendingDataReport(s,{code:Tt,success:!1,description:"Message ACK timeout"}),i(new Qr("Message ACK timeout",{code:Tt,details:{protocolId:e,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(e,{kind:"action",protocolId:e,timeoutId:o,createAckError:r,resolve:n,reject:i,report:s});try{if(!this.websocket||this.websocket.readyState!==ji)throw new Qr("WebSocket is not connected",{code:St,details:{protocolId:e,retryable:!0}});const r=this.msyncCodec.prepareOutgoing(t);Promise.resolve(this.websocket.send(r)).catch(t=>{const r=t instanceof Error?t.message:String(t);this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:-1,success:!1,description:r}),i(new Qr(`WebSocket action send failed: ${r}`,{code:St,details:{protocolId:e,retryable:!0,cause:r}}))})}catch(a){if(this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:a instanceof Qr?a.code:At,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof Qr)throw a;i(new Qr("Message encode failed",{code:At,details:{protocolId:e,retryable:!1}}))}})}prepareCombineMessage(e){const t=e.body,r=t.messageList??[];Mm(r);const s=Em(r);Um(s);const n=(e=>{try{const t=e.map((e,t)=>{const r=JSON.stringify(e);if(!r)throw new Qr("Combine payload item encode failed",{code:dr,details:{index:t}});return _i(r)}),r=um.length+t.reduce((e,t)=>e+4+t.length,0)+1,s=new Uint8Array(r);let n=0;s.set(um,n),n+=um.length;for(const e of t){const t=fm(e.length);s.set(t,n),n+=t.length,s.set(e,n),n+=e.length}const i=ym(s.subarray(0,s.length-1));return s[s.length-1]=i,s}catch(t){if(t instanceof Qr)throw t;throw new Qr("Combine payload encode failed",{code:dr,details:{cause:t instanceof Error?t.message:String(t)}})}})(r),i=new ArrayBuffer(n.byteLength);new Uint8Array(i).set(n);const o=new File([i],t.filename||"combine",{type:t.filetype||"application/octet-stream"}),a=cm(o);if(!a&&!this.attachmentUploader)throw new Qr("Combine payload local url generation failed",{code:dr});am.set(e.msgLocalId,o);const c={...e,body:{...t,combineLevel:s,fileLength:n.byteLength,filename:t.filename||"combine",filetype:t.filetype||"application/octet-stream",url:a??t.url}};return wh(e,c),Rh(e,c),c}handleAck(e,t,r,s){const n=this.pendingMessages.get(e);if(!n)return void Ci("Received ACK without a tracked pending message",{protocolId:e});if("action"===n.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),void n.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:s});const i={...n.message,...this.resolveReplacedMessage(n.message,r),sendStatus:"sent",msgServerId:t||r?.msgServerId||n.message.msgServerId};wh(n.message,i),this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),"image"!==i.type&&"video"!==i.type&&"voice"!==i.type&&"file"!==i.type&&"combine"!==i.type||am.delete(i.msgLocalId),Ci("Message ACK matched",{protocolId:e,msgLocalId:i.msgLocalId,msgServerId:i.msgServerId??null,type:i.type,conversationType:i.conversationType,conversationId:i.conversationId}),this.eventHub.dispatch(b,i),n.resolve(i)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const r=this.pendingMessages.get(e);if(!r)return;if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof Qr?t.code:-1,success:!1,description:t.message}),void r.reject(t);const s={...r.message,sendStatus:"failed"};wh(r.message,s),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof Qr?t.code:-1,success:!1,description:t.message}),Si("Message send failed after ACK/error",{protocolId:e,msgLocalId:s.msgLocalId,type:s.type,conversationType:s.conversationType,conversationId:s.conversationId,error:t.message}),r.reject(t)}handleAckFailure(e,t,r,s){const n=this.pendingMessages.get(e);if(n)return"action"===n.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t,success:!1,description:r??s.message}),void n.reject(n.createAckError?.(t,r)??s)):void this.handleSendError(e,s)}setWebSocket(e){this.websocket=e}destroy(){for(const[e,t]of this.pendingMessages)clearTimeout(t.timeoutId),this.finishPendingDataReport(t.report,{code:-1,success:!1,description:"Message sender destroyed"}),t.reject(new Qr("Message sender destroyed",{code:Rt,details:"message"===t.kind?{msgLocalId:t.message.msgLocalId,protocolId:e,retryable:!1}:{protocolId:e,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(e){if(("message"===e.category?this.messageReportCount:this.chatRoomReportCount)>=Vp){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(Si("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=nm({operationName:e.operationName,operationType:e.operationType,msgId:e.msgId,messageType:e.messageType});if(t)return"message"===e.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:e.category,operation:t,request:t.startRequest({requestName:e.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(e,t){e&&!e.released&&(e.released=!0,e.request.finish(t),e.operation.finish(t),"message"===e.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<Vp&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<Vp&&(this.chatRoomReportSaturated=!1)))}}class Om{constructor(e){this.sessions=new Map,this.ttlMs=e?.ttlMs??3e5,this.maxSessions=e?.maxSessions??100}getOrCreate(e){this.evictStale();const t=this.sessions.get(e);if(t)return t.lastActivityTs=Date.now(),t;this.sessions.size>=this.maxSessions&&this.evictOldest();const r={msgId:e,startSeq:null,lastDispatchedSeq:-1,fullText:"",completed:!1,chunksBySeq:new Map,lastActivityTs:Date.now()};return this.sessions.set(e,r),r}get(e){return this.sessions.get(e)}addChunk(e,t){const r=this.getOrCreate(e),s=t.stream.seq;return r.chunksBySeq.has(s)?{duplicate:!0,session:r}:(r.chunksBySeq.set(s,t),r.lastActivityTs=Date.now(),t.stream.status!==rt.START&&t.stream.status!==rt.START_COMPLETED||null!==r.startSeq||(r.startSeq=s),{duplicate:!1,session:r})}getSequentialChunks(e){const t=this.sessions.get(e);if(!t||t.completed||null===t.startSeq)return[];let r=t.lastDispatchedSeq<t.startSeq?t.startSeq:t.lastDispatchedSeq+1;const s=[];for(;t.chunksBySeq.has(r);){const e=t.chunksBySeq.get(r);if(!e)break;s.push(e),r+=1}return s}markDispatched(e,t,r){const s=this.sessions.get(e);if(!s)return;const n=t.stream.seq;s.lastDispatchedSeq=Math.max(s.lastDispatchedSeq,n),s.fullText=r,s.chunksBySeq.delete(n)}markCompleted(e,t,r){const s=this.getOrCreate(e);s.completed=!0,s.completedReason=t,s.fullText=r}clear(e){this.sessions.delete(e)}clearAll(){this.sessions.clear()}evictStale(){const e=Date.now();for(const[t,r]of this.sessions)e-r.lastActivityTs>this.ttlMs&&this.sessions.delete(t)}evictOldest(){let e=null,t=1/0;for(const[r,s]of this.sessions)s.lastActivityTs<t&&(t=s.lastActivityTs,e=r);e&&this.sessions.delete(e)}}class xm{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new Om}handle(e){const t=this.resolveMessageId(e);if(!t)return void Si("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void Ci("stream message already completed, ignore",{msgId:t});if(e.stream.status===rt.FULL)return void this.handleFullChunk(t,e);const r=this.cache.get(t);if(r?.completed)return void Ci("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:s}=this.cache.addChunk(t,e);s?Ci("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const r of t){const t=this.cache.get(e);if(!t)return;const s=t.fullText,n=r.stream.deltaText,i=`${s}${n}`,o=r.stream.errorType>0?rt.ERROR:r.stream.status,a=this.buildDispatchMessage(r,{status:o,fullText:i,deltaText:n});if(this.eventHub.dispatch(k,a),this.cache.markDispatched(e,r,i),o===rt.START_COMPLETED||o===rt.COMPLETED||o===rt.ERROR){const t=o===rt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else Ci("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=!r||-1===r.lastDispatchedSeq&&0===r.chunksBySeq.size,a=t.stream.errorType>0?rt.ERROR:o?rt.START_COMPLETED:rt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:n,deltaText:i});this.eventHub.dispatch(k,c);const d=a===rt.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,d,n),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=this.buildDispatchMessage(t,{status:rt.ERROR,fullText:n,deltaText:i});this.eventHub.dispatch(k,o),this.cache.markCompleted(e,"timeout_error",n),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const r=e.stream.fullText;if(r&&r.length>=t.length)return r;const s=e.body.content;return s&&s.length>=t.length?s:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,r){return t.startsWith(e)?t.slice(e.length):r}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class Lm{constructor(e=100){this.seenIds=new Set,this.orderedIds=[],this.limit=Math.max(1,Math.floor(e))}checkAndRecord(e){if(!e)return!1;if(this.seenIds.has(e))return!0;for(this.seenIds.add(e),this.orderedIds.push(e);this.orderedIds.length>this.limit;){const e=this.orderedIds.shift();e&&this.seenIds.delete(e)}return!1}clear(){this.seenIds.clear(),this.orderedIds.length=0}size(){return this.seenIds.size}}const Pm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Dm{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new xm(r),this.messageContexts=new Map,this.recentMessageIds=new Lm(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(e){try{Ci("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);Ci("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:r,messages:s}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),r&&(Ci("Decoded sync ACK",{ok:r.ok,protocolId:r.protocolId,serverId:r.serverId??null,statusCode:r.statusCode??null,reason:r.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(r,t.replacedMessage));for(const e of s)this.dispatchMessage(e);return t}catch(t){Ti("Failed to decode sync payload",t)}return null}handleAck(e,t){if(e.ok)return Ci("ACK accepted",{protocolId:e.protocolId,serverId:e.serverId??null,hasReplacedMessage:Boolean(t)}),void(e.chatRoomInfo?this.messageSender.handleAck(e.protocolId,e.serverId,t,e.chatRoomInfo):this.messageSender.handleAck(e.protocolId,e.serverId,t));Si("ACK rejected",{protocolId:e.protocolId,statusCode:e.statusCode,reason:e.reason,hasReplacedMessage:Boolean(t)});const r=((e,t)=>{const r=kn(e,t),s=r.code===Gr?_t:r.code;return{code:s,message:On[s]??(t?`Message send failed: ${t}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(e.statusCode,e.reason),s=new Qr(r.message,{code:r.code,details:{protocolId:e.protocolId,serverCode:e.statusCode,reason:e.reason,retryable:!1}});this.messageSender.handleAckFailure(e.protocolId,e.statusCode,e.reason,s)}dispatchMessage(e){if(st(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?Ci("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(N,e),Ci("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const t=this.msyncCodec.getContext().userId;t&&e.from!==t&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{Si("Failed to send delivery ack",e)})}handleNotifies(e){const t=[];for(const r of e)if("presence"===r.type)this.handlePresenceNotify(r);else if("contact"===r.type)this.handleContactNotify(r);else if("group"===r.type)this.handleGroupNotify(r);else if("thread"===r.type)this.handleChatThreadNotify(r);else if("chatroom"===r.type)this.handleChatRoomNotify(r);else if("reaction"===r.type)this.handleReactionNotify(r);else if("conv"===r.type)this.handleConversationNotify(r);else if("multiDevice"===r.type)this.handleMultiDeviceNotify(r);else if("message_receipts"===r.type){const e=this.toMessageReceiptPayload(r);e&&t.push(e)}else"message_recalled"===r.type?this.handleMessageRecalledNotify(r):"message_updated"===r.type?this.handleMessageUpdatedNotify(r):"message_delivered"===r.type?this.handleMessageDeliveredNotify(r):this.handleUserInfoNotify(r);t.length>0&&this.eventHub.dispatch(x,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const r=e.data;if(!r||"object"!=typeof r)return;const s=r,n="string"==typeof s.username?s.username:"string"==typeof s.userId?s.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",i=s.metadata&&"object"==typeof s.metadata&&!Array.isArray(s.metadata)?s.metadata:null,o="number"==typeof s.lastModified?s.lastModified:"string"==typeof s.lastModified?Number(s.lastModified):Number.NaN;if(!n||!i||!Number.isFinite(o))return;const a={notifyType:t,userId:n,metadata:i,lastModified:o};this.eventHub.dispatch(v,a)}handleContactNotify(e){if(Ci("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==K&&e.eventName!==H&&e.eventName!==V&&e.eventName!==W&&e.eventName!==J)return;const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.from&&r.from&&"string"==typeof r.to&&r.to&&"string"==typeof r.message&&this.eventHub.dispatch(e.eventName,r)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t,s=Array.isArray(r.values)?r.values:[];if(0===s.length)return;const n=[];for(const i of s){if(!i||"object"!=typeof i)continue;const e=i,t=this.normalizePresenceStatus(e.status),r="string"==typeof e.uid?e.uid:"";r&&n.push({userId:r,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==n.length&&this.eventHub.dispatch(z,n)}handleGroupNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(f,r)}handleChatRoomNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(g,r)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const r of t){if(!Pm(r)||"string"!=typeof r.messageId)continue;const e=this.resolveReactionConversationContext(r);e&&this.eventHub.dispatch(q,{messageId:r.messageId,conversationId:e.conversationId,conversationType:e.conversationType,from:e.from,to:e.to,reactions:this.normalizeReactionList(r.reactions),timestamp:this.normalizeTimestamp(r.ts)})}}handleConversationNotify(e){if(!Pm(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const r=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===r.clientResource&&"string"==typeof t.from&&t.from===r.userId)return;const s="string"==typeof t.ext?t.ext:"",n="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",o="string"==typeof t.id?t.id:"";s&&i&&o&&this.eventHub.dispatch(B,{messageId:s,conversationId:"chat"===n?i:o,conversationType:"chat"===n?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:i,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!Pm(e.data)||"string"!=typeof e.eventName)return;const t=e.data;switch(e.eventName){case"onMultiDeviceContact":case"onMultiDeviceGroup":case"onMultiDeviceThread":case"onMultiDeviceConversation":case"onMultiDeviceMessageRemoved":return void this.eventHub.dispatch(e.eventName,t);default:return}}toMessageReceiptPayload(e){if(!Pm(e.data))return null;const t=e.data;if(!Array.isArray(t.messageIds)||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||"number"!=typeof t.timestamp)return null;const r=t.messageIds.filter(e=>"string"==typeof e&&e.length>0);if(0===r.length)return null;const s=r[0];if(!s)return null;const n=this.resolveMessageReceiptContext(s,t.conversationId,t.conversationType);if("groupChat"===n.conversationType){const e=new Set(r),s=Array.isArray(t.receiptDetails)?t.receiptDetails.flatMap(t=>{if(!Pm(t))return[];const r=t.messageId,s=t.count;return"string"==typeof r&&e.has(r)&&"number"==typeof s&&Number.isInteger(s)&&s>=0?[{messageId:r,count:s}]:[]}):[];return{messageIds:r,conversationId:n.conversationId,conversationType:"groupChat",timestamp:t.timestamp,receiptDetails:s}}return{messageIds:r,conversationId:n.conversationId,conversationType:"singleChat",timestamp:t.timestamp}}handleMessageDeliveredNotify(e){if(!Pm(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(L,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!Pm(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(P,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}handleMessageUpdatedNotify(e){if(!Pm(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Pm(t.message)||"string"!=typeof t.message.type||!Pm(t.message.body)||!Pm(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Pm(t.message.modifiedInfo)?{modifiedInfo:{operatorId:"string"==typeof t.message.modifiedInfo.operatorId?t.message.modifiedInfo.operatorId:"",operationCount:"number"==typeof t.message.modifiedInfo.operationCount?t.message.modifiedInfo.operationCount:0,operationTime:"number"==typeof t.message.modifiedInfo.operationTime?t.message.modifiedInfo.operationTime:0}}:{}};this.eventHub.dispatch(D,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",message:r,timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}normalizeUpdatedMessageBody(e,t){if("text"!==e)return t;const r="string"==typeof t.content?t.content:"string"==typeof t.message?t.message:void 0;if(void 0===r)return t;const{message:s,...n}=t;return{...n,content:r}}handleChatThreadNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"onChatThreadChange"===r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(y,r)}normalizePresenceStatus(e){if(!e||"object"!=typeof e)return[];return Object.entries(e).map(([e,t])=>({device:e,status:Number(t)||0}))}destroy(){this.streamMessageHandler.destroy(),this.recentMessageIds.clear(),this.messageContexts.clear()}rememberMessageContext(e){const t=this.resolveMessageContextId(e),r=this.resolveMessageConversationContext(e);if(t&&r)for(this.messageContexts.delete(t),this.messageContexts.set(t,r);this.messageContexts.size>500;){const e=this.messageContexts.keys().next().value;if(!e)break;this.messageContexts.delete(e)}}resolveMessageReceiptContext(e,t,r){const s=this.messageContexts.get(e);return s||("groupChat"===r?{conversationId:t,conversationType:"groupChat"}:{conversationId:t,conversationType:"singleChat"})}resolveMessageContextId(e){return"string"==typeof e.msgServerId&&e.msgServerId.length>0?e.msgServerId:"string"==typeof e.msgLocalId&&e.msgLocalId.length>0?e.msgLocalId:""}resolveMessageConversationContext(e){if("string"!=typeof e.conversationId||!e.conversationId)return null;if("groupChat"===e.conversationType)return{conversationId:e.conversationId,conversationType:"groupChat"};if("chatRoom"===e.conversationType)return{conversationId:e.conversationId,conversationType:"chatRoom"};if("singleChat"!==e.conversationType)return null;const t=this.msyncCodec.getContext().userId,r="SEND"===e.direct||e.sender.userId===t?e.conversationId:e.sender.userId;return r?{conversationId:r,conversationType:"singleChat"}:null}resolveReactionConversationContext(e){const t="string"==typeof e.from?e.from:"",r="string"==typeof e.to?e.to:"",s="string"==typeof e.channel_type?e.channel_type:"";if(!t||!r)return null;if("groupChat"===s||"groupchat"===s||"group"===s)return{conversationId:r,conversationType:"groupChat",from:t,to:r};if(""!==s&&"chat"!==s&&"singleChat"!==s)return null;return{conversationId:t===this.msyncCodec.getContext().userId?r:t,conversationType:"singleChat",from:t,to:r}}normalizeReactionList(e){if(!Array.isArray(e))return[];const t=[];for(const r of e)Pm(r)&&"string"==typeof r.reaction&&t.push({reaction:r.reaction,count:"number"==typeof r.count&&Number.isFinite(r.count)?r.count:0,userList:Array.isArray(r.userList)?r.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof r.isAddedBySelf?r.isAddedBySelf:void 0,op:this.normalizeReactionOperations(r.op)});return t}normalizeReactionOperations(e){if(!Array.isArray(e))return;const t=[];for(const r of e)!Pm(r)||"string"!=typeof r.operator||"create"!==r.reactionType&&"delete"!==r.reactionType||t.push({operator:r.operator,reactionType:r.reactionType});return t.length>0?t:void 0}normalizeTimestamp(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){const t=Number(e);return Number.isFinite(t)?t:0}return 0}}const qm=e=>e instanceof Error?e.message:String(e);class Bm{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?qd({fetchImpl:fetch}):void 0))(e)}async downloadAndParse(e){const t=e.url.trim();if(!t)throw new Zr("Combine message url is required",{code:or,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof e.maxItems?e.maxItems:300;Am(1,r);const s=this.requestAdapter;if(!s)throw new Yr("Request adapter is required for combine message download",{code:ur});const n=ri(t,e.secret);try{const t=await s.request({url:n,method:"GET",responseType:"arraybuffer",timeoutMs:e.timeoutMs??15e3,headers:{[Ml]:Al()}});if(401===t.status||403===t.status)throw new Jr(401===t.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===t.status?dt:ut,details:{url:n,httpStatus:t.status}});if(t.status>=400)throw new Yr("Combine payload download failed",{code:ur,details:{status:t.status,url:n}});const i=(e=>{if(e.length<um.length+1)throw new Yr("Combine payload is too short",{code:lr});const t=e.subarray(0,um.length);if(t[0]!==um[0]||t[1]!==um[1])throw new Yr("Combine payload header is invalid",{code:lr});const r=e.subarray(0,e.length-1),s=ym(r),n=e[e.length-1]??0;if(n!==s)throw new Yr("Combine payload checksum failed",{code:lr,details:{expectedChecksum:s,actualChecksum:n}});const i=[];let o=um.length;const a=e.length-1;for(;o<a;){if(o+4>a)throw new Yr("Combine payload length header is incomplete",{code:lr});const t=gm(e,o);if(o+=4,t<=0||o+t>a)throw new Yr("Combine payload item length is invalid",{code:lr,details:{itemLength:t}});const r=e.subarray(o,o+t);o+=t;const s=Cm(r,i.length);i.push(s)}if(o!==a)throw new Yr("Combine payload has unexpected trailing bytes",{code:lr,details:{offset:o,expected:a}});return i})((e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if("string"==typeof e)return _i(e);throw new Yr("Combine payload response type is invalid",{code:ur})})(t.data));return Am(i.length,r),Mm(i),i.map(e=>({msgServerId:e.msgServerId??"",msgLocalId:e.msgLocalId??"",from:e.sender.userId,to:e.conversationId,sender:e.sender,conversationId:e.conversationId,conversationType:e.conversationType,type:e.type,sendStatus:"sent",ext:e.ext??{},timestamp:e.timestamp,body:e.body,direct:"RECEIVE"}))}catch(i){if(i instanceof Zr||i instanceof Jr||i instanceof Yr)throw i;throw new Yr("Combine payload download or parse failed",{code:ur,details:{cause:qm(i),url:n}})}}}const $m=e=>{switch(e.type){case"image":return e.body.filename??"image";case"video":return e.body.filename??"video";case"voice":return e.body.filename??"voice";case"file":return e.body.filename??"file";default:return"attachment"}},Fm=e=>{switch(e.type){case"image":case"video":case"voice":case"file":return e.body.filetype??"application/octet-stream";default:return"application/octet-stream"}};class Gm{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?qd({fetchImpl:fetch}):void 0))(e)}async download(e,t=15e3){if("image"!==e.type&&"video"!==e.type&&"voice"!==e.type&&"file"!==e.type)throw new Zr("message does not contain downloadable attachment",{code:Ot,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:r,secret:s}=(e=>{switch(e.type){case"image":{const t=e.body;return{url:t.originalImageUrl??t.bigImageUrl??t.thumbnailUrl??"",secret:t.secret}}case"video":case"voice":case"file":{const t=e.body;return{url:t.url??"",secret:t.secret}}default:return{url:""}}})(e);if(!r)throw new Zr("attachment url is required",{code:Ot,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});if(!this.requestAdapter)throw new Vr("request adapter is required for attachment download");const n=await this.requestAdapter.request({url:ri(r,s),method:"GET",responseType:"arraybuffer",timeoutMs:t,headers:{[Ml]:Al()}});if(401===n.status)throw new Jr("attachment download unauthorized",{code:dt,details:{url:r,httpStatus:n.status}});if(403===n.status)throw new Jr("attachment download forbidden",{code:ut,details:{url:r,httpStatus:n.status}});if(404===n.status){const e=("string"==typeof n.data?n.data:"").includes("expired");throw new Hr(e?"attachment file is expired":"attachment not found",e?xt:kt)}if(429===n.status)throw new Hr("attachment download rate limited",Fr);if(n.status>=400)throw new Hr("attachment download failed",er,{details:{status:n.status,url:r}});return{filename:$m(e),mimeType:Fm(e),size:(()=>{switch(e.type){case"image":case"video":case"voice":return e.body.fileLength;case"file":return e.body.fileLength??e.body.fileSize;default:return}})(),data:new Uint8Array(n.data),downloadUrl:r}}}const jm=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[Ml]:Al(),...r??{}}),zm=async e=>{const t=jm(e.token,"application/json",e.headers),r=Date.now(),s="upload.multipart.init"===e.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===e.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",n=e.dataReportOperation?.startRequest({requestName:s,method:e.method,url:e.url});let i=0;if(Ci("Upload request start",{operation:e.operation,method:e.method}),e.requestAdapter)try{const s=await e.requestAdapter.request({url:e.url,method:e.method,headers:t,responseType:"json",timeoutMs:xn});i=s.status;const a=Date.now()-r;if(s.status<200||s.status>=300)throw Si("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:a}),new rs("Upload request failed",{code:qr,details:{url:e.url,status:s.status}});Ci("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:a});const c="string"==typeof(o=s.data)?JSON.parse(o):o;return n?.finish({code:s.status,success:!0}),c}catch(d){if(n?.finish({code:0!==i?i:d instanceof rs?d.code:qr,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof rs)throw d;throw Si("Upload request failed",{operation:e.operation,method:e.method}),new rs("Upload request failed",{code:qr,details:{url:e.url}})}var o;const a=new AbortController,c=setTimeout(()=>a.abort(),xn);try{const s=await fetch(e.url,{method:e.method,headers:t,signal:a.signal});i=s.status;const o=Date.now()-r;if(!s.ok)throw Si("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:o}),new rs("Upload request failed",{code:qr,details:{url:e.url,status:s.status}});return Ci("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:o}),n?.finish({code:s.status,success:!0}),await s.json()}catch(d){if(n?.finish({code:0!==i?i:d instanceof rs?d.code:qr,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof rs)throw d;if(d instanceof Error&&"AbortError"===d.name)throw Si("Upload request timeout",{operation:e.operation,method:e.method,timeout:xn}),new rs("Upload timeout",{code:Br,details:{url:e.url,timeout:xn}});throw Si("Upload request failed",{operation:e.operation,method:e.method}),new rs("Upload request failed",{code:qr,details:{url:e.url}})}finally{clearTimeout(c)}},Km=(e,t,r,s,n,i)=>new Promise((o,a)=>{const c=new XMLHttpRequest,d=Date.now(),u=i?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:e});Ci("Upload part start",{operation:"upload.multipart.part",partNumber:r}),c.upload&&n&&c.upload.addEventListener("progress",e=>{n(e.loaded)},!1),c.addEventListener("abort",()=>{u?.finish({code:$r,success:!1,description:"Upload aborted"}),Si("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload aborted",{code:$r,details:{url:e,partNumber:r}}))},!1),c.addEventListener("error",()=>{u?.finish({code:qr,success:!1,description:"Upload part failed"}),Si("Upload part failed",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload part failed",{code:qr,details:{url:e,partNumber:r}}))},!1),c.addEventListener("timeout",()=>{u?.finish({code:Br,success:!1,description:"Upload timeout"}),Si("Upload part timeout",{operation:"upload.multipart.part",partNumber:r,timeout:xn}),a(new rs("Upload timeout",{code:Br,details:{url:e,partNumber:r}}))},!1),c.addEventListener("load",()=>{const t=Date.now()-d;if(200!==c.status)return u?.finish({code:c.status,success:!1,description:"Upload part failed"}),Si("Upload part error",{operation:"upload.multipart.part",partNumber:r,status:c.status,duration:t}),void a(new rs("Upload part failed",{code:qr,details:{url:e,partNumber:r,status:c.status}}));Ci("Upload part success",{operation:"upload.multipart.part",partNumber:r,duration:t}),u?.finish({code:c.status,success:!0}),o()},!1);const l=new FormData;l.append("part_file",s),l.append("part_number",r),c.timeout=xn,c.open("PUT",e),Object.entries(jm(t,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{c.setRequestHeader(e,t)}),c.send(l)}),Hm=async e=>{if(e.fileSize<=jn)throw new rs("Multipart not required",{code:qr,details:{reason:"file size below threshold"}});const{config:t,file:r,conversationId:s,conversationType:n,fileName:i,fileType:o,fileSize:a,messageType:c,imageType:d,md5:u,width:l,height:h}=e,{orgName:p,appName:m}=Qn(t.appKey),f=`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload`;let g;try{g=await zm({url:f,method:"POST",token:t.token,operation:"upload.multipart.init",requestAdapter:t.requestAdapter,dataReportOperation:e.dataReportOperation})}catch(M){throw new rs("Multipart init failed",{code:qr,details:{stage:"init",cause:M,url:f}})}const y=(e=>{const t=e.entities?.[0],r="number"==typeof t?.file_upper_limit?t.file_upper_limit:0,s="number"==typeof t?.part_lower_limit?t.part_lower_limit:zn,n="string"==typeof t?.uuid?t.uuid:"";if(!n)throw new rs("Multipart init failed",{code:qr,details:{response:e}});return{fileMaxSize:r,partMinSize:s,uuid:n}})(g);if(y.fileMaxSize&&a>y.fileMaxSize)throw new rs("File size exceeds limit",{code:Dr,details:{fileSize:a,maxSize:y.fileMaxSize}});const v=y.partMinSize||zn,b=Math.ceil(a/v),I=Array.from({length:b},()=>0),w=`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload/${y.uuid}`,C=[],S=(t,r)=>{I[t]=r;const s=I.reduce((e,t)=>e+t,0),n=a?s/a*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:s,total:a,percent:n})};for(let E=0;E<b;E+=1){const s=E*v,n=Math.min(a,s+v),i=r.slice(s,n),o=String(E+1),c=Km(w,t.token,o,i,e=>S(E,e),e.dataReportOperation).finally(()=>{const e=C.indexOf(c);e>=0&&C.splice(e,1)});C.push(c),C.length>=4&&await Promise.race(C)}await Promise.all(C);const T=Yn(n),_=ti(`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload/${y.uuid}`,{"restrict-access":"true","chat-type":T,"chat-target":s,"thumbnail-width":e.thumbnailWidth,"thumbnail-height":e.thumbnailHeight,md5:u??"",..."image"===c?{imageType:ii(d),width:l,height:h}:{}}),R=await zm({url:_,method:"POST",token:t.token,operation:"upload.multipart.complete",requestAdapter:t.requestAdapter,dataReportOperation:e.dataReportOperation}),A=ai({response:R,restBaseUrl:t.restBaseUrl,orgName:p,appName:m,fileType:o,fileName:i,fallbackSize:a,messageType:c,imageType:d,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(A),A},Vm=e=>new Promise((t,r)=>{const{config:s,file:n,conversationId:i,conversationType:o,messageType:a,imageType:c,md5:d,width:u,height:l,fileName:h,fileType:p,fileSize:m}=e,{orgName:f,appName:g}=Qn(s.appKey),y=Yn(o),v=ti(`${s.restBaseUrl}/${f}/${g}/chatfiles`,{"chat-type":y,"chat-target":i,md5:d??"",..."image"===a?{imageType:ii(c),width:u,height:l}:{}}),b=Date.now(),I=e.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:v});Ci("Upload request start",{operation:"upload.simple",method:"POST",fileSize:m,messageType:a});const w=new XMLHttpRequest;w.upload&&e.callbacks?.onFileUploadProgress&&w.upload.addEventListener("progress",t=>{if(!t.lengthComputable)return void e.callbacks?.onFileUploadProgress?.({loaded:t.loaded});const r=t.total?t.loaded/t.total*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:t.loaded,total:t.total,percent:r})},!1),w.addEventListener("abort",()=>{I?.finish({code:$r,success:!1,description:"Upload canceled"}),Si("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.(),r(new rs("Upload canceled",{code:$r,details:{url:v}}))},!1),w.addEventListener("error",()=>{I?.finish({code:qr,success:!1,description:"Upload failed"}),Si("Upload request failed",{operation:"upload.simple"}),r(new rs("Upload failed",{code:qr,details:{url:v}}))},!1),w.addEventListener("timeout",()=>{I?.finish({code:Br,success:!1,description:"Upload timeout"}),Si("Upload request timeout",{operation:"upload.simple",timeout:xn}),r(new rs("Upload timeout",{code:Br,details:{url:v,timeout:xn}}))},!1),w.addEventListener("load",()=>{try{const r=Date.now()-b,n=JSON.parse(w.responseText);if(w.status>=400)throw I?.finish({code:w.status,success:!1,description:"Upload failed"}),Si("Upload response error",{operation:"upload.simple",status:w.status,duration:r}),new rs("Upload failed",{code:qr,details:{status:w.status,response:n}});Ci("Upload response success",{operation:"upload.simple",status:w.status,duration:r});const i=ai({response:n,restBaseUrl:s.restBaseUrl,orgName:f,appName:g,fileType:p,fileName:h,fallbackSize:m,messageType:a,imageType:c,useCustomAttachmentUpload:s.useCustomAttachmentUpload});e.callbacks?.onFileUploadComplete?.(i),I?.finish({code:w.status||200,success:!0}),t(i)}catch(n){I?.finish({code:n instanceof rs?n.code:qr,success:!1,description:n instanceof Error?n.message:String(n)}),r(n instanceof Error?n:new Error(String(n)))}},!1),w.timeout=xn,w.open("POST",v),w.setRequestHeader("restrict-access","true"),w.setRequestHeader("Accept","*/*"),w.setRequestHeader("Authorization",`Bearer ${s.token}`),w.setRequestHeader(Ml,Al());const C=new FormData;C.append("file",n,h),void 0!==e.thumbnailWidth&&C.append("thumbnail-width",String(e.thumbnailWidth)),void 0!==e.thumbnailHeight&&C.append("thumbnail-height",String(e.thumbnailHeight)),w.send(C)}),Wm=hu(),Jm=e=>Object.prototype.toString.call(e),Zm=e=>{const t=e&&"object"==typeof e?e:null,r="string"==typeof t?.path?t.path:void 0,s="string"==typeof t?.uri?t.uri:void 0,n="string"==typeof t?.name?t.name:void 0,i="string"==typeof t?.type?t.type:void 0,o="number"==typeof t?.size?t.size:void 0;return{kind:Jm(e),isFile:"undefined"!=typeof File&&e instanceof File,isBlob:"undefined"!=typeof Blob&&e instanceof Blob,hasPath:"string"==typeof r&&r.length>0,pathPrefix:r?r.slice(0,48):void 0,hasUri:"string"==typeof s&&s.length>0,uriPrefix:s?s.slice(0,48):void 0,name:n,type:i,size:o}},Qm=e=>({sourceType:e.source.sourceType,fileName:e.fileName,fileType:e.fileType,fileSize:e.fileSize,hasWebFile:Boolean(e.webFile),sourceName:e.source.name,sourceMimeType:e.source.mimeType,sourceSize:e.source.size}),Ym=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Xm=e=>"object"==typeof e&&null!==e,ef=(e,t)=>{const r=Xm(t)?t:void 0,s=r?.code===Pi&&r.stage===xi;return"miniapp-path"===e&&(e=>{if(!Xm(e))return!1;const t=Xm(e.details)?e.details:void 0;return e.code===Pi&&e.stage===xi&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&s};class tf{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(e,t){if(!Ym(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=am.get(e.msgLocalId),i=Boolean(n);if(Si("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:e.msgLocalId,messageType:e.type,conversationType:e.conversationType,hasFile:i,uploadUrl:s,cachedFile:Zm(n),adapter:{hasRequestAdapter:Boolean(this.config?.requestAdapter),hasUploadAdapter:Boolean(this.config?.uploadAdapter),hasImageProcessor:Boolean(this.config?.imageProcessor),restBaseUrl:Boolean(this.config?.restBaseUrl),useCustomAttachmentUpload:this.config?.useCustomAttachmentUpload}}),!((e,t)=>!!t||!e||!Zn(e))(s,i))return e;if(!n)throw new rs("Attachment file is required",{code:Lr,details:{msgLocalId:e.msgLocalId,url:s}});if(!this.config?.restBaseUrl)throw new rs("REST base url is required for upload",{code:Lr,details:{reason:"restBaseUrl missing"}});let o,a,c;try{o=await this.prepareAttachmentUpload(e,r,n),o.precheck?.hit||(c=nm({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:e.msgLocalId,messageType:e.type})),a=o.precheck?.hit?this.buildPrecheckedUploadResult(e,o,t):await this.uploadAttachment(e,o,t,c),c?.finish({code:0,success:!0})}catch(d){const e=ll(d);throw c?.finish({code:e.code,success:!1,description:e.message}),e.code===$r&&t?.onFileUploadCanceled?.(),t?.onFileUploadError?.(e),e}return this.buildPreparedMessage(e,o,a)}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&Zn(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&Zn(t.url)}async prepareAttachmentUpload(e,t,r){const s=((e,t)=>{if(!e)throw new rs("Attachment file is required",{code:Lr,details:{reason:"file missing"}});const r=("number"==typeof t.fileLength?t.fileLength:void 0)??("fileSize"in t&&"number"==typeof t.fileSize?t.fileSize:void 0),s=Gn({file:e,fallbackName:t.filename,fallbackMimeType:t.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new rs("Attachment file is required",{code:Lr,details:{reason:"web file missing"}});return s})(r,t);if(Si("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Qm(s)}),"image"!==e.type){return{body:t,fileInfo:s,md5FileInfo:s,precheck:await this.maybePrecheck(e,s,s,void 0)}}const n=t,i=await this.resolveImageCandidate(n,s),o={...n,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===Wn},a=await this.maybePrecheck(e,i.fileInfo,s,i.imagePolicy.resolvedImageType);return{body:o,fileInfo:i.fileInfo,md5FileInfo:s,imageType:i.imagePolicy.resolvedImageType,precheck:a,originalWidth:n.width,originalHeight:n.height}}async resolveImageCandidate(e,t){const r=(e=>e.isGif?{resolvedImageType:Wn,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:Wn,reason:"explicit-original"}:{resolvedImageType:Jn,reason:"default-large"})(e);if(Si("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:e.isGif,source:Qm(t)}),r.resolvedImageType===Wn){let s=e.width,n=e.height;if(!s||!n){const e=this.resolveImageProcessor(t.source.sourceType);Si("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Qm(t)});const r=await e.getImageInfo(t.source);s=r.width,n=r.height}return{imagePolicy:r,sourceKind:"origin",fileInfo:t,width:s,height:n}}try{const e=this.resolveImageProcessor(t.source.sourceType);Si("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Qm(t)});const s=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:r,sourceKind:"big",fileInfo:{source:s.source,fileName:s.fileName??t.fileName,fileType:s.fileType??t.fileType,fileSize:s.fileSize??t.fileSize,webFile:s.webFile},width:s.width,height:s.height}}catch(s){return Si("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:s instanceof Error?s.message:String(s),source:Qm(t)}),{imagePolicy:{resolvedImageType:Wn,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,r,s){if(!Ym(e.type))return;if(!0!==this.config?.enableMd5Check)return void Ci("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:s,fileSize:t.fileSize});const n=si({messageType:e.type,fileSize:t.fileSize,imageType:s});if(!n.shouldPrecheck)return void Ci("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:s,fileSize:t.fileSize,thresholdBytes:n.thresholdBytes});let i;try{i=await this.computeMd5(r)}catch(a){if(ef(r.source.sourceType,a))return void Si("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:s,thresholdType:n.thresholdType,source:Qm(r),error:a instanceof Error?a.message:String(a)});throw a}const o=await this.requestPrecheck(e,n.thresholdType,i,s);return Ci(o.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:o.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:s,exists:o.exists,existsType:o.existsType,uuid:o.uuid,hasShareSecret:"string"==typeof o.shareSecret&&o.shareSecret.length>0}),{...o,md5:i}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return Si("Attachment md5 compute start",{operation:"upload.md5.start",source:Qm(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return Si("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return Si("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),Wm;throw Si("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),Fi("Image processor capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(e,t,r,s){if(!this.config)throw new rs("Upload config is required",{code:Lr});const{orgName:n,appName:i}=Qn(this.config.appKey),o=ti(`${this.config.restBaseUrl}/${n}/${i}/chatfiles/exists`,{md5:r,..."image"===e.type?{imageType:ii(s)}:{}}),a=await this.requestJson({url:o,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(n=>{Si("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:e.type,imageType:s,thresholdType:t,md5:r,error:n instanceof Error?n.message:String(n)})});return a?(e=>{const t=e.entities?.[0],r=!0===t?.exists,s="string"==typeof t?.uuid&&t.uuid.length>0?t.uuid:void 0,n=t,i=n?.["exists-type"]??n?.existsType,o="origin"===i?Wn:i===Jn||i===Wn?i:void 0,a="string"==typeof t?.["share-secret"]?t["share-secret"]:void 0;if(r&&!s)throw new rs("Upload precheck response missing uuid",{code:qr,details:{response:e}});return{uuid:s,exists:r,existsType:o,shareSecret:a,hit:(c={exists:r,uuid:s},c.exists&&"string"==typeof c.uuid&&c.uuid.length>0)};var c})(a):{exists:!1,hit:!1}}async requestJson(e){return this.config?.requestAdapter?this.requestByAdapter(this.config.requestAdapter,e):this.requestByFetch(e)}async requestByAdapter(e,t){const r=await e.request({url:t.url,method:t.method,headers:t.headers,responseType:"json",timeoutMs:xn});if(r.status>=400)throw new rs("Upload precheck request failed",{code:qr,details:{url:t.url,status:r.status,operation:t.operation}});return r.data}async requestByFetch(e){if("function"!=typeof fetch)throw Fi("Request capability is missing for current platform",{code:Pi,stage:Ui,retryable:!1,details:{operation:e.operation}});const t=new AbortController,r=setTimeout(()=>t.abort(),xn);try{const r=await fetch(e.url,{method:e.method,headers:e.headers,signal:t.signal});if(!r.ok)throw new rs("Upload precheck request failed",{code:qr,details:{url:e.url,status:r.status,operation:e.operation}});return await r.json()}finally{clearTimeout(r)}}buildPrecheckedUploadResult(e,t,r){if(!this.config||!t.precheck)throw new rs("Precheck result is required",{code:qr});if(!t.precheck.uuid)throw new rs("Precheck hit missing uuid",{code:qr,details:{precheck:t.precheck}});if(!Ym(e.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:e.type}});const{orgName:s,appName:n}=Qn(this.config.appKey),i="image"===e.type?t.precheck.existsType??t.imageType:void 0,o="image"===e.type&&i===Wn?t.md5FileInfo:t.fileInfo,a="image"===e.type&&i===Wn?t.originalWidth:"image"===e.type?t.body.width:void 0,c="image"===e.type&&i===Wn?t.originalHeight:"image"===e.type?t.body.height:void 0,d={entities:[{uuid:t.precheck.uuid,...t.precheck.shareSecret?{"share-secret":t.precheck.shareSecret}:{}}]},u=ai({response:d,restBaseUrl:this.config.restBaseUrl,orgName:s,appName:n,fileType:o.fileType,fileName:o.fileName,fallbackSize:o.fileSize,messageType:e.type,imageType:i,width:a,height:c,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return r?.onFileUploadComplete?.(u),u}async uploadAttachment(e,t,r,s){if(!this.config)throw new rs("Upload config is required",{code:Lr});if(!Ym(e.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:e.type}});const n=e.type,i=await this.resolveUploadMetadata(n,t);if(this.config.uploadAdapter)return Si("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:n,source:Qm(t.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r);if(!t.fileInfo.webFile)throw new rs("Upload adapter is required for non-web file source",{code:Lr,details:{sourceType:t.fileInfo.source.sourceType}});const o={message:e,file:t.fileInfo.webFile,conversationId:e.conversationId,conversationType:e.conversationType,messageType:n,imageType:t.imageType,md5:i.md5,width:i.width,height:i.height,fileName:t.fileInfo.fileName,fileType:t.fileInfo.fileType,fileSize:t.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(n,t.body),thumbnailHeight:this.resolveThumbnailHeight(n,t.body),callbacks:r,config:this.config,dataReportOperation:s},a=!1!==this.config?.enableMultipartUpload,c=a&&t.fileInfo.fileSize>jn;if(Si("Attachment web upload selected",{operation:"upload.web.selected",messageType:n,source:Qm(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Hm(o)}catch(d){const e=d instanceof rs?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return Vm(o);throw d}return Vm(o)}async uploadByAdapter(e,t,r,s,n){if(!this.config)throw new rs("Upload config is required",{code:Lr});const{orgName:i,appName:o}=Qn(this.config.appKey),a=Yn(t.conversationType);if(!Ym(t.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:t.type}});const c=t.type,d=ti(`${this.config.restBaseUrl}/${i}/${o}/chatfiles`,{"chat-type":a,"chat-target":t.conversationId,md5:s.md5,..."image"===c?{imageType:ii(r.imageType),width:s.width,height:s.height}:{}}),u={},l={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[Ml]:Al()},h=this.resolveThumbnailWidth(c,r.body),p=this.resolveThumbnailHeight(c,r.body);void 0!==h&&(u["thumbnail-width"]=String(h)),void 0!==p&&(u["thumbnail-height"]=String(p)),Si("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:c,source:Qm(r.fileInfo),uploadUrl:d,fields:u});const m=await e.upload({url:d,headers:l,source:r.fileInfo.source,fields:u,onProgress:e=>{n?.onFileUploadProgress?.(e)}});if(m.status>=400){const e=m.body??"",t=413===m.status?tr:"string"==typeof e&&e.includes("content improper")?rr:qr;throw new rs("Upload failed",{code:t,details:{status:m.status,response:m.body}})}let f;try{f=JSON.parse(m.body)}catch(y){throw new rs("Upload response parse failed",{code:qr,details:{response:m.body,cause:y instanceof Error?y.message:String(y)}})}const g=ai({response:f,restBaseUrl:this.config.restBaseUrl,orgName:i,appName:o,fileType:r.fileInfo.fileType,fileName:r.fileInfo.fileName,fallbackSize:r.fileInfo.fileSize,messageType:c,imageType:r.imageType,width:s.width,height:s.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(g),g}buildPreparedMessage(e,t,r){if("image"===e.type){const s=t.body,n={...e,body:{...s,isOriginalImage:r.isOriginalImage??s.isOriginalImage,originalImageUrl:r.originalImageUrl??s.originalImageUrl,bigImageUrl:r.bigImageUrl??s.bigImageUrl,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl,width:r.width??s.width,height:r.height??s.height}};return wh(e,n),Rh(e,n),n}if("video"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl}};return wh(e,n),n}if("voice"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return wh(e,n),n}if("combine"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return wh(e,n),n}const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return wh(e,n),n}resolveThumbnailWidth(e,t){if("video"===e){const e="width"in t?t.width:void 0;return"number"==typeof e&&e>0?e:void 0}}resolveThumbnailHeight(e,t){if("video"===e){const e="height"in t?t.height:void 0;return"number"==typeof e&&e>0?e:void 0}}async resolveUploadMetadata(e,t){let r=t.precheck?.md5??"";if(!t.precheck)try{r=await this.computeMd5(t.md5FileInfo)}catch(n){if(!ef(t.md5FileInfo.source.sourceType,n))throw n;Si("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Qm(t.md5FileInfo),error:n instanceof Error?n.message:String(n)})}const s=t.body;return{md5:r,width:"image"===e&&"number"==typeof s.width&&s.width>0?s.width:void 0,height:"image"===e&&"number"==typeof s.height&&s.height>0?s.height:void 0}}}class rf{constructor(e,t){this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null,this.runtime=e,this.handlers=t}start(){this.unsubscribeNetwork||this.unsubscribeVisibility||(this.unsubscribeNetwork=this.runtime.onNetworkChange(e=>{this.handleNetworkChange(e)}),this.unsubscribeVisibility=this.runtime.onAppVisibilityChange(e=>{this.handleVisibilityChange(e)}))}stop(){this.unsubscribeNetwork?.(),this.unsubscribeVisibility?.(),this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null}handleNetworkChange(e){this.lastOnline!==e&&(this.lastOnline=e,e?this.handlers.onOnline():this.handlers.onOffline())}handleVisibilityChange(e){this.lastForeground!==e&&(this.lastForeground=e,e?this.handlers.onForeground():this.handlers.onBackground())}}const sf="__internal:core";class nf{constructor(e,t){this.runtimeEventBridge=null,this.handleOnline=()=>{this.connectionManager.handleOnline()},this.handleOffline=()=>{this.connectionManager.handleOffline()},this.handleForegroundChange=e=>{e&&this.connectionManager.handleForeground()},this.eventHub=t,this.connectionManager=new om({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new tf({restBaseUrl:e.restBaseUrl,token:e.token,appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,enableMultipartUpload:e.enableMultipartUpload,requestAdapter:e.platformAdapter?.request,uploadAdapter:e.platformAdapter?.upload,imageProcessor:e.platformAdapter?.imageProcessor}):void 0;this.messageSender=new km(r,null,this.eventHub,s),this.messageReceiver=new Dm(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Bm(e.platformAdapter?.request),this.attachmentDownloader=new Gm(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(sf,{[a]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[c]:e=>{this.messageSender.setWebSocket(null)},[d]:e=>{this.messageSender.setWebSocket(null)},[b]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new rf(e,{onOnline:this.handleOnline,onOffline:this.handleOffline,onForeground:()=>{this.handleForegroundChange(!0)},onBackground:()=>{this.handleForegroundChange(!1)}}),this.runtimeEventBridge.start()}unregisterNetworkListeners(){this.runtimeEventBridge?.stop(),this.runtimeEventBridge=null}resolveRuntimeAdapter(){return this.platformAdapter?this.platformAdapter.runtime:this.createBrowserRuntimeAdapter()}createBrowserRuntimeAdapter(){return{getPlatform:()=>"web",onNetworkChange(e){if("undefined"==typeof window)return()=>{};const t=()=>{e(!0)},r=()=>{e(!1)};return window.addEventListener("online",t),window.addEventListener("offline",r),"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine&&e(navigator.onLine),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}},onAppVisibilityChange(e){if("undefined"==typeof document)return()=>{};const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),t(),()=>{document.removeEventListener("visibilitychange",t)}}}}async connect(){return this.connectionManager.connect()}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}getClientResource(){return this.connectionManager.getClientResource()}renewToken(e,t){const r=this.connectionManager.renewToken(e,t);return this.messageSender.updateAuthToken(e),r}async sendMessage(e,t){return this.messageSender.sendMessage(e,t)}async sendMessageAction(e,t){return this.messageSender.sendAction(e,t)}async sendChatRoomOperation(e,t){return this.messageSender.sendChatRoomOperation(e,t)}async downloadAndParseCombineMessage(e){return this.combineMessageDownloader.downloadAndParse(e)}async downloadAttachment(e,t){return this.attachmentDownloader.download(e,t)}decodeServerMessageMeta(e){return this.connectionManager.getMsyncCodec().decodeServerMessageMeta(e)}destroy(){this.unregisterNetworkListeners(),this.connectionManager.destroy(),this.messageSender.destroy(),this.messageReceiver.destroy(),this.eventHub.removeEventHandler(sf),am.clear()}}const of=e=>{if(e.length>=1048576){const t=[],r=32768;for(let s=0;s<e.length;s+=r)t.push(String.fromCharCode(...e.subarray(s,s+r)));return btoa(t.join(""))}let t="";for(let r=0;r<e.length;r+=1){const s=e[r];void 0!==s&&(t+=String.fromCharCode(s))}return btoa(t)},af=e=>{const t=new Uint8Array(Vc.util.base64.length(e));return Vc.util.base64.decode(e,t,0),t};class cf{getCrypto(){return Vi().crypto}constructor(e,t){if(this.enabled=(()=>{const e=Vi();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const t=co(e);if("web"!==t.framework&&"worker"!==t.framework&&t.platform!==Mi.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const r=`${e}:${t}`;this.keyPromise=this.deriveKey(r)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,r=new TextEncoder,s=this.getCrypto().getRandomValues(new Uint8Array(12)),n=r.encode(e),i=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:s},t,n),o={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:of(s),ct:of(new Uint8Array(i))};return JSON.stringify(o)}async decrypt(e){if(!this.enabled||!this.keyPromise)return e;let t;try{t=JSON.parse(e)}catch{return e}if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return!0===t.__enc&&1===t.v&&"AES-GCM"===t.alg&&"SHA-256"===t.kdf&&"string"==typeof t.iv&&"string"==typeof t.ct})(t))return e;try{const e=await this.keyPromise,r=af(t.iv),s=af(t.ct),n=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:r},e,s);return(new TextDecoder).decode(n)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),r=this.getCrypto(),s=await r.subtle.digest("SHA-256",t);return r.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const df="conversationMap",uf="userInfoMap",lf="groupNamecardMap",hf="contactRelationMap",pf="contactVersion",mf="contactMeta",ff="sessionListMap",gf="sessionListCheckpoint",yf="joinedGroupPreview",vf="metadata",bf=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class If{constructor(e,t,r){this.store=e,this.key=t,this.schemaVersion=r}async load(){const e={schemaVersion:this.schemaVersion,lastFlush:0},t=await this.store.readAsync(this.key,e);return t.schemaVersion!==this.schemaVersion?e:t}async save(e){await this.store.writeAsync(this.key,e)}async touchLastFlush(){const e={schemaVersion:this.schemaVersion,lastFlush:Date.now()};return await this.save(e),e}}const wf=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=Vi().localStorage;return t&&"function"==typeof t.getItem?t:null};class Cf{constructor(e,t){this.storage=t??Cf.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!Cf.checkAvailable())return null;const e=wf();return e?{getItem:t=>Promise.resolve(e.getItem(t)),setItem:(t,r)=>(e.setItem(t,r),Promise.resolve()),removeItem:t=>(e.removeItem(t),Promise.resolve())}:null}static checkAvailable(){const e=wf();if(!e)return!1;try{const t="__im_sdk_cache_test__";return e.setItem(t,"1"),e.removeItem(t),!0}catch{return!1}}async readAsync(e,t){if(!this.storage)return t;try{const r=await this.storage.getItem(e);if(!r)return t;let s=r;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(r);if(null===e)return t;s=e}return $l(s,t)}catch(r){return Si("CacheStore read failed",r),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,r){if(!this.storage)return;const s=(e=>{try{return JSON.stringify(e)}catch{return null}})(t);if(null!==s)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(s):s;await this.storage.setItem(e,t)}catch(n){if(Tu(n))throw n;if(r)throw n;Si("CacheStore write failed",n)}else if(r)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){Si("CacheStore remove failed",t)}}}const Sf={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Tf={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class _f{constructor(){this.items=new Map,this.versionState=Sf,this.meta=Tf}load(e,t,r){this.items.clear();for(const s of e){const e=this.normalizeRecord(s);e&&this.items.set(e.userId,e)}this.versionState=this.normalizeVersionState(t),this.meta=this.normalizeMeta(r)}getAll(){return Array.from(this.items.values()).sort((e,t)=>e.addTs!==t.addTs?e.addTs-t.addTs:e.userId.localeCompare(t.userId))}getVersionState(){return this.versionState}getMeta(){return this.meta}getUserIds(){return Array.from(this.items.keys())}replaceAll(e){this.items.clear(),this.upsert(e)}upsert(e){for(const t of e){const e=this.normalizeRecord(t);e&&this.items.set(e.userId,e)}}addByNotice(e,t){const r=e.trim();return!!r&&(!this.items.has(r)&&(this.items.set(r,{userId:r,remark:"",sign:"",addTs:t,updatedAt:t,metadataUpdatedAt:t}),!0))}remove(e){return this.items.delete(e)}updateRemark(e,t,r){const s=this.items.get(e);return!(!s||s.remark===t)&&(this.items.set(e,{...s,remark:t,updatedAt:r}),!0)}setVersionState(e){this.versionState=this.normalizeVersionState(e)}updateVersionFromNotice(e,t){const r=e.trim();return!!r&&((this.versionState.version!==r||"roster_notice"!==this.versionState.lastVersionSource)&&(this.versionState={version:r,lastVersionCheckAt:t,lastVersionSource:"roster_notice"},!0))}setMeta(e){this.meta=this.normalizeMeta(e)}updateMeta(e){this.meta={cacheIntegrity:e.cacheIntegrity,reason:"complete"===e.cacheIntegrity?void 0:e.reason,lastSyncTs:e.lastSyncTs??this.meta.lastSyncTs,lastSuccessfulVersion:e.lastSuccessfulVersion??this.meta.lastSuccessfulVersion,lastSyncMode:e.lastSyncMode??this.meta.lastSyncMode}}computeIntegrity(e){if(0===this.items.size&&!this.meta.lastSuccessfulVersion)return{...this.meta,cacheIntegrity:"incomplete",reason:"first_sync_pending"};const t=new Set(e.map(e=>e.userId));return this.getUserIds().some(e=>!t.has(e))?{...this.meta,cacheIntegrity:"incomplete",reason:"user_info_missing"}:{...this.meta,cacheIntegrity:"complete",reason:void 0}}buildSnapshot(e,t){const r=new Map(e.map(e=>[e.userId,e])),s=this.getAll().map(e=>{const t=r.get(e.userId);return{userId:e.userId,userInfo:{userId:e.userId,nickname:t?.nickname,avatarUrl:t?.avatarUrl,sign:t?.sign??e.sign,ext:t?.ext},remark:e.remark,addTs:e.addTs}}),n="complete"===this.computeIntegrity(e).cacheIntegrity;return{items:s,source:t,version:this.versionState.version||this.meta.lastSuccessfulVersion,complete:n}}normalizeRecord(e){if(!Bl(e))return null;const t="string"==typeof e.userId?e.userId:"";return t?{userId:t,remark:"string"==typeof e.remark?e.remark:"",sign:"string"==typeof e.sign?e.sign:"",addTs:"number"==typeof e.addTs?e.addTs:0,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:0,metadataUpdatedAt:"number"==typeof e.metadataUpdatedAt?e.metadataUpdatedAt:0}:null}normalizeVersionState(e){return Bl(e)?{version:"string"==typeof e.version?e.version:"",lastVersionCheckAt:"number"==typeof e.lastVersionCheckAt?e.lastVersionCheckAt:0,lastVersionSource:"metadata"===e.lastVersionSource||"sync_page"===e.lastVersionSource||"roster_notice"===e.lastVersionSource?e.lastVersionSource:"metadata"}:Sf}normalizeMeta(e){return Bl(e)?{cacheIntegrity:"complete"===e.cacheIntegrity?"complete":"incomplete",reason:"quota_exceeded"===e.reason||"user_info_missing"===e.reason||"corrupted"===e.reason||"manual_reset"===e.reason||"first_sync_pending"===e.reason?e.reason:void 0,lastSyncTs:"number"==typeof e.lastSyncTs?e.lastSyncTs:0,lastSuccessfulVersion:"string"==typeof e.lastSuccessfulVersion?e.lastSuccessfulVersion:"",lastSyncMode:"full"===e.lastSyncMode||"incremental"===e.lastSyncMode||"skipped"===e.lastSyncMode?e.lastSyncMode:"skipped"}:Tf}}const Rf=(e,t,r)=>{if(t<=0)return{kept:e,removed:[]};const s=[],n=[];for(const i of e)r-i.lastUpdate>t?n.push(i):s.push(i);return{kept:s,removed:n}},Af=(e,t)=>{if(t<=0||0===e.length)return{kept:e,removed:[]};const r=[...e].sort((e,t)=>e.lastAccess-t.lastAccess).slice(0,t),s=new Set(r);return{kept:e.filter(e=>!s.has(e)),removed:r}},Mf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r};class Ef{constructor(){this.items=[]}load(e,t){const r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r}getAll(){return this.items}setAll(e){this.items=[...e]}updateLastAccess(e,t){if(0===e.length)return!1;let r=!1;for(const s of e){const e=this.findIndex(s.conversationId,s.type);if(e<0)continue;const n=this.items[e];n&&(n.lastAccess!==t&&(this.items[e]={...n,lastAccess:t},r=!0))}return r}removeExpired(e,t){const r=Rf(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=Af(this.items,e);return this.items=[...t.kept],t.removed.length>0}trimMax(e){if(!e||this.items.length<=e)return!1;const t=[...this.items].sort((e,t)=>e.lastAccess-t.lastAccess),r=Math.max(this.items.length-e,0),s=t.slice(0,r),n=new Set(s);return this.items=this.items.filter(e=>!n.has(e)),s.length>0}findIndex(e,t){return this.items.findIndex(r=>r.conversationId===e&&r.type===t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;const r=e;if("string"!=typeof r.conversationId||0===r.conversationId.length)return null;const s="single"===(n=r.type)||"chat"===n||"singleChat"===n?"singleChat":"group"===n||"groupchat"===n||"groupChat"===n?"groupChat":"room"===n||"chatroom"===n||"chatRoom"===n?"chatRoom":null;var n;if(!s)return null;const i=this.normalizeMessage(r.lastMessage);return{conversationId:r.conversationId,type:s,lastMessage:i,unreadCount:"number"==typeof r.unreadCount?r.unreadCount:0,isPinned:"boolean"==typeof r.isPinned?r.isPinned:void 0,pinnedTime:"number"==typeof r.pinnedTime?r.pinnedTime:void 0,marks:Mf(r.marks),lastAccess:"number"==typeof r.lastAccess?r.lastAccess:0,lastUpdate:"number"==typeof r.lastUpdate?r.lastUpdate:t}}normalizeMessage(e){if(!e||"object"!=typeof e)return null;if(!Bl(e))return null;const t="string"==typeof e.msgId?e.msgId:"",r="string"==typeof e.type?e.type:"",s="number"==typeof e.timestamp?e.timestamp:0,n=Bl(e.body)?e.body:{},i="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,o="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:r,body:n,timestamp:s,userInfoUpdateTime:i,namecardUpdateTime:o}:null}}const Uf=(e,t)=>`${e}:${t}`;class Nf{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(Uf(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=Uf(e,t),i=this.items.get(n);return i?(s&&this.items.set(n,{...i,lastAccess:r}),i):null}getByGroupId(e,t,r){const s=[];for(const n of this.items.values())n.groupId===e&&(s.push(n),r&&this.items.set(Uf(n.groupId,n.userId),{...n,lastAccess:t}));return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=Uf(e.groupId,e.userId),n=this.items.get(s);this.items.set(s,{...e,lastAccess:n?.lastAccess??e.lastAccess,lastUpdate:t})}}remove(e){for(const t of e)this.items.delete(Uf(t.groupId,t.userId))}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=Rf(n,e,t),o=new Set(i.removed.map(e=>Uf(e.groupId,e.userId)));this.items.clear();for(const a of s)o.has(Uf(a.groupId,a.userId))||this.items.set(Uf(a.groupId,a.userId),a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=Af(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>Uf(e.groupId,e.userId)));this.items.clear();for(const o of r)i.has(Uf(o.groupId,o.userId))||this.items.set(Uf(o.groupId,o.userId),o);return n.removed.length>0}trimMax(e,t=new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!Bl(e))return null;const r="string"==typeof e.groupId?e.groupId:"",s="string"==typeof e.userId?e.userId:"";if(!r||!s)return null;return{groupId:r,userId:s,namecard:"string"==typeof e.namecard?e.namecard:"",namecardUpdateTime:"number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const kf=100,Of=3e3,xf=e=>({...e}),Lf=e=>"object"==typeof e&&null!==e,Pf=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 Df{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:kf,serverLimit:Of,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:kf,serverLimit:Of,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return Lf(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:Pf(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,kf),this.meta=(e=>{const t=Lf(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:kf,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:Of,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=>xf(e)).slice(0,kf),this.meta={...e.meta,source:"localPreview",storageLimit:kf,serverLimit:Of,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>xf(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>xf(e)),meta:{...this.meta,source:"localPreview"}}}}const qf=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Bf=e=>{const t={...e};return delete t.type,t},$f=e=>{if(!Bl(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!Bl(e.body))return null;const r=((e,t)=>{if(Bl(e)&&"string"==typeof e.userId){const t={userId:e.userId};return"string"==typeof e.nickname&&(t.nickname=e.nickname),"string"==typeof e.avatarUrl&&(t.avatarUrl=e.avatarUrl),t}return t?{userId:t}:null})(e.sender,e.from);if(!r)return null;const s=qf(e.conversationType),n=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),i=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),o=(e=>{if(Bl(e)&&"string"==typeof e.operatorId&&"number"==typeof e.operationCount&&"number"==typeof e.operationTime)return{operatorId:e.operatorId,operationCount:e.operationCount,operationTime:e.operationTime}})(e.modifiedInfo),a="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,c="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return{msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:r,body:Bf(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...s?{conversationType:s}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...n?{sendStatus:n}:{},...i?{direct:i}:{},...o?{modifiedInfo:o}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},Ff=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},Gf=(e,t)=>{const r="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,s="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(r!==s)return s-r;const n=e.lastMessageAt??e.updatedAt,i=t.lastMessageAt??t.updatedAt;return n!==i?i-n:e.conversationId.localeCompare(t.conversationId)};class jf{constructor(){this.items=[]}load(e,t){const r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r.sort(Gf)}getAll(){return this.items}setAll(e){const t=Date.now(),r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r.sort(Gf)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!Bl(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=qf(r.conversationType);if(!n)return null;const i="string"==typeof r.conversationName&&r.conversationName.length>0?r.conversationName:s,o="string"==typeof r.conversationAvatar?r.conversationAvatar:void 0;return{conversationId:s,conversationType:n,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:$f(e.lastMessage),lastMessageAt:"number"==typeof e.lastMessageAt?e.lastMessageAt:void 0,isPinned:"boolean"==typeof e.isPinned?e.isPinned:void 0,pinnedTimestamp:"number"==typeof r.pinnedTimestamp?r.pinnedTimestamp:void 0,marks:Ff(e.marks),readAt:"number"==typeof r.readAt?r.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:i,conversationAvatar:o,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class zf{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,r){const s=[];for(const n of e){const e=this.items.get(n);e&&(s.push(e),r&&this.items.set(n,{...e,lastAccess:t}))}return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=this.items.get(e.userId),n=s?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:n,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=Rf(n,e,t),o=new Set(i.removed.map(e=>e.userId));this.items.clear();for(const a of s)o.has(a.userId)||this.items.set(a.userId,a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=Af(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>e.userId));this.items.clear();for(const o of r)i.has(o.userId)||this.items.set(o.userId,o);return n.removed.length>0}trimMax(e,t=new Set){if(e<=0||this.items.size<=e)return!1;const r=Array.from(this.items.values()),s=Math.max(r.length-e,0);return this.evictByLru(s,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!Bl(e))return null;const r="string"==typeof e.userId?e.userId:"";if(!r)return null;return{userId:r,nickname:"string"==typeof e.nickname?e.nickname:void 0,avatarUrl:"string"==typeof e.avatarUrl?e.avatarUrl:void 0,sign:"string"==typeof e.sign?e.sign:void 0,ext:"string"==typeof e.ext?e.ext:void 0,userInfoUpdateTime:"number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const Kf=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Hf=e=>e.lastMessageAt??e.updatedAt,Vf=e=>[...e].sort((e,t)=>{const r=Kf(t)-Kf(e);if(0!==r)return r;const s=Hf(t)-Hf(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),Wf=e=>`${e.conversationType}:${e.conversationId}`,Jf=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Zf=(e,t)=>((e,t)=>Hf(t)>Hf(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Jf(e,t),lastMessageAt:Math.max(e.lastMessageAt??0,t.lastMessageAt??0),isPinned:t.isPinned??e.isPinned,pinnedTimestamp:"number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:e.pinnedTimestamp,marks:t.marks.length>0?t.marks:e.marks,readAt:t.readAt??e.readAt,remindType:t.remindType??e.remindType,conversationName:t.conversationName===t.conversationId?e.conversationName:t.conversationName,conversationAvatar:t.conversationAvatar??e.conversationAvatar,updatedAt:Math.max(e.updatedAt,t.updatedAt)}:e,Qf=e=>{const t=new Map,r=new Set;for(const i of e.snapshot)r.add(Wf(i));for(const i of e.existing)t.set(Wf(i),i);const s=e.snapshot.map(e=>{const r=t.get(Wf(e));return r?Zf(e,r):e}),n=e.existing.filter(t=>!r.has(Wf(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Vf([...s,...n])},Yf=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Xf=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),eg=e=>({userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,lastAccess:e.lastAccess,lastUpdate:e.lastModified});class tg{constructor(){this.records=new Map}clear(){this.records.clear()}get(e,t=!1,r=Date.now()){const s=this.records.get(e)??null;if(!s||!t)return s;const n={...s,lastAccess:r};return this.records.set(e,n),n}setAll(e,t=Date.now()){for(const r of e){const e=r.lastModified??t,s=this.records.get(r.profile.userId),n=s?.lastAccess??t;this.records.set(r.profile.userId,{profile:r.profile,lastModified:e,lastAccess:n,source:r.source})}}applyPatch(e,t,r=Date.now()){const s=this.records.get(e.userId),n={userId:e.userId,...t??{},...s?.profile??{}};if(s&&e.lastModified<s.lastModified)return{applied:!1,reason:"stale",record:s};const i={...n,...e.attributes,userId:e.userId};if(s&&e.lastModified===s.lastModified&&(o=s.profile,a=i,Yf.every(e=>o[e]===a[e])))return{applied:!1,reason:"duplicate",record:s};var o,a;const c={profile:i,lastModified:e.lastModified,lastAccess:s?.lastAccess??r,source:"subscription"===e.source?"subscription_notify":"contact"===e.source?"contact_notify":"own_notify"};return this.records.set(e.userId,c),{applied:!0,reason:"applied",record:c}}}const rg=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class sg{constructor(e){this.conversationDeletionTimestamps=new Map,this.currentConversation=null,this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.flushTimer=null,this.flushIdleHandle=null,this.activeFlushPromise=null,this.sessionListCommitInProgress=!1,this.mutationRevision=0,this.domainRevisions=new Map,this.pendingDirtyRevisions=new Map,this.userId=e.userId,this.config={schemaVersion:1,ttlSeconds:86400,flushIntervalMs:1e3,maxUserInfoCount:1e3,maxGroupNamecardCount:1e3,maxConversations:e.config?.maxConversations,...e.config};const t="off"===e.cacheEncryptionMode?null:new cf(e.appKey,e.userId);this.store=new Cf(t??void 0,e.storageAdapter);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=bf(r,df),this.userInfoKey=bf(r,uf),this.groupNamecardKey=bf(r,lf),this.sessionListKey=bf(r,ff),this.sessionListCheckpointKey=bf(r,gf),this.joinedGroupPreviewKey=bf(r,yf),this.contactRelationKey=bf(r,hf),this.contactVersionKey=bf(r,pf),this.contactMetaKey=bf(r,mf),this.metadataKey=bf(r,vf),this.metadataStore=new If(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Ef,this.userInfoCache=new zf,this.groupNamecardCache=new Nf,this.sessionListCache=new jf,this.joinedGroupPreviewCache=new Df,this.contactCache=new _f,this.userInfoRuntimeStore=new tg,this.loadPromise=this.loadFromStorage()}getConfig(){return this.config}async prepare(){await this.loadPromise}loadConversationSummaries(){return this.conversationCache.getAll()}loadSessionList(){return this.sessionListCache.exportItems()}loadJoinedGroupPreviewSnapshot(){return this.joinedGroupPreviewCache.getSnapshot()}applyJoinedGroupPreviewSnapshot(e){this.joinedGroupPreviewCache.setSnapshot(e),this.scheduleFlush(["joinedGroupPreview"])}async commitJoinedGroupPreviewSnapshot(e){this.activeFlushPromise&&await this.activeFlushPromise;const t=this.getDomainRevision("joinedGroupPreview"),r=new Df;if(r.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,r.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const s=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==s&&s<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),r=t.items.filter(t=>t.groupId!==e);return r.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:r,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let r=!1,s=!1;const n=this.conversationCache.getAll().map(n=>n.conversationId!==e.conversationId||n.type!==e.type?n:(r=!0,0===n.unreadCount?n:(s=!0,{...n,unreadCount:0,lastUpdate:t})));let i=!1;const o=this.sessionListCache.getAll().map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:(r=!0,0===s.unreadCount&&s.readAt===t?s:(i=!0,{...s,unreadCount:0,readAt:t,updatedAt:t})));return s||i?(s&&this.conversationCache.setAll(n),i&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:r}):{items:this.sessionListCache.exportItems(),changed:!1,matched:r}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),r=this.conversationCache.getAll(),s=r.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),r=this.conversationCache.getAll(),s=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:{...r,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(r=>r.conversationId!==e.conversationId||r.conversationType!==e.type?r:{...r,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),r=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,r,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),r=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(r,e.deletedAt))}const s=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),n=r.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),i=s.length!==t.length,o=n.length!==r.length;return i||o?(i&&this.conversationCache.setAll(s),o&&this.sessionListCache.setAll(n),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),n=this.conversationCache.getAll(),i=n.map(e=>{const n=`${e.type}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,lastUpdate:r}}),o=this.sessionListCache.getAll(),a=o.map(e=>{const n=`${e.conversationType}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,updatedAt:r}}),c=!this.isConversationListEqual(n,i),d=!this.isSessionListEqual(o,a);return c||d?(c&&this.conversationCache.setAll(i),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,r){const s=Date.now(),n=e.map(e=>({...e,updatedAt:e.lastMessageAt??s})),i=Qf({snapshot:n,existing:this.sessionListCache.getAll(),syncStartedAt:r?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(i,s)),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}mergeSessionListIncremental(e,t){this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e))),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}async commitSessionListSync(e){this.activeFlushPromise&&await this.activeFlushPromise,this.sessionListCommitInProgress=!0;let t=[],r=this.getDomainRevision("sessionList");try{let s=!1;for(;!s;){const n=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),r=this.getDomainRevision("sessionList"),r===n&&(s=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const n=this.pendingDirtyRevisions.get("sessionList");return void 0!==n&&n<=r&&this.pendingDirtyRevisions.delete("sessionList"),await this.metadataStore.touchLastFlush(),{items:this.sessionListCache.exportItems(),checkpoint:this.sessionListCheckpoint}}finally{this.sessionListCommitInProgress=!1,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}setUserInfoSummaries(e){const t=Date.now();this.userInfoCache.setAll(e,t),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}upsertRuntimeUserInfos(e){0!==e.length&&this.userInfoRuntimeStore.setAll(e)}getRuntimeUserInfo(e,t=!1){return this.userInfoRuntimeStore.get(e,t)?.profile??null}applyUserInfoNotifyPatch(e){const t=this.userInfoCache.getByIds([e.userId],Date.now(),!1)[0],r=t?Xf(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([eg(t)])}getUserInfoSummaries(e,t){const r=Date.now(),s=this.userInfoCache.getByIds(e,r,t);return t&&this.scheduleFlush(["userInfo"]),s}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,r){const s=this.groupNamecardCache.get(e,t,Date.now(),r);return r&&s&&this.scheduleFlush(["groupNamecard"]),s}setGroupNamecards(e){const t=Date.now();this.groupNamecardCache.setAll(e,t),"number"==typeof this.config.maxGroupNamecardCount&&this.groupNamecardCache.trimMax(this.config.maxGroupNamecardCount),this.scheduleFlush(["groupNamecard"])}removeGroupNamecards(e){this.groupNamecardCache.remove(e),this.scheduleFlush(["groupNamecard"])}setContactVersionState(e){this.contactCache.setVersionState(e),this.scheduleFlush(["contactVersion"])}markContactCacheIncomplete(e){this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:e}),this.scheduleFlush(["contactMeta"])}applyContactSync(e){const t=this.loadContactSnapshot("cache"),r=Date.now();this.userInfoCache.setAll(e.userInfos.map(e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext,lastAccess:r,lastUpdate:r})),r),"full"===e.mode?this.contactCache.replaceAll(e.relations):this.contactCache.upsert(e.relations),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.contactCache.setVersionState({version:e.version,lastVersionCheckAt:r,lastVersionSource:"sync_page"}),this.contactCache.updateMeta({cacheIntegrity:"complete",lastSyncTs:e.lastSyncTs,lastSuccessfulVersion:e.version,lastSyncMode:e.mode}),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactRelation","contactVersion","contactMeta"]);const s=this.loadContactSnapshot("sync");return{snapshot:s,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(s)}}refreshSessionListDisplayFromUserInfos(e){const t=new Map;for(const d of e){if(!d.userId)continue;const e=t.get(d.userId);"number"==typeof e&&"number"==typeof d.lastModified&&e>=d.lastModified||t.set(d.userId,d.lastModified)}if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=this.loadContactSnapshot("cache").items,n=new Map(s.map(e=>[e.userId,e])),i=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),o=this.sessionListCache.getAll().map(e=>{let s=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,i)){const t=n.get(e.conversationId),o=this.resolveSessionDisplayUserInfo(e.conversationId,i),a=this.buildSingleSessionDisplayFields(e.conversationId,t,o,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(s={...s,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:r})}const o=s.lastMessage;if(o&&!this.shouldSkipSessionUserDisplayRefresh(o.sender.userId,t,i)){const e=n.get(o.sender.userId),t=this.resolveSessionDisplayUserInfo(o.sender.userId,i),a=this.buildSessionMessageSender(o.sender.userId,o.sender,e,t);this.isSenderEqual(o.sender,a)||(s={...s,lastMessage:{...o,sender:a},updatedAt:r})}return s}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,o);return c&&(this.sessionListCache.setAll(o),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const r=new Map;for(const a of e){const e=a.groupId.trim();e&&r.set(e,a)}if(0===r.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const n=r.get(e.conversationId);if(!n)return e;const i=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&i)return e;const o=n.name?.trim(),a=o||e.conversationName,c=n.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(n.remindType),u=void 0!==d&&d!==e.remindType;return a!==e.conversationName||c!==e.conversationAvatar||u?{...e,conversationName:a,conversationAvatar:c,remindType:u?d:e.remindType,updatedAt:s}:e}),i=this.sessionListCache.getAll(),o=!this.isSessionListEqual(i,n);return o&&(this.sessionListCache.setAll(n),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:o}}removeContact(e){return this.applyContactLocalPatch(()=>this.contactCache.remove(e))}updateContactRemark(e,t){return this.applyContactLocalPatch(()=>this.contactCache.updateRemark(e,t,Date.now()))}applyContactRosterNotice(e){const t=this.loadContactSnapshot("cache"),r=Date.now(),s="add"===e.action?this.contactCache.addByNotice(e.userId,r):this.contactCache.remove(e.userId),n="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,r);(s||n)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const i=this.loadContactSnapshot("cache");return{snapshot:i,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(i)}}updateConversationsFromServer(e,t){const r=Date.now(),s=this.conversationCache.getAll(),n=this.mergeConversationLists(s,e,r,t?.syncStartedAt),i=!this.isConversationListEqual(s,n);return this.conversationCache.setAll(n),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:n,changed:i}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const r=Date.now(),s=this.conversationCache.getAll(),n=s.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),i=n>=0?s[n]:void 0,o=this.buildConversationFromMessage(e,i,r);if(!o)return{items:s,changed:!1};const a=[o,...s.filter((e,t)=>t!==n)];return this.isConversationListEqual(s,a)?{items:s,changed:!1}:(this.conversationCache.setAll(a),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:this.conversationCache.getAll(),changed:!0})}applyIncomingMessageToSessionList(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.sessionListCache.exportItems(),changed:!1};const r=this.sessionListCache.getAll(),s=r.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),n=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!n)return{items:this.sessionListCache.exportItems(),changed:!1};const i=(e=>{const t=Wf(e.nextRecord),r=e.existing.filter(e=>Wf(e)!==t);return Vf([e.nextRecord,...r])})({existing:r,nextRecord:this.buildSessionListRecordFromConversation(n,e,s,Date.now())});return this.isSessionListEqual(r,i)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0})}async loadFromStorage(){const e=Date.now(),t=await this.readDump(this.conversationKey);this.conversationCache.load(t,e);const r=await this.readDump(this.userInfoKey);this.userInfoCache.load(r,e);const s=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(s,e);const n=await this.readValue(this.sessionListKey,null),i=n&&Bl(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(i,e);const o=(n&&Bl(n)&&Bl(n.checkpoint)?n.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(o);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),d=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,d,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&Bl(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&Bl(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=new Map,e}restoreDirtyBatch(e){for(const[t,r]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(r,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const s=6;for(let n=0;n<=s;n+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!Tu(t))return this.restoreDirtyBatch(e),void Si("Cache flush failed",t);const s=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,s),"none"===s)return void Si("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(s)}catch(r){if(!Tu(r))return this.restoreDirtyBatch(e),void Si("Cache quota cleanup persistence failed",r)}}Si("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of rg)e.has(t)&&await this.writeDomain(t)}async writeDomain(e){switch(e){case"conversation":return void(await this.store.writeAsync(this.conversationKey,{items:this.conversationCache.getAll()}));case"userInfo":return void(await this.store.writeAsync(this.userInfoKey,{items:this.userInfoCache.getAll()}));case"groupNamecard":return void(await this.store.writeAsync(this.groupNamecardKey,{items:this.groupNamecardCache.getAll()}));case"sessionList":return void(await this.writeSessionListStorageRecord());case"joinedGroupPreview":return void(await this.store.writeAsync(this.joinedGroupPreviewKey,this.joinedGroupPreviewCache.exportRecord()));case"contactRelation":return void(await this.store.writeAsync(this.contactRelationKey,{items:this.contactCache.getAll()}));case"contactVersion":return void(await this.store.writeAsync(this.contactVersionKey,this.contactCache.getVersionState()));case"contactMeta":await this.store.writeAsync(this.contactMetaKey,this.contactCache.getMeta())}}async writeSessionListStorageRecord(e=this.sessionListCache.getAll(),t=this.sessionListCheckpoint,r=!1){const s={items:e,checkpoint:t};r?await this.store.writeStrictAsync(this.sessionListKey,s):await this.store.writeAsync(this.sessionListKey,s),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),r=new Map;for(const n of t)r.set(`${n.conversationType}:${n.conversationId}`,n);const s=Date.now();return(e=>{const t=e.incoming.filter(e=>Kf(e)>0),r=new Map;for(const n of e.incoming)r.set(Wf(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(Wf(e))&&0===Kf(e)):e.existing.filter(e=>!r.has(Wf(e)));return Vf([...s,...e.incoming])})({existing:t,incoming:this.filterItemsAgainstConversationDeletions(e).map(e=>{const t=`${e.conversationType}:${e.conversationId}`;return{...e,updatedAt:e.lastMessageAt??r.get(t)?.updatedAt??s}})})}buildSessionListSyncCandidate(e){const t=Date.now();if("incremental"===e.mode)return this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e.items),t);const r=this.filterItemsAgainstConversationDeletions(e.items).map(e=>({...e,updatedAt:e.lastMessageAt??t}));return this.hydrateSessionListRecordsFromLocalProfiles(Qf({snapshot:r,existing:this.sessionListCache.getAll(),syncStartedAt:e.syncStartedAt}),t)}filterItemsAgainstConversationDeletions(e){return e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.conversationType),r=this.conversationDeletionTimestamps.get(t);if(void 0===r)return!0;return Math.max(e.lastMessageAt??0,e.lastMessage?.timestamp??0)>r})}getConversationLatestUpdate(e,t,r,s){const n=e.find(e=>e.conversationId===r&&e.type===s),i=t.find(e=>e.conversationId===r&&e.conversationType===s);return Math.max(n?.lastUpdate??0,n?.lastMessage?.timestamp??0,i?.updatedAt??0,i?.lastMessageAt??0,i?.lastMessage?.timestamp??0)}handleQuotaExceeded(){const e=Date.now(),t=1e3*this.config.ttlSeconds;if(this.groupNamecardCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard";const r=this.groupNamecardCache.getAll().length;if(r>0){const e=this.calculateEvictCount(r,.2);if(this.groupNamecardCache.evictByLru(e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard"}if(this.userInfoCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"userInfo";const s=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),s}evictByPolicy(){const e=this.userInfoCache.getAll().length;if(e>0){const t=this.calculateEvictCount(e,.2);return t>0?(this.userInfoCache.evictByLru(t),"userInfo"):"none"}const t=this.conversationCache.getAll().length,r=this.calculateEvictCount(t,.05);return r>0?(this.conversationCache.evictByLru(r),"conversation"):"none"}calculateEvictCount(e,t){if(e<=0)return 0;const r=Math.floor(e*t);return Math.max(r,1)}mergeConversationLists(e,t,r,s){const n=new Map,i=new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);n.set(e,d.lastAccess),i.set(e,d)}const o=[],a=new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=n.get(e)??r;o.push({...d,marks:Array.isArray(d.marks)?d.marks:[],lastAccess:t,lastUpdate:r})}const c=e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.type);return!a.has(t)&&("number"==typeof s&&e.lastUpdate>s)});return[...o,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildConversationSignature(s)!==this.buildConversationSignature(n))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,r=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",s=e.isPinned?"1":"0",n="number"==typeof e.pinnedTime?e.pinnedTime:0,i=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${s}:${n}:${i}:${r}`}buildConversationKey(e,t){return`${t}:${e}`}areConversationMarksEqual(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}buildConversationFromMessage(e,t,r=Date.now()){const s=this.resolveConversationFromMessage(e);if(!s)return null;const n=e.msgServerId||e.msgLocalId,i=t?.lastMessage?.msgId!==n&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,o="SEND"===e.direct?r:t?.lastAccess??r;return{conversationId:s.conversationId,type:s.type,lastMessage:this.buildMessageSnippet(e),unreadCount:i,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:o,lastUpdate:r}}resolveConversationFromMessage(e){if(e.isChatThread||"cmd"===e.type)return null;if("string"!=typeof e.conversationId||!e.conversationId)return null;if("singleChat"===e.conversationType){const t="RECEIVE"===e.direct&&e.from.startsWith(`${this.userId}/`)&&e.sender.userId===this.userId,r="SEND"===e.direct||t?e.conversationId:"string"==typeof e.sender.userId?e.sender.userId:"";return r?{conversationId:r,type:"singleChat"}:null}return"groupChat"===e.conversationType?{conversationId:e.conversationId,type:"groupChat"}:"chatRoom"===e.conversationType?{conversationId:e.conversationId,type:"chatRoom"}:null}buildMessageSnippet(e){const t=(e=>{const t=Ih(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{msgId:e.msgServerId||e.msgLocalId,type:e.type,body:this.normalizeMessageBody(e.body),timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}buildSessionListRecordFromConversation(e,t,r,s=Date.now()){const n=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),i=n.get(e.conversationId),o=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],s,!1)[0],c=o??(a?{userId:a.userId,nickname:a.nickname,avatarUrl:a.avatarUrl,sign:a.sign,ext:a.ext}:null),d=e.lastMessage,u=r?.conversationName,l=r?.conversationAvatar,h="string"==typeof t.sender.userId?t.sender.userId:"",p=this.resolveSessionDisplayUserInfo(h),m=this.buildSessionMessageSender(h,t.sender,n.get(h),p),f="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,g="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,i,c,u,l):"chatRoom"===e.type?this.buildChatRoomSessionDisplayFields(e.conversationId,u,l):this.buildGroupSessionDisplayFields(e.conversationId,u,l);return{conversationId:e.conversationId,conversationType:e.type,unreadCount:this.resolveSessionListUnreadCount(e,t,r),lastMessage:d?{msgServerId:d.msgId,from:h,to:f,sender:m,conversationId:e.conversationId,conversationType:e.type,type:t.type,sendStatus:t.sendStatus,timestamp:d.timestamp,direct:t.direct,body:d.body}:null,lastMessageAt:d?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:r?.readAt,remindType:r?.remindType??"DEFAULT",conversationName:g.conversationName,conversationAvatar:g.conversationAvatar,updatedAt:s}}resolveSessionListUnreadCount(e,t,r){const s=r?.unreadCount,n=t.msgServerId||t.msgLocalId;return r?.lastMessage?.msgServerId!==n&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof s?Math.max(e.unreadCount,s+1):e.unreadCount:"number"==typeof s?Math.max(e.unreadCount,s):e.unreadCount}shouldIncreaseUnreadForMessage(e){if("RECEIVE"!==e.direct||!1===e.isOnline)return!1;const t=this.resolveConversationFromMessage(e);return!t||!this.currentConversation||(this.currentConversation.conversationId!==t.conversationId||this.currentConversation.type!==t.type)}buildSingleSessionDisplayFields(e,t,r,s,n){const i=t?.remark?.trim(),o=t?.userInfo.avatarUrl??r?.avatarUrl??n;if(i)return{conversationName:i,conversationAvatar:o};const a=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return a?{conversationName:a,conversationAvatar:o}:s?{conversationName:s,conversationAvatar:o}:{conversationName:e,conversationAvatar:o}}shouldSkipSessionUserDisplayRefresh(e,t,r){if(!t.has(e))return!0;const s=t.get(e),n=r.get(e);return"number"==typeof s&&"number"==typeof n?.lastUpdate&&n.lastUpdate>s}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const r=this.loadContactSnapshot("cache").items,s=new Map(r.map(e=>[e.userId,e])),n=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const r=e.lastMessage;if(!r)return e;const i=r.sender.userId,o=s.get(i),a=this.resolveSessionDisplayUserInfo(i,n),c="singleChat"===e.conversationType&&i===e.conversationId?this.buildSingleChatPeerMessageSender(i,r.sender,o,a):this.buildSessionMessageSender(i,r.sender,o,a);return this.isSenderEqual(r.sender,c)?e:{...e,lastMessage:{...r,sender:c},updatedAt:t}})}resolveSessionDisplayUserInfo(e,t){const r=this.userInfoRuntimeStore.get(e,!1)?.profile;if(r)return r;const s=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return s?Xf(s):null}buildSessionMessageSender(e,t,r,s){const n=r?.remark?.trim();return{userId:e,nickname:n||r?.userInfo.nickname?.trim()||s?.nickname?.trim()||t?.nickname?.trim()||void 0,avatarUrl:r?.userInfo.avatarUrl??s?.avatarUrl??t?.avatarUrl}}buildSingleChatPeerMessageSender(e,t,r,s){const n=this.buildSessionMessageSender(e,void 0,r,s);return{userId:e,nickname:t?.nickname?.trim()||n.nickname,avatarUrl:t?.avatarUrl||n.avatarUrl}}isSenderEqual(e,t){return e.userId===t.userId&&e.nickname===t.nickname&&e.avatarUrl===t.avatarUrl}buildGroupSessionDisplayFields(e,t,r){return t?{conversationName:t,conversationAvatar:r}:{conversationName:e}}mapJoinedGroupRemindTypeToSession(e){if("DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e)return e}buildChatRoomSessionDisplayFields(e,t,r){return t?{conversationName:t,conversationAvatar:r}:{conversationName:e}}isSessionListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildSessionListSignature(s)!==this.buildSessionListSignature(n))return!1}return!0}buildSessionListSignature(e){const t=e.lastMessage,r=t?`${t.msgServerId}:${t.from}:${t.to}:${t.conversationId}:${t.conversationType}:${t.type}:${t.sendStatus??""}:${t.direct??""}:${t.sender.userId}:${t.sender.nickname??""}:${t.sender.avatarUrl??""}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",s=`${e.conversationName}:${e.conversationAvatar??""}`;return[e.conversationType,e.conversationId,e.unreadCount,e.isPinned?"1":"0",e.pinnedTimestamp??0,e.marks.join(","),e.readAt??0,e.remindType,e.lastMessageAt??0,s,r].join(":")}refreshContactCacheIntegrity(e=!0){const t=this.contactCache.computeIntegrity(this.userInfoCache.getAll());this.contactCache.setMeta(t),e&&this.scheduleFlush(["contactMeta"])}buildContactSnapshotSignature(e){const t=e.items.map(e=>`${e.userId}:${e.userInfo.nickname??""}:${e.userInfo.avatarUrl??""}:${e.userInfo.sign??""}:${e.userInfo.ext??""}:${e.remark}:${e.addTs}`).join("|");return`${e.version}:${e.complete?"1":"0"}:${t}`}applyContactLocalPatch(e){const t=this.loadContactSnapshot("cache"),r=e();return r&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactMeta"])),{snapshot:this.loadContactSnapshot("cache"),changed:r&&this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(this.loadContactSnapshot("cache"))}}}class ng{constructor(){this.handlers=new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const r=[],s=[];for(const i of this.handlers.entries()){const[e]=i;e.startsWith("__internal")?r.push(i):s.push(i)}const n=this.dispatchToHandlers(e,t,r);n?n.then(()=>{this.dispatchToHandlers(e,t,s)}):this.dispatchToHandlers(e,t,s)}dispatchToHandlers(e,t,r){let s=null;for(const[,n]of r){const r=n[e];r&&(s=s?s.then(async()=>{await this.invokeHandler(e,t,r)}):this.invokeHandler(e,t,r))}return s}invokeHandler(e,t,r){try{const s=r(t);return this.isPromiseLike(s)?Promise.resolve(s).then(()=>{}).catch(t=>{Ti(`Event handler error for ${e}`,t)}):null}catch(s){return Ti(`Event handler error for ${e}`,s),null}}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const ig={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function og(e,t){const r=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),s=Math.min(r,t.maxDelay);if(t.jitter){const e=.2*s,t=(2*Math.random()-1)*e;return Math.max(0,s+t)}return s}function ag(e){return new Promise(t=>setTimeout(t,e))}const cg=e=>{const t={...e};return delete t.type,t},dg=(e,t)=>{const r=e.lastMessage;if(!r)return null;const s=((e,t)=>{const r=t.getCurrentUserId?.()??"",s="singleChat"===e.type?e.conversationId:"";return{from:s,to:"singleChat"===e.type?r:e.conversationId,sender:{userId:s}}})(e,t);return{msgServerId:r.msgId,from:s.from,to:s.to,sender:s.sender,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof r.type&&r.type.length>0?r.type:"text",timestamp:r.timestamp,body:cg(r.body),modifiedInfo:r.modifiedInfo,userInfoUpdateTime:r.userInfoUpdateTime,namecardUpdateTime:r.namecardUpdateTime}},ug=async(e,t)=>{const r=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!r)return new Map;const s=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===s.length)return new Map;const n=[];for(let a=0;a<s.length;a+=50)n.push(s.slice(a,a+50));const i=new Map;let o=0;return await Promise.all(Array.from({length:Math.min(3,n.length)},async()=>await(async()=>{for(;o<n.length;){const e=o;o+=1;const t=n[e];if(t)try{const e=await r.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&i.set(t.groupId,t)}catch{}}})())),i},lg=async(e,t)=>{const r=await ug(e,t);return e.map(e=>((e,t,r)=>{const s=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),n=((e,t)=>{const r=e.getCacheManager();if(!r)return null;const s=r.getRuntimeUserInfo(t,!1);if(s)return s;const n=r.getUserInfoSummaries([t],!1)[0];return n?{userId:n.userId,nickname:n.nickname,avatarUrl:n.avatarUrl,sign:n.sign,ext:n.ext}:null})(t,e.conversationId),i="singleChat"===e.type?((e,t,r)=>{const s=t?.remark?.trim();if(s)return{conversationName:s,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl};const n=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return n?{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}})(e.conversationId,s,n):"groupChat"===e.type?(o=e.conversationId,a=r.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:o}):(e=>({conversationName:e}))(e.conversationId);var o,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:dg(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:i.conversationName,conversationAvatar:i.conversationAvatar}})(e,t,r))};class hg{constructor(e=`session-list-${dm()}`){this.status="idle",this.seenBatchKeys=new Set,this.itemsByConversation=new Map,this.batchCount=0,this.requestId=e,this.startedAt=Date.now()}getRequestId(){return this.requestId}getStartedAt(){return this.startedAt}start(){"idle"===this.status&&(this.status="connecting")}markSyncing(){if("completed"===this.status||"failed"===this.status||"cancelled"===this.status)throw new Hr("Session-list sync session cannot re-enter syncing state after completion",Sr);this.status="syncing"}pushBatch(e){if(e.requestId!==this.requestId)throw new Hr("Session-list sync requestId mismatch",Sr,{details:{expected:this.requestId,received:e.requestId}});if(this.isTerminal())throw new Hr("Session-list sync batch received after terminal state",Sr,{details:{requestId:e.requestId,status:this.status}});const t=(r=e.requestId,s=e.batchSequence,`${r}:${s}`);var r,s;if(this.seenBatchKeys.has(t))return{accepted:!1,done:e.isLastBatch};this.markSyncing(),this.seenBatchKeys.add(t);for(const n of e.sessions)this.itemsByConversation.set(`${n.conversationType}:${n.conversationId}`,n);return this.batchCount+=1,e.isLastBatch&&(this.status="completed",this.finishedAt=Date.now()),{accepted:!0,done:e.isLastBatch}}fail(){this.status="failed",this.finishedAt=Date.now()}cancel(){this.status="cancelled",this.finishedAt=Date.now()}getItems(){return[...this.itemsByConversation.values()]}getBatchCount(){return this.batchCount}getStatus(){return this.status}buildSnapshot(){return{requestId:this.requestId,status:this.status,pageCount:this.batchCount,startedAt:this.startedAt,finishedAt:this.finishedAt,seenBatchKeys:[...this.seenBatchKeys]}}isTerminal(){return"completed"===this.status||"failed"===this.status||"cancelled"===this.status}}const pg=0,mg=5,fg=10,gg=11,yg=1,vg=2,bg=1,Ig=2,wg=3,Cg=e=>e===yg?"groupChat":e===vg?"chatRoom":"singleChat",Sg=()=>vl().lookupType("easemob.pb.MessageBody"),Tg=e=>{const t=Sg().toObject(Sg().decode(e),{longs:Number,bytes:Uint8Array}),r=Array.isArray(t.contents)?t.contents:[],s=(n=r[0])&&"object"==typeof n&&!Array.isArray(n)?n:{};var n;const i="number"==typeof s.type?s.type:ys,o="string"==typeof s.remotePath&&s.remotePath.length>0||"string"==typeof s.title&&s.title.length>0||"string"==typeof s.summary&&s.summary.length>0||"number"==typeof s.combineLevel&&s.combineLevel>0,a=Object.prototype.hasOwnProperty.call(s,"subType")&&0===s.subType;return i===_s||i===ys&&(a||o)?{type:"combine",title:"string"==typeof s.title?s.title:"",summary:"string"==typeof s.summary?s.summary:"",filename:"string"==typeof s.displayName?s.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof s.remotePath?s.remotePath:void 0,secret:"string"==typeof s.secretKey?s.secretKey:void 0,fileLength:"number"==typeof s.fileLength?s.fileLength:void 0,combineLevel:"number"==typeof s.combineLevel?s.combineLevel:0}:i===ys?{type:"text",content:"string"==typeof s.text?s.text:""}:1===i?{type:"image",filename:"string"==typeof s.displayName?s.displayName:"image",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:2===i?{type:"video",filename:"string"==typeof s.displayName?s.displayName:"video",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:3===i?{type:"location",latitude:"number"==typeof s.latitude?s.latitude:0,longitude:"number"==typeof s.longitude?s.longitude:0,address:"string"==typeof s.address?s.address:void 0}:4===i?{type:"voice",filename:"string"==typeof s.displayName?s.displayName:"voice",remotePath:"string"==typeof s.remotePath?s.remotePath:"",duration:"number"==typeof s.duration?s.duration:0}:5===i?{type:"file",filename:"string"==typeof s.displayName?s.displayName:"file",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:6===i?{type:"cmd",action:"string"==typeof s.action?s.action:""}:7===i?{type:"custom",event:"string"==typeof s.customEvent?s.customEvent:""}:{}},_g=e=>{const t=e.session_id??"",r=(e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{return null}return null})(e.metadata),s="string"==typeof r?.nickname?r.nickname:void 0,n="string"==typeof r?.remark?r.remark:void 0,i="string"==typeof r?.avatarurl?r.avatarurl:"string"==typeof r?.avatarUrl?r.avatarUrl:void 0;return n?{conversationName:n,conversationAvatar:i}:s?{conversationName:s,conversationAvatar:i}:{conversationName:t,conversationAvatar:i}},Rg=e=>{const t={...e};return delete t.type,t},Ag=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,Mg=(e,t,r)=>{if(!e)return null;const s=(e=>{if(!e)return"";const t=e.lastIndexOf("_");return t>=0?e.slice(t+1):e})(e.from?.name),n={userId:s};return"singleChat"===r.conversationType&&s===r.conversationId&&r.singleChatPeerDisplay&&(r.singleChatPeerDisplay.conversationName!==s&&(n.nickname=r.singleChatPeerDisplay.conversationName),r.singleChatPeerDisplay.conversationAvatar&&(n.avatarUrl=r.singleChatPeerDisplay.conversationAvatar)),{msgServerId:e.id??"",from:s,to:Ag({conversationId:r.conversationId,conversationType:r.conversationType,from:s,currentUserId:r.currentUserId}),sender:n,conversationId:r.conversationId,conversationType:r.conversationType,type:(i=t.type,"text"===i||"image"===i||"file"===i||"voice"===i||"video"===i||"location"===i||"custom"===i||"cmd"===i||"combine"===i?i:"text"),timestamp:e.timestamp??0,body:Rg(t)};var i},Eg=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},Ug=(e,t)=>e.sessions.map(e=>{const r=(e=>{if(!e||0===e.byteLength)return{};try{return Tg(e)}catch{return{}}})(e.last_message?.payload),s=e.session_id??"",n=Cg(e.session_type),i=(e=>{const t=e.session_id??"",r=Cg(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:_g(e)})(e);return{conversationId:s,conversationType:n,unreadCount:e.unread_count??0,lastMessage:Mg(e.last_message,r,{conversationId:s,conversationType:n,currentUserId:t,singleChatPeerDisplay:"singleChat"===n?i:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:Eg(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===bg?"ALL":o===Ig?"AT":o===wg?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),Ng={nested:{easemob:{nested:{sessionlist:{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}}},JID:{fields:{app_key:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},client_resource:{type:"string",id:4}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},timestamp:{type:"uint64",id:4},payload:{type:"bytes",id:6}}},SessionItem:{fields:{session_id:{type:"string",id:1},session_type:{type:"int32",id:2},last_message:{type:"Meta",id:3},updated_at:{type:"int64",id:6},pinned_time:{type:"int64",id:7},unread_count:{type:"uint32",id:8},marks:{rule:"repeated",type:"string",id:9},read_receipt:{type:"int64",id:10},remind_type:{type:"int32",id:11},group_name:{type:"string",id:12},group_avatar:{type:"string",id:13},metadata:{type:"string",id:14}}},GetSessionListRequest:{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},need_empty_session:{type:"bool",id:7},need_session_mark:{type:"bool",id:8}}},GetSessionListResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},sessions:{rule:"repeated",type:"SessionItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let kg=null,Og=!1;const xg=()=>kg||(Og||(Vc.util.Long=mo,Vc.configure(),Og=!0),Sd(),kg=Vc.Root.fromJSON(Ng),Cd(kg),kg),Lg=e=>xg().lookupType(e),Pg=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("bigint"==typeof e)return Number(e);if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},Dg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Pg(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Pg(t.protocol_version)??Pg(t.protocolVersion)??0}},qg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{appKey:"string"==typeof t.app_key?t.app_key:"string"==typeof t.appKey?t.appKey:void 0,name:"string"==typeof t.name?t.name:void 0,domain:"string"==typeof t.domain?t.domain:void 0,clientResource:"string"==typeof t.client_resource?t.client_resource:"string"==typeof t.clientResource?t.clientResource:void 0}},Bg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Pg(t.id)?String(Pg(t.id)):void 0,from:qg(t.from),timestamp:Pg(t.timestamp),payload:t.payload instanceof Uint8Array?t.payload:Array.isArray(t.payload)?Uint8Array.from(t.payload.filter(e=>"number"==typeof e)):void 0}};class $g{constructor(){this.requestType=Lg("easemob.sessionlist.GetSessionListRequest"),this.responseType=Lg("easemob.sessionlist.GetSessionListResponse"),this.errorType=Lg("easemob.sessionlist.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,need_empty_session:e.includeEmpty??!1,need_session_mark:e.includeMark??!0});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 s=this.tryDecodeRequest(e);return s||{type:pg}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=Pg(t.type);return r!==fg?null:{type:r,header:Dg(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Pg(t.last_sync_time)??0,includeEmpty:!0===t.need_empty_session,includeMark:!0===t.need_session_mark}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=Pg(t.type);return r!==gg?null:{type:r,header:Dg(t.header),sessions:Array.isArray(t.sessions)?t.sessions.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{session_id:"string"==typeof t.session_id?t.session_id:void 0,session_type:Pg(t.session_type),last_message:Bg(t.last_message),updated_at:Pg(t.updated_at),pinned_time:Pg(t.pinned_time),unread_count:Pg(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Pg(t.read_receipt),remind_type:Pg(t.remind_type),group_name:"string"==typeof t.group_name?t.group_name:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:void 0,metadata:"string"==typeof t.metadata?t.metadata:void 0}})(e)):[],isLastBatch:!0===t.is_last_batch,lastSyncFinishedTs:Pg(t.last_sync_finished_ts)}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=Pg(t.type);return r!==mg?null:{type:r,header:Dg(t.header),code:Pg(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Fg=async e=>{const t=e.client.getCacheManager(),r=e.client.getRestContext(),s=e.client.getSessionListSyncWsUrls();if(!t||0===s.length)throw new Wr("session-list sync websocket is unavailable",{code:gt,details:{protocol:"session-list",stage:"socket_connect"}});const[n,i]=r.appKey.split("#");if(!n||!i)throw new Zr("session-list appKey is invalid",{code:it,details:{appKey:r.appKey}});const o=t.loadSessionListCheckpoint(),a=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:e.session.getRequestId(),resource:r.clientResource,org:n,app:i,username:r.userId,lastSyncTime:(c=o.sessionsLastSyncTs,Math.max(0,c-2e4)),params:e.params});var c;const d=new $g;let u=0,l=o.sessionsLastSyncTs;return await e.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:e.session.getRequestId(),encode:()=>d.encodeRequest(a),decode:e=>{const t=d.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:t=>{if(5===t.type&&"code"in t&&"message"in t)throw 1002===(s=t).code?new Jr(s.message,{code:lt,details:{protocol:"session-list",responseCode:s.code}}):1003===s.code?new Hr(s.message,Nt,{details:{protocol:"session-list",responseCode:s.code}}):1501===s.code||1001===s.code?new Zr(s.message,{code:it,details:{protocol:"session-list",responseCode:s.code}}):1503===s.code?new Hr(s.message,Ut,{details:{protocol:"session-list",responseCode:s.code}}):(s.code,new Hr(s.message,fr,{details:{protocol:"session-list",responseCode:s.code}}));var s;if(11!==t.type)throw new Hr("session-list response type is invalid",Mt,{details:{responseType:t.type}});const n=t,i=n.header?.requestId;if(i&&i!==e.session.getRequestId())return;u+=1,Ci("Decoded session-list sync raw response",{requestId:e.session.getRequestId(),batchSequence:u,response:n});const o=Ug(n,r.userId),a=e.session.pushBatch({requestId:e.session.getRequestId(),batchSequence:u,sessions:o,isLastBatch:!0===n.isLastBatch,lastSyncFinishedTs:n.lastSyncFinishedTs});if("number"==typeof n.lastSyncFinishedTs&&(l=n.lastSyncFinishedTs),!a.done)return;return{done:!0,result:{items:e.session.getItems(),lastSyncFinishedTs:l}}}})},Gg=e=>new Zr(`${e} must be a local paging cursor returned by SDK`,{code:it,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),jg=(e,t,r)=>{const s=e+t;return s<r?String(s):""},zg=e=>({...e}),Kg=e=>{const t=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),r=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:r,lastUpdate:r}},Hg=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,Vg=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new Zr("pageSize must be a positive integer",{code:it,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const t=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw Gg(t);const r=Number.parseInt(e,10);if(!Number.isSafeInteger(r)||r<0)throw Gg(t);return r})(e.cursor,"cursor"),r=[];for(const s of e.items){if("chatRoom"===s.conversationType)continue;const e=Hg(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:jg(t,e.pageSize,r.length)}},Wg=()=>Date.now(),Jg={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Zg=(e,t)=>({status:e,determinedAt:Wg(),reason:t}),Qg=e=>e instanceof Hr&&(e.code===Nt||1103===e.code),Yg=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Qg(e)});class Xg{constructor(e){this.running=null,this.currentSession=null,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}refresh(e){return this.running||(this.currentSession=new hg,this.currentSession.start(),this.running=this.runRefresh(this.currentSession,{includeEmpty:e.includeEmpty,includeMark:!0}),this.running.finally(()=>{this.running=null,this.currentSession=null})),this.running}async runRefresh(e,t){const r=this.client.getCacheManager();if(!r)return[];this.client.emitSyncDataStart("conversation");const s=await this.tryDirectFallback(r);if(s)return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),s;try{const s=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let i=0;const o=await async function(e,t,r={}){const s={...ig,...r};let n;for(let o=1;o<=s.maxAttempts;o++)try{return await e()}catch(i){if(n=i,!t(i))throw i;if(o>=s.maxAttempts)throw i;const e=og(o,s);await ag(e)}throw n}(async()=>{i+=1;const r=1===i?e:this.createRetrySession();r.start();try{return await Fg({client:this.client,session:r,params:t})}catch(s){throw r.fail(),s}},Qg,Jg),a={result:o,syncStartedAt:e.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:Wg()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:Wg()};try{await r.commitSessionListSync({items:c,mode:s,checkpoint:d,syncStartedAt:a.syncStartedAt})}catch(n){e.fail();const t=new Xr("Session-list final persistence failed",{details:{cause:n instanceof Error?n.message:String(n)}});return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Yg(t)}),r.loadSessionList()}const u=r.loadSessionList();return r.updateConversationsFromServer(u.map(Kg),{syncStartedAt:a.syncStartedAt}),await r.flushPending(),this.client.emitConversationListUpdate("conversation","full"===s),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),u}catch(n){const t=n instanceof Hr?n:new Hr(n instanceof Error?n.message:String(n));e.fail();const s=(e=>e.code===Ut||e.code===dt?{capabilityState:Zg("unsupported",e.message),shouldUseFallback:!0}:e.code===lt||e.code===ht?{shouldUseFallback:!0}:e.code===Nt||1103===e.code?{shouldUseFallback:!0,shouldRetry:!0}:e.code===Sr?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(t);s.capabilityState&&(this.capabilityState=s.capabilityState),s.shouldResetCheckpoint&&r.resetSessionListCheckpoint();const i=await this.buildFallbackSessionList(r);return s.shouldUseFallback&&r.replaceSessionList(i),this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Yg(t)}),i}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}var t;const r=Boolean(this.client.getServerUrlsConfig()?.syncWsUrl),s=this.client.isSessionListDnsProbeAvailable();if(!r&&!s){this.capabilityState=Zg("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new hg}async buildFallbackSessionList(e){return await(async(e,t)=>await lg(e,t))(e.loadConversationSummaries(),this.client)}}const ey=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),ty=async e=>{if("string"==typeof e||ey(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):ey(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength))(e);if((e=>"undefined"!=typeof Blob&&e instanceof Blob&&"function"==typeof e.arrayBuffer||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e))return new Uint8Array(await e.arrayBuffer());throw new Hr("sync websocket frame payload type is invalid",Tr,{details:{stage:"response_decode",payloadType:typeof e}})},ry=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},sy=async e=>{await new Promise(t=>{setTimeout(t,e)})},ny=e=>e instanceof Error?e:new Error(String(e));class iy{constructor(e){this.pending=new Map,this.socket=null,this.state="idle",this.connectPromise=null,this.activeUrl="",this.urlIndex=0,this.attempt=0,this.connectTimer=null,this.idleTimer=null,this.retryTimer=null,this.completeCloseTimer=null,this.cancelled=!1,this.getUrls=e.getUrls,this.socketAdapter=e.socketAdapter}async request(e){if(this.cancelled)throw new Hr("sync websocket session is cancelled",_r,{details:{stage:"cancelled",requestId:e.requestId}});if(this.pending.has(e.requestId))throw new Hr("sync websocket requestId is duplicated",it,{details:{stage:"request_send",requestId:e.requestId}});this.clearCompleteCloseTimer();const t=new Promise((t,r)=>{this.pending.set(e.requestId,{...e,resolve:t,reject:r})});t.catch(()=>{});try{await this.ensureConnected(),this.sendPendingRequest(this.pending.get(e.requestId))}catch(r){this.rejectPending(e.requestId,ny(r))}return await t}cancel(e="sync-websocket-cancelled"){this.cancelled=!0;const t=new Hr("sync websocket cancelled",_r,{details:{stage:"cancelled",reason:e}});this.rejectAll(t),this.closeSocket(4001,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}close(e="sync-websocket-closed"){this.closeSocket(1e3,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}async ensureConnected(){if("open"!==this.state||this.socket?.readyState!==ji){if(this.connectPromise)return await this.connectPromise;this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let e=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&Si("sync websocket retry started",this.buildLogContext({reason:e?.message}));try{return void(await this.openSocket())}catch(t){if(e=ny(t),this.cancelled||0===this.pending.size)throw e;if(this.attempt>=3)throw Si("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),e;const r=ry(this.attempt);Si("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await sy(r)}}throw new Wr("sync websocket retry exhausted",{code:Cr,details:{stage:"socket_connect",reason:e?.message??"unknown"}})}async openSocket(){const e=await this.getUrls();if(0===e.length)throw new Wr("sync websocket urls are unavailable",{code:Cr,details:{stage:"socket_connect"}});const t=e[this.urlIndex%e.length];if(this.urlIndex+=1,!t)throw new Wr("sync websocket url is invalid",{code:Cr,details:{stage:"socket_connect"}});this.activeUrl=t,this.state="connecting",Si("sync websocket connect started",this.buildLogContext());const r=Vi(),s=this.socketAdapter??Hd({webSocketCtor:r.WebSocket});if(!s)throw this.state="idle",this.buildConnectionError("sync websocket adapter is unavailable","socket_connect");let n=null;try{const e=await Promise.race([s.connect({url:t}),new Promise((e,t)=>{n=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},5e3)})]);n&&clearTimeout(n),this.socket=e,e.onMessage(t=>{this.socket===e&&this.handleMessage(t)}),e.onError(()=>{this.socket===e&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),e.onClose(t=>{if(this.socket===e)return"closing"===this.state||0===this.pending.size?(this.clearTimers(),this.socket=null,void(this.state="idle")):void this.handleSocketFailure(this.buildConnectionError("sync websocket socket closed","sync_page",{closeCode:t.code,closeReason:t.reason}))}),this.state="open",this.resetIdleTimer(),Si("sync websocket connected",this.buildLogContext())}catch(i){if(n&&clearTimeout(n),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),i instanceof Wr)throw i;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:i instanceof Error?i.message:String(i)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await ty(e);if(!(await this.routeFrame(t)))return}catch(t){const e=ny(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(e){const t=[];let r=null;for(const n of this.pending.values())try{const t=n.decode(e);if(t.requestId&&t.requestId===n.requestId){try{const e=await n.onFrame(t.frame,this.socket);e?.done&&(this.pending.delete(n.requestId),n.resolve(e.result),this.closeIfComplete())}catch(s){this.pending.delete(n.requestId),n.reject(ny(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(ny(s))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&t.length===this.pending.size)throw new Hr("sync websocket frame decode failed",Tr,{details:{stage:"response_decode",cause:t[0]?.message}});return Si("sync websocket frame ignored",this.buildLogContext({reason:t[0]?.message??"requestId not matched"})),!1}handleSocketFailure(e){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(Si("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),void this.rejectAll(e)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(ny(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(e){if(e&&this.socket&&this.socket.readyState===ji)try{this.socket.send(e.encode()).catch(t=>{this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}),Si("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(t){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}}rejectPending(e,t){const r=this.pending.get(e);r&&(this.pending.delete(e),r.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(Si("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},0))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},1e4))}clearTimers(){this.clearConnectTimer(),this.clearIdleTimer(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.clearCompleteCloseTimer()}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearCompleteCloseTimer(){this.completeCloseTimer&&(clearTimeout(this.completeCloseTimer),this.completeCloseTimer=null)}closeSocket(e,t){const r=this.socket;this.socket=null,!r||r.readyState>=zi||(this.state="closing",r.close(e,t))}buildConnectionError(e,t,r={}){return new Wr(e,{code:Cr,details:{stage:t,url:this.activeUrl,...r}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:zr(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const oy=(e,t)=>{if(!e.matchField)return!1;const r=t[e.matchField];return void 0!==e.matchPattern?"string"==typeof r&&r.includes(e.matchPattern):void 0===e.matchValue?void 0!==r:r===e.matchValue||!("string"!=typeof r&&"number"!=typeof r||"string"!=typeof e.matchValue&&"number"!=typeof e.matchValue)&&String(r)===String(e.matchValue)};function ay(e){const t=e.entry?.code??fr,r=e.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:e.apiName,entry:e.entry,mapped:e.mapped,reasonKey:e.reasonKey});return new ts(r,{code:t,details:{api:e.apiName,serverCode:e.serverCode,serverMessage:e.serverMessage,httpStatus:e.httpStatus,mapped:e.mapped??Boolean(e.entry),reasonKey:e.reasonKey,matchedBy:e.matchedBy,retryable:e.entry?.retryable,canonicalCode:e.entry?.canonicalCode??e.entry?.code}})}const cy={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"}},dy=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),uy=e=>{if(Array.isArray(e))return e.length;if(!e||"object"!=typeof e)return;const t=e;for(const r of["entities","data","items","messages","conversations","results"]){const e=t[r];if(Array.isArray(e))return e.length}};class ly{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=t?.requestAdapter,this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),r=t.searchParams;for(const e of r.keys())r.set(e,"***");const s=r.toString(),n=s?`?${s}`:"";return`${t.origin}${t.pathname}${n}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(e,t,r,s){const n={...t.operation?{api:t.operation}:{},url:t.url,method:t.method,httpStatus:e,serverCode:r,serverMessage:s,mapped:!1};if(400===e)return new Zr("Invalid request parameters",{code:ot,details:{...n,canonicalCode:ot}});if(401===e){const e=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),t=e?lt:dt;return new Jr(e?"Authentication token expired":"Authentication failed",{code:t,details:{...n,reasonKey:e?"token_expired":"unauthorized",canonicalCode:t}})}return 403===e?new Jr("Access forbidden",{code:ut,details:{...n,canonicalCode:ut}}):429===e?new ts("REST rate limit exceeded",{code:Fr,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:Fr}}):e>=500?new ts("REST business error: request failed",{code:fr,details:{...n,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:fr}}):void 0}async request(e,t={}){const r=`${this.baseUrl}${e}`,s=t.method??"GET",n=Date.now(),i=this.sanitizeUrl(r);Ci("REST request",{method:s,url:i,operation:t.operation});const o=t.operation?(e=>{const t=cy[e];if(t)return t;const r=(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_${dy(e)}`,operationType:r}})(t.operation):void 0,a=o?nm(o):void 0,c=a?.startRequest({requestName:o?.operationName,method:s,url:r});let d=0;const u={...this.defaultHeaders,...t.headers};this.includeRequestId&&(u[Ml]=Al());const l={method:s,headers:u};if(t.body&&"GET"!==s){const e=Object.keys(u).some(e=>"content-type"===e.toLowerCase());"string"==typeof t.body?(e||(u["Content-Type"]="application/x-www-form-urlencoded"),l.body=t.body):(e||(u["Content-Type"]="application/json"),l.body=JSON.stringify(t.body))}else if("GET"===s)for(const p of Object.keys(u))"content-type"===p.toLowerCase()&&delete u[p];try{if(this.requestAdapter){const e=await this.requestAdapter.request({url:r,method:s,headers:u,body:t.body,timeoutMs:t.timeout??this.timeout});d=e.status;const o=((e,t)=>{if("string"!=typeof e)return e;const r=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),s=e.trim();if(!(r?.[1].includes("application/json")||s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]")))return e;try{return JSON.parse(s)}catch{return e}})(e.data,e.headers),l=Date.now()-n;(e.status<200||e.status>=300)&&(Si("REST response error",{method:s,url:i,status:e.status,duration:l}),this.handleErrorPayload(e.status,"",o,{operation:t.operation,url:r,method:s})),Ci("REST response",{method:s,url:i,status:e.status,duration:l});const h=uy(o);return c?.finish({code:e.status,success:!0,resultCount:h}),a?.finish({code:0,success:!0,resultCount:h}),o}const e=new AbortController,o=setTimeout(()=>e.abort(),t.timeout??this.timeout),h=await fetch(r,{...l,signal:e.signal});d=h.status,clearTimeout(o);const p=Date.now()-n;h.ok||(Si("REST response error",{method:s,url:i,status:h.status,duration:p}),await this.handleErrorResponse(h,{operation:t.operation,url:r,method:s})),Ci("REST response",{method:s,url:i,status:h.status,duration:p});const m=h.headers.get("content-type");if(m?.includes("application/json")){const e=await h.json(),t=uy(e);return c?.finish({code:h.status,success:!0,resultCount:t}),a?.finish({code:0,success:!0,resultCount:t}),e}const f=await h.text();return c?.finish({code:h.status,success:!0}),a?.finish({code:0,success:!0}),f}catch(h){const e=0!==d?d:h instanceof Hr?h.code:-1,n=h instanceof Error?h.message:String(h);if(c?.finish({code:e,success:!1,description:n}),a?.finish({code:e,success:!1,description:n}),h instanceof Hr)throw h;if(h instanceof Error&&"AbortError"===h.name)throw Si("REST request timeout",{method:s,url:i,timeout:t.timeout??this.timeout}),new es(`Request timeout: ${r}`,{code:pr,details:{url:r,method:s,timeout:t.timeout??this.timeout}});throw Si("REST request failed",{method:s,url:i}),new es(`Request failed: ${r}`,{code:hr,details:{url:r,method:s}})}}async handleErrorResponse(e,t){let r;try{r=await e.json()}catch{r=await e.text()}this.handleErrorPayload(e.status,e.statusText,r,t)}handleErrorPayload(e,t,r,s){const n=r&&"object"==typeof r?r:{},i=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const r=e.error,s=r.code;if("number"!=typeof s&&"string"!=typeof s)return;const n=String(s);return/^\d{7}$/.test(n)&&Number(n.slice(0,3))===t?r:void 0})(n,e),o=i?{...n,code:i.code,message:i.message}:r,a=function(e,t,r){if(!e)return;const s=r&&"object"==typeof r?r:{},n="string"==typeof s.error?s.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)(s),o="string"==typeof s.error_description?s.error_description:"string"==typeof s.message?s.message:void 0,a=(e,t=!1)=>{const r=(e,r,s)=>({reasonKey:e,entry:r,matchedBy:t?"common":s});if(n&&e[n])return r(n,e[n],"key");for(const[n,i]of Object.entries(e))if(oy(i,s))return r(n,i,"field");if(void 0!==i)for(const[s,n]of Object.entries(e)){if(n.code===i||n.canonicalCode===i)return r(s,n,"code");if(Array.isArray(n.aliases)&&n.aliases.includes(String(i)))return r(s,n,"alias")}if(o)for(const[s,n]of Object.entries(e))if(Array.isArray(n.aliases)&&n.aliases.includes(o))return r(s,n,"alias")},c=t?e.apis[t]:void 0,d=c?a(c.errors):void 0;if(d)return d;for(const u of Object.values(e.common)){const e=a(u.errors,!0);if(e)return e}}(this.errorMap,s.operation,o),c="string"==typeof n.error?n.error:void 0,d="number"==typeof n.error_code||"string"==typeof n.error_code?n.error_code:"number"==typeof n.errorCode||"string"==typeof n.errorCode?n.errorCode:"number"==typeof n.code||"string"==typeof n.code?n.code:"string"==typeof n.error?n.error:"number"==typeof i?.code||"string"==typeof i?.code?i.code:void 0,u="string"==typeof n.message?n.message:"string"==typeof n.error_description?n.error_description:"string"==typeof i?.message?i.message:void 0,l=!!(401!==e&&403!==e||void 0!==c&&"unauthorized"!==c&&"auth_failed"!==c&&"forbidden"!==c)&&(void 0!==c||"string"==typeof n.error_description||"string"==typeof n.message);if(s.operation&&a)throw ay({apiName:s.operation,entry:a.entry,serverCode:d,serverMessage:u,httpStatus:e,mapped:!0,reasonKey:a.reasonKey,matchedBy:a.matchedBy});const h=this.buildHttpStatusFallbackError(e,s,d,u);if(h)throw h;if(s.operation&&l)throw ay({apiName:s.operation,serverCode:d,serverMessage:u,httpStatus:e,mapped:!1,reasonKey:c});throw new es(`HTTP ${e}: ${t}`,{code:mr,details:{url:s.url,method:s.method,httpStatus:e}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}}const hy=async(e,t,r)=>{const{orgName:s,appName:n}=Qn(e.appKey),i=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,o=new ly(e.restBaseUrl,{requestAdapter:r,includeRequestId:!0});o.setAuthToken(e.token);try{return((e,t)=>{const r=Date.now(),s=e=>{const s="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:s,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??s!==t,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:r}};if(Bl(e))return Bl(e.data)?s(e.data):s(e);throw new Zr("Invalid contact metadata response",{code:it,details:{payload:e}})})(await o.get(i),t)}catch(a){if(a instanceof Zr)throw a;const e=a instanceof Hr&&a.details?a.details:{};throw new es("Contact metadata request failed",{code:wr,details:{stage:"metadata",cause:a instanceof Error?a.message:String(a),httpStatus:"number"==typeof e.httpStatus?e.httpStatus:void 0,sourceCode:a instanceof Hr?a.code:void 0}})}};var py,fy,gy;(fy=py||(py={})).assertEqual=e=>{},fy.assertIs=function(e){},fy.assertNever=function(e){throw new Error},fy.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},fy.getValidEnumValues=e=>{const t=fy.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return fy.objectValues(r)},fy.objectValues=e=>fy.objectKeys(e).map(function(t){return e[t]}),fy.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},fy.find=(e,t)=>{for(const r of e)if(t(r))return r},fy.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,fy.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},fy.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(gy||(gy={})).mergeShapes=(e,t)=>({...e,...t});const yy=py.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vy=e=>{switch(typeof e){case"undefined":return yy.undefined;case"string":return yy.string;case"number":return Number.isNaN(e)?yy.nan:yy.number;case"boolean":return yy.boolean;case"function":return yy.function;case"bigint":return yy.bigint;case"symbol":return yy.symbol;case"object":return Array.isArray(e)?yy.array:null===e?yy.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?yy.promise:"undefined"!=typeof Map&&e instanceof Map?yy.map:"undefined"!=typeof Set&&e instanceof Set?yy.set:"undefined"!=typeof Date&&e instanceof Date?yy.date:yy.object;default:return yy.unknown}},by=py.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Iy extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof Iy))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,py.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Iy.create=e=>new Iy(e);const wy=(e,t)=>{let r;switch(e.code){case by.invalid_type:r=e.received===yy.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case by.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,py.jsonStringifyReplacer)}`;break;case by.unrecognized_keys:r=`Unrecognized key(s) in object: ${py.joinValues(e.keys,", ")}`;break;case by.invalid_union:r="Invalid input";break;case by.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${py.joinValues(e.options)}`;break;case by.invalid_enum_value:r=`Invalid enum value. Expected ${py.joinValues(e.options)}, received '${e.received}'`;break;case by.invalid_arguments:r="Invalid function arguments";break;case by.invalid_return_type:r="Invalid function return type";break;case by.invalid_date:r="Invalid date";break;case by.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:py.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case by.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case by.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case by.custom:r="Invalid input";break;case by.invalid_intersection_types:r="Intersection results could not be merged";break;case by.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case by.not_finite:r="Number must be finite";break;default:r=t.defaultError,py.assertNever(e)}return{message:r}};let Cy=wy;function Sy(e,t){const r=Cy,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],o={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let a="";const c=s.filter(e=>!!e).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...n,path:i,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===wy?void 0:wy].filter(e=>!!e)});e.common.issues.push(s)}class Ty{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return _y;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const e=await s.key,t=await s.value;r.push({key:e,value:t})}return Ty.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return _y;if("aborted"===n.status)return _y;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const _y=Object.freeze({status:"aborted"}),Ry=e=>({status:"dirty",value:e}),Ay=e=>({status:"valid",value:e}),My=e=>"aborted"===e.status,Ey=e=>"dirty"===e.status,Uy=e=>"valid"===e.status,Ny=e=>"undefined"!=typeof Promise&&e instanceof Promise;var ky,Oy;(Oy=ky||(ky={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},Oy.toString=e=>"string"==typeof e?e:e?.message;class xy{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ly=(e,t)=>{if(Uy(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Iy(e.common.issues);return this._error=t,this._error}}};function Py(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class Dy{get description(){return this._def.description}_getType(e){return vy(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:vy(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ty,ctx:{common:e.parent.common,data:e.data,parsedType:vy(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ny(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vy(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ly(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vy(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Uy(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Uy(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vy(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(Ny(s)?s:Promise.resolve(s));return Ly(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:by.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new Pv({schema:this,typeName:Vv.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Dv.create(this,this._def)}nullable(){return qv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Iv.create(this)}promise(){return Lv.create(this,this._def)}or(e){return Sv.create([this,e],this._def)}and(e){return _v.create(this,e,this._def)}transform(e){return new Pv({...Py(this._def),schema:this,typeName:Vv.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Bv({...Py(this._def),innerType:this,defaultValue:t,typeName:Vv.ZodDefault})}brand(){return new Gv({typeName:Vv.ZodBranded,type:this,...Py(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new $v({...Py(this._def),innerType:this,catchValue:t,typeName:Vv.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return jv.create(this,e)}readonly(){return zv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const qy=/^c[^\s-]{8,}$/i,By=/^[0-9a-z]+$/,$y=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fy=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Gy=/^[a-z0-9_-]{21}$/i,jy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zy=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ky=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Hy;const Vy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Jy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Zy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Qy=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Xy="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ev=new RegExp(`^${Xy}$`);function tv(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function rv(e){return new RegExp(`^${tv(e)}$`)}function sv(e){let t=`${Xy}T${tv(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function nv(e,t){return!("v4"!==t&&t||!Vy.test(e))||!("v6"!==t&&t||!Jy.test(e))}function iv(e,t){if(!jy.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function ov(e,t){return!("v4"!==t&&t||!Wy.test(e))||!("v6"!==t&&t||!Zy.test(e))}class av extends Dy{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==yy.string){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.string,received:t.parsedType}),_y}const t=new Ty;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,i=e.data.length<s.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?Sy(r,{code:by.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&Sy(r,{code:by.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)Ky.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"email",code:by.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)Hy||(Hy=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Hy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"emoji",code:by.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)Fy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"uuid",code:by.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)Gy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"nanoid",code:by.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)qy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"cuid",code:by.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)By.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"cuid2",code:by.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)$y.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"ulid",code:by.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Sy(r,{validation:"url",code:by.invalid_string,message:s.message}),t.dirty()}else if("regex"===s.kind){s.regex.lastIndex=0;s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"regex",code:by.invalid_string,message:s.message}),t.dirty())}else if("trim"===s.kind)e.data=e.data.trim();else if("includes"===s.kind)e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty());else if("toLowerCase"===s.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===s.kind)e.data=e.data.toUpperCase();else if("startsWith"===s.kind)e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty());else if("endsWith"===s.kind)e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){sv(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){ev.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){rv(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?zy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"duration",code:by.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?nv(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"ip",code:by.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?iv(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"jwt",code:by.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?ov(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"cidr",code:by.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Qy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"base64",code:by.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Yy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"base64url",code:by.invalid_string,message:s.message}),t.dirty()):py.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:by.invalid_string,...ky.errToObj(r)})}_addCheck(e){return new av({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ky.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ky.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ky.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ky.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ky.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ky.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ky.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ky.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ky.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ky.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ky.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ky.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ky.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ky.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...ky.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ky.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ky.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ky.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ky.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ky.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ky.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ky.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ky.errToObj(t)})}nonempty(e){return this.min(1,ky.errToObj(e))}trim(){return new av({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new av({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new av({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function cv(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}av.create=e=>new av({checks:[],typeName:Vv.ZodString,coerce:e?.coerce??!1,...Py(e)});class dv extends Dy{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==yy.number){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.number,received:t.parsedType}),_y}let t;const r=new Ty;for(const s of this._def.checks)if("int"===s.kind)py.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==cv(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.not_finite,message:s.message}),r.dirty()):py.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ky.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ky.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ky.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ky.toString(t))}setLimit(e,t,r,s){return new dv({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ky.toString(s)}]})}_addCheck(e){return new dv({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ky.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ky.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ky.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ky.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ky.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ky.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ky.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ky.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ky.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&py.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}dv.create=e=>new dv({checks:[],typeName:Vv.ZodNumber,coerce:e?.coerce||!1,...Py(e)});class uv extends Dy{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==yy.bigint)return this._getInvalidInput(e);let t;const r=new Ty;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):py.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.bigint,received:t.parsedType}),_y}gte(e,t){return this.setLimit("min",e,!0,ky.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ky.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ky.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ky.toString(t))}setLimit(e,t,r,s){return new uv({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ky.toString(s)}]})}_addCheck(e){return new uv({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ky.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ky.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ky.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ky.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ky.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}uv.create=e=>new uv({checks:[],typeName:Vv.ZodBigInt,coerce:e?.coerce??!1,...Py(e)});class lv extends Dy{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==yy.boolean){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.boolean,received:t.parsedType}),_y}return Ay(e.data)}}lv.create=e=>new lv({typeName:Vv.ZodBoolean,coerce:e?.coerce||!1,...Py(e)});class hv extends Dy{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==yy.date){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.date,received:t.parsedType}),_y}if(Number.isNaN(e.data.getTime())){return Sy(this._getOrReturnCtx(e),{code:by.invalid_date}),_y}const t=new Ty;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):py.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new hv({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ky.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ky.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}hv.create=e=>new hv({checks:[],coerce:e?.coerce||!1,typeName:Vv.ZodDate,...Py(e)});class pv extends Dy{_parse(e){if(this._getType(e)!==yy.symbol){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.symbol,received:t.parsedType}),_y}return Ay(e.data)}}pv.create=e=>new pv({typeName:Vv.ZodSymbol,...Py(e)});class mv extends Dy{_parse(e){if(this._getType(e)!==yy.undefined){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.undefined,received:t.parsedType}),_y}return Ay(e.data)}}mv.create=e=>new mv({typeName:Vv.ZodUndefined,...Py(e)});class fv extends Dy{_parse(e){if(this._getType(e)!==yy.null){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.null,received:t.parsedType}),_y}return Ay(e.data)}}fv.create=e=>new fv({typeName:Vv.ZodNull,...Py(e)});class gv extends Dy{constructor(){super(...arguments),this._any=!0}_parse(e){return Ay(e.data)}}gv.create=e=>new gv({typeName:Vv.ZodAny,...Py(e)});class yv extends Dy{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ay(e.data)}}yv.create=e=>new yv({typeName:Vv.ZodUnknown,...Py(e)});class vv extends Dy{_parse(e){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.never,received:t.parsedType}),_y}}vv.create=e=>new vv({typeName:Vv.ZodNever,...Py(e)});class bv extends Dy{_parse(e){if(this._getType(e)!==yy.undefined){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.void,received:t.parsedType}),_y}return Ay(e.data)}}bv.create=e=>new bv({typeName:Vv.ZodVoid,...Py(e)});class Iv extends Dy{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==yy.array)return Sy(t,{code:by.invalid_type,expected:yy.array,received:t.parsedType}),_y;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(Sy(t,{code:e?by.too_big:by.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(Sy(t,{code:by.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(Sy(t,{code:by.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new xy(t,e,t.path,r)))).then(e=>Ty.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new xy(t,e,t.path,r)));return Ty.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Iv({...this._def,minLength:{value:e,message:ky.toString(t)}})}max(e,t){return new Iv({...this._def,maxLength:{value:e,message:ky.toString(t)}})}length(e,t){return new Iv({...this._def,exactLength:{value:e,message:ky.toString(t)}})}nonempty(e){return this.min(1,e)}}function wv(e){if(e instanceof Cv){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Dv.create(wv(s))}return new Cv({...e._def,shape:()=>t})}return e instanceof Iv?new Iv({...e._def,type:wv(e.element)}):e instanceof Dv?Dv.create(wv(e.unwrap())):e instanceof qv?qv.create(wv(e.unwrap())):e instanceof Rv?Rv.create(e.items.map(e=>wv(e))):e}Iv.create=(e,t)=>new Iv({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Vv.ZodArray,...Py(t)});class Cv extends Dy{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=py.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==yy.object){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.object,received:t.parsedType}),_y}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof vv&&"strip"===this._def.unknownKeys))for(const a in r.data)n.includes(a)||i.push(a);const o=[];for(const a of n){const e=s[a],t=r.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new xy(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof vv){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)o.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(Sy(r,{code:by.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new xy(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>Ty.mergeObjectSync(t,e)):Ty.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return ky.errToObj,new Cv({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:ky.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Cv({...this._def,unknownKeys:"strip"})}passthrough(){return new Cv({...this._def,unknownKeys:"passthrough"})}extend(e){return new Cv({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Cv({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Vv.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Cv({...this._def,catchall:e})}pick(e){const t={};for(const r of py.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Cv({...this._def,shape:()=>t})}omit(e){const t={};for(const r of py.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Cv({...this._def,shape:()=>t})}deepPartial(){return wv(this)}partial(e){const t={};for(const r of py.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new Cv({...this._def,shape:()=>t})}required(e){const t={};for(const r of py.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Dv;)e=e._def.innerType;t[r]=e}return new Cv({...this._def,shape:()=>t})}keyof(){return kv(py.objectKeys(this.shape))}}Cv.create=(e,t)=>new Cv({shape:()=>e,unknownKeys:"strip",catchall:vv.create(),typeName:Vv.ZodObject,...Py(t)}),Cv.strictCreate=(e,t)=>new Cv({shape:()=>e,unknownKeys:"strict",catchall:vv.create(),typeName:Vv.ZodObject,...Py(t)}),Cv.lazycreate=(e,t)=>new Cv({shape:e,unknownKeys:"strip",catchall:vv.create(),typeName:Vv.ZodObject,...Py(t)});class Sv extends Dy{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const r=e.map(e=>new Iy(e.ctx.common.issues));return Sy(t,{code:by.invalid_union,unionErrors:r}),_y});{let e;const s=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new Iy(e));return Sy(t,{code:by.invalid_union,unionErrors:n}),_y}}get options(){return this._def.options}}function Tv(e,t){const r=vy(e),s=vy(t);if(e===t)return{valid:!0,data:e};if(r===yy.object&&s===yy.object){const r=py.objectKeys(t),s=py.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const i of s){const r=Tv(e[i],t[i]);if(!r.valid)return{valid:!1};n[i]=r.data}return{valid:!0,data:n}}if(r===yy.array&&s===yy.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=Tv(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===yy.date&&s===yy.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Sv.create=(e,t)=>new Sv({options:e,typeName:Vv.ZodUnion,...Py(t)});class _v extends Dy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(My(e)||My(s))return _y;const n=Tv(e.value,s.value);return n.valid?((Ey(e)||Ey(s))&&t.dirty(),{status:t.value,value:n.data}):(Sy(r,{code:by.invalid_intersection_types}),_y)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}_v.create=(e,t,r)=>new _v({left:e,right:t,typeName:Vv.ZodIntersection,...Py(r)});class Rv extends Dy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==yy.array)return Sy(r,{code:by.invalid_type,expected:yy.array,received:r.parsedType}),_y;if(r.data.length<this._def.items.length)return Sy(r,{code:by.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_y;!this._def.rest&&r.data.length>this._def.items.length&&(Sy(r,{code:by.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new xy(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>Ty.mergeArray(t,e)):Ty.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Rv({...this._def,rest:e})}}Rv.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rv({items:e,typeName:Vv.ZodTuple,rest:null,...Py(t)})};class Av extends Dy{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==yy.object)return Sy(r,{code:by.invalid_type,expected:yy.object,received:r.parsedType}),_y;const s=[],n=this._def.keyType,i=this._def.valueType;for(const o in r.data)s.push({key:n._parse(new xy(r,o,r.path,o)),value:i._parse(new xy(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Ty.mergeObjectAsync(t,s):Ty.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new Av(t instanceof Dy?{keyType:e,valueType:t,typeName:Vv.ZodRecord,...Py(r)}:{keyType:av.create(),valueType:e,typeName:Vv.ZodRecord,...Py(t)})}}class Mv extends Dy{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==yy.map)return Sy(r,{code:by.invalid_type,expected:yy.map,received:r.parsedType}),_y;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new xy(r,e,r.path,[i,"key"])),value:n._parse(new xy(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return _y;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return _y;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}Mv.create=(e,t,r)=>new Mv({valueType:t,keyType:e,typeName:Vv.ZodMap,...Py(r)});class Ev extends Dy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==yy.set)return Sy(r,{code:by.invalid_type,expected:yy.set,received:r.parsedType}),_y;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(Sy(r,{code:by.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(Sy(r,{code:by.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return _y;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>n._parse(new xy(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new Ev({...this._def,minSize:{value:e,message:ky.toString(t)}})}max(e,t){return new Ev({...this._def,maxSize:{value:e,message:ky.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ev.create=(e,t)=>new Ev({valueType:e,minSize:null,maxSize:null,typeName:Vv.ZodSet,...Py(t)});class Uv extends Dy{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Uv.create=(e,t)=>new Uv({getter:e,typeName:Vv.ZodLazy,...Py(t)});class Nv extends Dy{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Sy(t,{received:t.data,code:by.invalid_literal,expected:this._def.value}),_y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function kv(e,t){return new Ov({values:e,typeName:Vv.ZodEnum,...Py(t)})}Nv.create=(e,t)=>new Nv({value:e,typeName:Vv.ZodLiteral,...Py(t)});class Ov extends Dy{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return Sy(t,{expected:py.joinValues(r),received:t.parsedType,code:by.invalid_type}),_y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return Sy(t,{received:t.data,code:by.invalid_enum_value,options:r}),_y}return Ay(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ov.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ov.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ov.create=kv;class xv extends Dy{_parse(e){const t=py.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==yy.string&&r.parsedType!==yy.number){const e=py.objectValues(t);return Sy(r,{expected:py.joinValues(e),received:r.parsedType,code:by.invalid_type}),_y}if(this._cache||(this._cache=new Set(py.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=py.objectValues(t);return Sy(r,{received:r.data,code:by.invalid_enum_value,options:e}),_y}return Ay(e.data)}get enum(){return this._def.values}}xv.create=(e,t)=>new xv({values:e,typeName:Vv.ZodNativeEnum,...Py(t)});class Lv extends Dy{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==yy.promise&&!1===t.common.async)return Sy(t,{code:by.invalid_type,expected:yy.promise,received:t.parsedType}),_y;const r=t.parsedType===yy.promise?t.data:Promise.resolve(t.data);return Ay(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Lv.create=(e,t)=>new Lv({type:e,typeName:Vv.ZodPromise,...Py(t)});class Pv extends Dy{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Vv.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{Sy(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(r.data,n);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return _y;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?_y:"dirty"===s.status||"dirty"===t.value?Ry(s.value):s});{if("aborted"===t.value)return _y;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?_y:"dirty"===s.status||"dirty"===t.value?Ry(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?_y:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?_y:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Uy(e))return _y;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>Uy(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):_y)}py.assertNever(s)}}Pv.create=(e,t,r)=>new Pv({schema:e,typeName:Vv.ZodEffects,effect:t,...Py(r)}),Pv.createWithPreprocess=(e,t,r)=>new Pv({schema:t,effect:{type:"preprocess",transform:e},typeName:Vv.ZodEffects,...Py(r)});class Dv extends Dy{_parse(e){return this._getType(e)===yy.undefined?Ay(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Dv.create=(e,t)=>new Dv({innerType:e,typeName:Vv.ZodOptional,...Py(t)});class qv extends Dy{_parse(e){return this._getType(e)===yy.null?Ay(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qv.create=(e,t)=>new qv({innerType:e,typeName:Vv.ZodNullable,...Py(t)});class Bv extends Dy{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===yy.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Bv.create=(e,t)=>new Bv({innerType:e,typeName:Vv.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Py(t)});class $v extends Dy{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ny(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Iy(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Iy(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}$v.create=(e,t)=>new $v({innerType:e,typeName:Vv.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Py(t)});class Fv extends Dy{_parse(e){if(this._getType(e)!==yy.nan){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.nan,received:t.parsedType}),_y}return{status:"valid",value:e.data}}}Fv.create=e=>new Fv({typeName:Vv.ZodNaN,...Py(e)});class Gv extends Dy{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class jv extends Dy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?_y:"dirty"===e.status?(t.dirty(),Ry(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?_y:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new jv({in:e,out:t,typeName:Vv.ZodPipeline})}}class zv extends Dy{_parse(e){const t=this._def.innerType._parse(e),r=e=>(Uy(e)&&(e.value=Object.freeze(e.value)),e);return Ny(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Kv(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Hv(e,t={},r){return e?gv.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Kv(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Kv(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):gv.create()}var Vv,Wv;zv.create=(e,t)=>new zv({innerType:e,typeName:Vv.ZodReadonly,...Py(t)}),(Wv=Vv||(Vv={})).ZodString="ZodString",Wv.ZodNumber="ZodNumber",Wv.ZodNaN="ZodNaN",Wv.ZodBigInt="ZodBigInt",Wv.ZodBoolean="ZodBoolean",Wv.ZodDate="ZodDate",Wv.ZodSymbol="ZodSymbol",Wv.ZodUndefined="ZodUndefined",Wv.ZodNull="ZodNull",Wv.ZodAny="ZodAny",Wv.ZodUnknown="ZodUnknown",Wv.ZodNever="ZodNever",Wv.ZodVoid="ZodVoid",Wv.ZodArray="ZodArray",Wv.ZodObject="ZodObject",Wv.ZodUnion="ZodUnion",Wv.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Wv.ZodIntersection="ZodIntersection",Wv.ZodTuple="ZodTuple",Wv.ZodRecord="ZodRecord",Wv.ZodMap="ZodMap",Wv.ZodSet="ZodSet",Wv.ZodFunction="ZodFunction",Wv.ZodLazy="ZodLazy",Wv.ZodLiteral="ZodLiteral",Wv.ZodEnum="ZodEnum",Wv.ZodEffects="ZodEffects",Wv.ZodNativeEnum="ZodNativeEnum",Wv.ZodOptional="ZodOptional",Wv.ZodNullable="ZodNullable",Wv.ZodDefault="ZodDefault",Wv.ZodCatch="ZodCatch",Wv.ZodPromise="ZodPromise",Wv.ZodBranded="ZodBranded",Wv.ZodPipeline="ZodPipeline",Wv.ZodReadonly="ZodReadonly";const Jv=av.create,Zv=dv.create,Qv=lv.create;gv.create;const Yv=yv.create,Xv=vv.create,eb=Iv.create,tb=Cv.create,rb=Sv.create;_v.create,Rv.create;const sb=Av.create,nb=Ov.create;Lv.create,Dv.create,qv.create;class ib{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof Iy){const e=r.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),t=`Validation failed: ${e.map(e=>`${e.path}: ${e.message}`).join("; ")}`,s=r.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received);return{success:!1,error:new Zr(t,{code:s?nt:it,details:{fields:e}})}}return{success:!1,error:new Zr("Unknown validation error",{code:ot,details:{fields:[]}})}}}static validateOrThrow(e,t){const r=this.validate(e,t);if(r.success&&void 0!==r.data)return r.data;if(r.error)throw r.error;throw new Zr("Unknown validation error",{code:ot,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const ob=e=>Jv().regex(/^https?:\/\/\S+$/i,e),ab=e=>Jv().regex(/^wss?:\/\/\S+$/i,e),cb=tb({appKey:Jv().min(1,"appKey is required").optional(),appId:Jv().min(1,"appId is required").optional(),enableUserInfoSync:Qv().optional(),enableSyncData:eb(nb(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Qv().optional(),deleteConversationOnGroupDestroyed:Qv().optional(),syncConversationListConfig:tb({includeEmpty:Qv().optional()}).strict().optional(),useCustomAttachmentUpload:Qv().optional(),useFixedDeviceId:Qv().optional(),deviceId:Jv().min(1,"deviceId is required").optional(),serviceConfig:tb({dnsConfigUrls:eb(ob("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:tb({restApiUrl:ob("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:ab("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:ob("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:ab("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:Qv().optional(),customDeviceName:Jv().min(1,"customDeviceName is required").optional(),customOSPlatform:Zv().int("customOSPlatform must be an integer").min(1,"customOSPlatform must be between 1 and 100").max(100,"customOSPlatform must be between 1 and 100").optional(),uiKitVersion:Jv().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Jv().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:eb(Yv()).optional(),platformAdapterOptions:tb({prefer:nb(["web","wechat-miniapp","qq-miniapp","toutiao-miniapp","baidu-miniapp","alipay-miniapp","dingtalk-miniapp","lark-miniapp","kuaishou-miniapp","jd-miniapp","360-miniapp","harmony-miniapp","quickapp","uniapp","react-native","electron-renderer","electron-main","unknown"]).optional(),runtimeInput:Hv(e=>"object"==typeof e&&null!==e).optional(),overrides:Hv(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{const r=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===r?t.addIssue({code:by.custom,path:["appKey"],message:"appKey or appId is required"}):r>1&&t.addIssue({code:by.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:by.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:by.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:by.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:by.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:by.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:by.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:by.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&n&&t.addIssue({code:by.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:by.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:by.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:by.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),db=tb({userId:Jv().min(1,"userId is required"),token:Jv().min(1,"token is required")}),ub=Jv().trim().min(1,"token is required"),lb=tb({channelName:Jv().trim().min(1,"channelName is required").optional()}).optional(),hb=eb(Zv({invalid_type_error:"rtcUid must be a number"}).int("rtcUid must be an integer").min(0,"rtcUid must be greater than or equal to 0").max(Number.MAX_SAFE_INTEGER,"rtcUid must be a safe integer")).nonempty("rtcUids is required").transform(e=>Array.from(new Set(e))),pb=tb({protocol:Jv(),domain:Jv().optional(),ip:Jv().optional(),port:rb([Jv(),Zv()]).optional()}).passthrough(),mb=tb({app_key:Jv().optional(),rest:tb({hosts:eb(pb).nonempty()}),"msync-wx":tb({hosts:eb(pb).nonempty()}),"sync-ws":tb({hosts:eb(pb).nonempty()}).optional(),enableReportLogs:nb(["true","false"]).optional(),reportInterval:Zv().positive().finite().optional(),enableDataReport:nb(["true","false"]).optional(),enableMd5Check:nb(["true","false"]).optional(),uploadinparts_enable:nb(["true","false"]).optional()}).passthrough(),fb=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),gb=e=>"function"==typeof URLSearchParams?new URLSearchParams(e):(e=>{const t=new Map;if(e)for(const[r,s]of Object.entries(e))t.set(r,s);return{set(e,r){t.set(e,r)},toString:()=>Array.from(t,([e,t])=>`${fb(e)}=${fb(t)}`).join("&")}})(e),yb="5.1.0",vb=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],bb=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],Ib=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function wb(e){return"object"==typeof e&&null!==e}function Cb(e){return Array.isArray(e)?{hosts:e}:function(e){return wb(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Sb(e,t,r){for(const s of t){const t=Cb(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=Cb(n);if(e)return{key:s,section:e}}}function Tb(e){if(!wb(e))return ib.validateOrThrow(mb,e);const t=Cb(e.rest),r=Sb(e,bb,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s=Sb(e,Ib,e=>{const t=e.toLowerCase();return!t.includes("msync")&&t.includes("sync")&&(t.includes("ws")||t.includes("socket"))}),n={...e,rest:t??e.rest,"msync-wx":r?.section};s?.section?n["sync-ws"]=s.section:"sync-ws"in n&&!Cb(n["sync-ws"])&&delete n["sync-ws"];const i="true"===(o=e.enableReportLogs)||!0===o?"true":"false"===o||!1===o?"false":void 0;var o;i&&(n.enableReportLogs=i);const a=function(e){if("number"!=typeof e&&"string"!=typeof e)return;if("string"==typeof e&&""===e.trim())return;const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}(e.reportInterval);void 0!==a?n.reportInterval=a:delete n.reportInterval;const c=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);c?n.enableDataReport=c:delete n.enableDataReport;const d=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);d?n.enableMd5Check=d:delete n.enableMd5Check;const u=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return u?n.uploadinparts_enable=u:delete n.uploadinparts_enable,r&&"msync-wx"!==r.key&&Si("DNS config websocket section normalized",{sourceKey:r.key}),s&&"sync-ws"!==s.key&&Si("DNS config sync websocket section normalized",{sourceKey:s.key}),ib.validateOrThrow(mb,n)}function _b(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS host missing domain/ip",{code:nt,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${"https"===t?"wss":"ws"}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}/websocket`}function Rb(e,t){return"https"===e?"https":"http"===e?"http":t}function Ab(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS rest host missing domain/ip",{code:nt,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${t}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}`}function Mb(e,t){const r=e.filter(e=>e.protocol===t);return r.length>0?r:"http"===t?e.filter(e=>"https"===e.protocol):[]}function Eb(e){const t=function(e){return e.filter(e=>Boolean(e.domain))}(e);return t.length>0?t:e.filter(e=>Boolean(e.domain||e.ip))}async function Ub(e,t,r){const s=new ly(e,{requestAdapter:r,includeRequestId:!0});let n="/easemob/server.json",i=!0;try{const t=new URL(e),r=""!==t.pathname&&"/"!==t.pathname,s=""!==t.search;(r||s)&&(n="",i=!1)}catch{n="/easemob/server.json",i=!0}if(i){n=`${n}?${(void 0!==t.appId?gb({app_id:t.appId,sdk_version:yb,file_version:"1"}):gb({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return Tb(await s.get(n))}function Nb(e,t){const r=e["sync-ws"];return r&&Array.isArray(r.hosts)?r.hosts.map(e=>function(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS host missing domain/ip",{code:nt,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${"https"===t?"wss":"ws"}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}`}(e,Rb(e.protocol,t))).filter(e=>"string"==typeof e&&e.length>0):[]}async function kb(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:vb;if(0===t.length)throw new Zr("DNS_CONFIG list is empty",{code:nt,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const r=e.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let s;for(const o of t)try{const t=void 0!==e.appId?{appId:e.appId}:{appKey:e.appKey},s=await Ub(o,t,e.requestAdapter),n=void 0!==e.appId?s.app_key:e.appKey;if("string"!=typeof n||0===n.length)throw new Zr("DNS app_key is required for appId initialization",{code:nt,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const i=Eb(Mb(s["msync-wx"].hosts,r));if(0===i.length)throw new Zr("DNS msync-wx hosts resolution failed",{code:it,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const a=i[0];if(!a)throw new Zr("DNS msync-wx hosts resolution failed",{code:it,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const c=Mb(s.rest.hosts,r);if(0===c.length)throw new Zr("DNS rest hosts resolution failed",{code:it,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const d=c[0];if(!d)throw new Zr("DNS rest hosts resolution failed",{code:it,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const u=i.map(e=>_b(e,Rb(e.protocol,r))),l=_b(a,Rb(a.protocol,r)),h=Nb(s,r);return{appKey:n,websocketUrl:l,websocketUrls:u,syncWebsocketUrls:h,baseUrl:o,restBaseUrl:Ab(d,Rb(d.protocol,r)),dnsConfig:s}}catch(i){Si("DNS config candidate failed",{baseUrl:o,reason:i instanceof Error?i.message:String(i),error:i instanceof Error&&"function"==typeof i.toJSON?i.toJSON():i}),s=i}const n={stage:"dns"};throw s&&(n.reason=s.message,"code"in s&&"number"==typeof s.code&&(n.causeCode=s.code)),new Wr("DNS_CONFIG exhausted",{code:wt,details:n})}const Ob=e=>new Zr(e,{code:it,details:{reason:"invalid_rest_response"}}),xb=e=>{if(!Bl(e))throw Ob("Invalid REST response");return Bl(e.data)?e.data:e},Lb=(e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&t.trim().length>0){const e=Number(t);if(Number.isFinite(e))return e}}},Pb=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},Db=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},qb=async(e,t)=>{const r=await e.get((e=>`${Db(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=xb(e),r=Lb(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw Ob("Invalid token expires response");return r})(r)},Bb=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=gb({channelName:t?.channelName??"*"});return`${Db(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=xb(e);return{appId:Pb(t,["app_id","appId"])??"",rtcToken:Pb(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:Pb(t,["channel_name","channelName"])??"",rtcUid:Lb(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:Lb(t,["expires_in","expire","expireAt"])??0}})(s)},$b=async(e,t,r)=>{const s=await e.post((e=>`${Db(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=xb(e),r={};for(const[s,n]of Object.entries(t)){const e=Number(s);!Number.isSafeInteger(e)||e<0||"string"!=typeof n||(r[e]=n)}return r})(s)},Fb=async(e,t)=>{const r=await e.get((e=>`${Db(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=Bl(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!Bl(n))continue;const e=Pb(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},Gb=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},jb={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},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:{}},zb=e=>({userId:e}),Kb=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Hb=e=>e,Vb=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Kb(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,Hb(t))}for(const o of r)s.has(o)||s.set(o,zb(o));return s};class Wb{constructor(e){this.options=e,this.pendingGroups=new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,r){if(!e||!t)return;const s=this.pendingGroups.get(e)??new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,s),this.pendingOrder.push(e));const n=s.get(t);s.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(n?.namecardUpdateTime,r)}),this.schedule()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingGroups.clear(),this.pendingOrder.length=0,this.readyGroups.length=0,this.activeGroups.clear(),this.activeGroupCount=0}getOptions(){return{windowMs:this.options.windowMs,minWindowMs:this.options.minWindowMs,maxBatchSize:this.options.maxBatchSize,maxConcurrency:this.options.maxConcurrency}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushWindow()},this.resolveWindowDelay()))}flushWindow(){if(0!==this.pendingOrder.length){for(const e of this.pendingOrder){const t=this.pendingGroups.get(e);if(!t||0===t.size)continue;const r=Array.from(t.values()),s=Math.max(1,this.options.maxBatchSize);for(let n=0;n<r.length;n+=s)this.readyGroups.push({groupId:e,targets:r.slice(n,n+s)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const e=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(e<0)return;const t=this.readyGroups.splice(e,1)[0];if(!t)return;this.activeGroupCount+=1,this.activeGroups.add(t.groupId),Promise.resolve(this.options.onFlushGroup(t)).catch(e=>{Si("Group namecard hydration queue flush failed",{groupId:t.groupId,userIds:t.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(t.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),r=t-e;return r<=0?t:e+Math.floor(Math.random()*(r+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class Jb{constructor(e){this.options=e,this.pendingTargets=new Map,this.readyBatches=[],this.timer=null,this.activeCount=0,this.generation=0}enqueue(e,t){e&&(this.mergeWaitingTarget({userId:e,userInfoUpdateTime:t,retryCount:0}),this.pendingTargets.size>=this.options.batchSize?this.flush():this.schedule())}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTargets.clear(),this.readyBatches.length=0,this.generation+=1}getOptions(){return{windowMs:this.options.windowMs,batchSize:this.options.batchSize,maxConcurrency:this.options.maxConcurrency,maxRetries:this.options.maxRetries}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.windowMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),0===this.pendingTargets.size)return;const e=Array.from(this.pendingTargets.values());this.pendingTargets.clear();const t=Math.max(1,this.options.batchSize);for(let r=0;r<e.length;r+=t)this.readyBatches.push(e.slice(r,r+t));this.runReadyBatches()}runReadyBatches(){const e=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<e&&this.readyBatches.length>0;){const e=this.readyBatches.shift();if(!e)return;const r=this.generation;this.activeCount+=1;const s=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let n;try{n=Promise.resolve(this.options.onFlush(s))}catch(t){n=Promise.reject(t instanceof Error?t:new Error(String(t)))}n.catch(t=>{const s=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(Si("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:s.length>0,error:t instanceof Error?t.message:String(t)}),r===this.generation&&0!==s.length){for(const e of s)this.mergeWaitingTarget(e);this.flush()}}).finally(()=>{this.activeCount-=1,this.runReadyBatches()})}}mergeWaitingTarget(e){for(const r of this.readyBatches){const t=r.findIndex(t=>t.userId===e.userId);if(t>=0){const s=r[t];return void(s&&(r[t]=this.mergeTarget(s,e)))}}const t=this.pendingTargets.get(e.userId);this.pendingTargets.set(e.userId,t?this.mergeTarget(t,e):e)}mergeTarget(e,t){return{userId:e.userId,userInfoUpdateTime:this.resolveMaxVersion(e.userInfoUpdateTime,t.userInfoUpdateTime),retryCount:Math.max(e.retryCount,t.retryCount)}}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}const Zb=0,Qb=1,Yb=2,Xb=3,eI=4,tI=5,rI=0,sI=0,nI=1,iI=1001,oI=1002,aI=1003,cI=1004,dI=1005,uI=1101,lI=Gb(jb,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),hI=class e{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=t,this.loginAttempt=0,this.currentUserId=null,this.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=new Set,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=ul(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new ng,this.managerEventContext={addEventHandler:(e,t)=>{this.eventHub.addEventHandler(e,t)},removeEventHandler:e=>{this.eventHub.removeEventHandler(e)},dispatch:(e,t)=>{this.eventHub.dispatch(e,t)}},this.userInfoHydrationQueue=new Jb({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Wb({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:1e3,maxBatchSize:50,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[o]:e=>{this.updateState(e.state)},[a]:e=>{this.updateState(e.state)},[c]:e=>{this.updateState(e.state)},[d]:e=>{this.updateState(e.state)},[N]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[k]:e=>{this.handleIncomingConversationStreamMessage(e)},[b]:e=>{this.handleOutgoingConversationMessage(e)},[$]:e=>{this.handleMultiDeviceContactEvent(e)},[F]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[V]:e=>this.handleIncomingContactRosterEvent("add",e),[J]:e=>this.handleIncomingContactRosterEvent("add",e),[K]:e=>this.handleIncomingContactRosterEvent("none",e),[W]:e=>this.handleIncomingContactRosterEvent("none",e),[H]:e=>this.handleIncomingContactRosterEvent("remove",e),[f]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===ne&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[g]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[y]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[v]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(t){const r=ib.validateOrThrow(cb,t),s=r.customOSPlatform,n=e.normalizeServiceConfig(r.serviceConfig),i={appKey:r.appKey,appId:r.appId,enableUserInfoSync:r.enableUserInfoSync??!1,enableSyncData:e.normalizeSyncDataTypes(r.enableSyncData??["conversation"]),enableDeliveryReceipt:r.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:r.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:r.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:r.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:n,useFixedDeviceId:r.useFixedDeviceId??!0,deviceId:r.deviceId??"webim",useReplacedMessageContents:r.useReplacedMessageContents??!1,customDeviceName:void 0!==s?r.customDeviceName:void 0,customOSPlatform:s,uiKitVersion:r.uiKitVersion,loginExtensionInfo:r.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:7e3,userInfoBatchSize:20,groupNamecardWindowMs:7e3,groupNamecardMaxConcurrency:5},platformAdapterOptions:r.platformAdapterOptions},o=t.managers??[];if(e.instance){if(!e.isSameConfig(e.instance.config,i))throw new Zr("ChatClient already initialized with different config",{code:it,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:e.instance.config,next:i}});return o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}return e.instance=new e(i),o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}async login(n){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const i=ib.validateOrThrow(db,n);if(this.state===r||this.state===s){const e=this.currentUserId&&this.currentUserId!==i.userId;throw new Wr(e?"Another user is already logged in":"ChatClient is already connecting or connected",{code:e?Jt:at,details:{stage:"auth",...e?{currentUserId:this.currentUserId,nextUserId:i.userId}:{}}})}const o=++this.loginAttempt;let a=this.config.appKey??null;this.activeAppKey=a,Si("Login started",{userId:i.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const c=this.platformAdapter??ul(this.config.platformAdapterOptions);var d;this.platformAdapter=c,d={requestAdapter:c.request,onDiagnostic:(e,t)=>{Si(e,t)}},em?.reset(),em=new Xp(d);const u=(e=>em?.startSession(e))({appKey:a??"default#appkey",uid:i.userId,sdkVersion:yb,platform:c.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),l=c.runtime.getNetworkType?.();l&&l.then(e=>{sm(e)}).catch(()=>{sm("unknown")});const h=nm({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:i.userId});let p,m,f;this.updateState(r),this.logReportEnabled=!1,vi("unknown");let g,y=!1,v=!1,b=!0;if("dns"===this.config.serviceConfig.mode){const e=h?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await kb(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:c.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:c.request});a=t.appKey,this.activeAppKey=a,tm({appKey:a}),Si("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,syncWsCount:t.syncWebsocketUrls.length,restBaseUrl:t.restBaseUrl}),p=t.websocketUrl,m=t.websocketUrls,this.contactSyncWsUrls=t.syncWebsocketUrls,this.syncConversationListConfigWsUrls=t.syncWebsocketUrls,this.contactSyncDnsResolved=!0,f=t.restBaseUrl,y="true"===t.dnsConfig.enableReportLogs,g=t.dnsConfig.reportInterval,v="true"===t.dnsConfig.enableMd5Check,b="false"!==t.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),rm(t.dnsConfig.enableDataReport),Ci("DNS report switch resolved",{enabled:y})}catch(C){const r=C instanceof Hr?C.code:-1,s=C instanceof Error?C.message:String(C);throw e?.finish({code:r,success:!1,description:s}),h?.finish({code:r,success:!1,description:s}),rm(void 0),vi("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(t),C}}else{const e=this.config.serviceConfig.serverUrls;if(!e?.wsUrl||!e.restApiUrl){const e=new Zr("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:nt,details:{fields:[{path:"serviceConfig.serverUrls.restApiUrl",message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured",rule:"required"},{path:"serviceConfig.serverUrls.wsUrl",message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured",rule:"required"}]}});throw h?.finish({code:e.code,success:!1,description:e.message}),rm(void 0),this.updateState(t),e}p=e.wsUrl,f=e.restApiUrl,v=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=e.syncWsUrl?[e.syncWsUrl]:[],this.contactSyncDnsResolved=!1,rm(void 0)}if(!a){const e=new Zr("appKey is unavailable after service discovery",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(t),im(),e}var I;if(bi({restBaseUrl:f,appKey:a,userId:i.userId,token:i.token,requestAdapter:c.request}),I=g,di.updateReportInterval(I),this.logReportEnabled=y,vi(y?"enabled":"disabled"),this.resetCore(),o!==this.loginAttempt){const e=new Wr("Login cancelled",{code:yt,details:{stage:"auth"}});throw h?.finish({code:yt,success:!1,description:e.message}),this.updateState(t),this.activeAppKey=this.config.appKey??null,im(),e}this.core=new nf({serverUrl:p,serverUrls:m,userId:i.userId,token:i.token,appKey:a,restBaseUrl:f,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:v,enableMultipartUpload:b,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:u,platformAdapter:c,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),bi({resource:this.core.getClientResource()});const w=h?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:p});try{if(Si("Connecting core websocket",{serverUrl:p,restBaseUrl:f,userId:i.userId}),await this.core.connect(),w?.finish({code:200,success:!0}),h?.finish({code:0,success:!0}),Si("Core websocket connected",{userId:i.userId,resource:this.core.getClientResource()}),this.currentUserId=i.userId,tm({uid:i.userId}),this.restBaseUrl=f??null,this.authToken=i.token,this.clientResource=this.core.getClientResource(),await this.initCacheManager(i.userId),Si("Cache initialized after login",{userId:i.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),await this.syncSelfUserInfoAfterLogin(),this.config.enableSyncData.includes("conversation")&&await this.refreshSessionList(this.config.syncConversationListConfig),this.triggerConfiguredSyncDataAfterLogin(i.userId),this.logReportEnabled)try{await Ii()}catch(C){Si("Report logs on login failed",C)}}catch(C){const e=C instanceof Hr?C.code:-1,r=C instanceof Error?C.message:String(C);throw w?.finish({code:e,success:!1,description:r}),h?.finish({code:e,success:!1,description:r}),this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(t),im(),C}}async logout(){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(this.loginAttempt+=1,!this.core)return this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.activeAppKey=this.config.appKey??null,this.resetManagerSessionRuntimes(),this.updateState(t),this.logReportEnabled=!1,vi("disabled"),wi(),void im();try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await Ii()}catch(r){Si("Report logs on logout failed",r)}await this.core.disconnect()}finally{this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,vi("disabled"),wi(),im()}}getConnectionState(){return this.state}getCurrentUserId(){return this.currentUserId}getClientResource(){return this.clientResource??this.core?.getClientResource()??null}getMessageCreationOptions(){return{useCustomAttachmentUpload:this.config.useCustomAttachmentUpload}}getRestContext(){if(!this.restBaseUrl)throw new Zr("restBaseUrl is required",{code:nt,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new Zr("token is required",{code:nt,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new Zr("userId is required",{code:nt,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const e=this.clientResource??this.core?.getClientResource();if(!e)throw new Zr("clientResource is required",{code:nt,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:e}}async renewToken(e){const t=ib.validateOrThrow(ub,e);if(!this.core||!this.currentUserId||this.state!==s)throw new Wr("ChatClient is not connected",{code:ct,details:{stage:"token",state:this.state}});const r=this.getRestContext(),n={...r},i=new ly(n.restBaseUrl,{errorMap:lI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(t),Si("Renew token started",{userId:r.userId});const o=await qb(i,n);if(o<=Date.now())throw new Wr("Token is expired",{code:lt,details:{stage:"token"}});const a=this.core.renewToken(t,o);return this.authToken=t,bi({token:t}),Si("Renew token succeeded",{userId:r.userId,expireAt:o}),a}async getRTCTokenInfo(e){const t=ib.validateOrThrow(lb,e),r=this.getRestContext(),s=new ly(r.restBaseUrl,{errorMap:lI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Si("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),Bb(s,r,t)}async getUserIdsWithRTCUids(e){const t=ib.validateOrThrow(hb,e),r=this.getRestContext(),s=new ly(r.restBaseUrl,{errorMap:lI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Si("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),$b(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new ly(e.restBaseUrl,{errorMap:lI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),Si("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),Fb(t,e)}getCacheManager(){return this.cacheManager}getManagerByCapability(e){return this.managerCapabilities.get(e)}getUploadAdapter(){return this.platformAdapter?.upload??null}getRequestAdapter(){return this.platformAdapter?.request}addInternalEvent(e,t){this.eventHub.dispatch(e,t)}refreshSessionList(e){return this.cacheManager&&this.currentUserId?this.ensureSessionListSyncController().refresh({includeEmpty:e?.includeEmpty??this.config.syncConversationListConfig.includeEmpty,includeMark:!0}).then(e=>(this.enqueueMissingGroupSessionSenderUserInfos(e),e.map(e=>({...e})))):Promise.resolve([])}getServerUrlsConfig(){return this.config.serviceConfig.serverUrls}getSessionListSyncWsUrls(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;return e?this.buildAuthenticatedSessionListSyncUrls([e]):this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new iy({socketAdapter:this.platformAdapter?.socket,getUrls:async()=>{const e=this.getSessionListSyncWsUrls();return e.length>0?e:await this.resolveContactSyncUrls()}})),this.syncWebSocketSession}isSessionListDnsProbeAvailable(){return"dns"===this.config.serviceConfig.mode}getSessionListSyncCapabilityState(){return this.syncConversationListConfigController?.getCapabilityState()??null}markConversationAccess(e){this.cacheManager?.markConversationAccess(e)}handleIncomingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleIncomingConversationStreamMessage(e){if(!this.cacheManager)return;const t=e.msgServerId||e.msgLocalId,r=e.stream.status===rt.START_COMPLETED||e.stream.status===rt.FULL||e.stream.status===rt.COMPLETED||e.stream.status===rt.ERROR;if(!this.activeIncomingStreamMessageIds.has(t))return this.applyIncomingConversationMessagePatch(e),void(r||this.activeIncomingStreamMessageIds.add(t));if(!r)return;this.activeIncomingStreamMessageIds.delete(t);this.cacheManager.loadSessionList().some(e=>e.lastMessage?.msgServerId===t)&&this.applyIncomingConversationMessagePatch(e)}applyIncomingConversationMessagePatch(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleOutgoingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}async handleMultiDeviceConversationEvent(e){if("CONVERSATION_DELETED"!==e.operation||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e.conversationId,type:e.conversationType??"singleChat",deletedAt:e.timestamp??Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}async handleGroupDestroyedConversation(e){if(!this.config.deleteConversationOnGroupDestroyed||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e,type:"groupChat",deletedAt:Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}handleMultiDeviceContactEvent(e){if("CONTACT_REMOVE"!==e.operation||!this.cacheManager)return;this.cacheManager.applyContactRosterNotice({action:"remove",userId:e.targetUserId,rosterVersion:e.rosterVersion}).changed&&this.cacheManager.flushPending()}getContactSnapshot(){return this.cacheManager?this.cacheManager.loadContactSnapshot("cache"):null}handleIncomingContactRosterEvent(e,t){const r=this.resolveContactRosterTargetUserId(t);if(r)return this.cacheManager&&this.currentUserId&&"none"!==e&&this.cacheManager.applyContactRosterNotice({action:e,userId:r,rosterVersion:Sh(t)}),this.hydrateContactRosterPayload(t,r,"remove"!==e)}resolveContactRosterTargetUserId(e){const t=this.currentUserId;return t?e.from===t&&e.to!==t?e.to:e.to===t&&e.from!==t||e.from&&e.from!==t?e.from:e.to&&e.to!==t?e.to:null:null}async hydrateContactRosterPayload(e,t,r){const s=await(async(e,t)=>((e,t,r)=>({userId:r,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 Vb([e],t)).get(e),e))(t,{cacheManager:this.cacheManager,fetchUserInfos:r?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=s}async fetchContactEventUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoReadCapability();if(!t)return[];try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Si("Contact roster event user info fetch failed",{userIds:e,error:r}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const e=this.getUserInfoReadCapability();if(e)try{0===(await e.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&Si("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){Si("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=Ih(e),r=e.sender.userId;if(!r||!this.cacheManager)return;const s=this.cacheManager.getUserInfoSummaries([r],!1)[0];if(s&&(e.sender={userId:r,nickname:s.nickname??e.sender.nickname,avatarUrl:s.avatarUrl??e.sender.avatarUrl}),"number"==typeof t?.userInfoUpdateTime?this.shouldHydrateUserInfo(s?.userInfoUpdateTime,t.userInfoUpdateTime)&&this.userInfoHydrationQueue.enqueue(r,t.userInfoUpdateTime):s||this.userInfoHydrationQueue.enqueue(r),"groupChat"!==e.conversationType)return;const n=this.cacheManager.getGroupNamecard(e.conversationId,r,!1);"number"==typeof t?.namecardUpdateTime?this.shouldHydrateGroupNamecard(n?.namecardUpdateTime,t.namecardUpdateTime)&&this.groupNamecardHydrationQueue.enqueue(e.conversationId,r,t.namecardUpdateTime):n||this.groupNamecardHydrationQueue.enqueue(e.conversationId,r)}attachOutgoingMessageProfileVersions(e){if(!this.isMessageProfileSyncEnabled())return void(e=>{vh.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};bh(e,t)}resolveCurrentUserInfoUpdateTime(){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getUserInfoSummaries([this.currentUserId],!1)[0]?.userInfoUpdateTime}resolveCurrentGroupNamecardUpdateTime(e){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getGroupNamecard(e,this.currentUserId,!1)?.namecardUpdateTime}shouldHydrateUserInfo(e,t){return"number"!=typeof e||e<t}shouldHydrateGroupNamecard(e,t){return"number"!=typeof e||e<t}async flushUserInfoHydrationTargets(e){const t=this.getUserInfoReadCapability();if(!t||0===e.length)return;const r=e.map(e=>e.userId);let s;try{s=await t.getUserInfoByUserId({userIds:r})}catch(d){throw Si("User info hydration failed",{userIds:r,error:d}),d}const n=this.currentUserId,i=n?s.find(e=>e.userId===n):void 0,o=s.filter(e=>e.userId!==n);i&&this.dispatchOwnInfoUpdated(i),o.length>0&&this.dispatchUserInfoUpdated(o),s.length>0&&this.refreshConversationDisplayFromUserInfos(s.map(e=>({userId:e.userId})),"profile");const a=new Set(s.map(e=>e.userId)),c=r.filter(e=>!a.has(e));c.length>0&&Si("User info hydration returned partial result",{requestedUserIds:r,missingUserIds:c})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(r){Si("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:r})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(t),this}async sendMessage(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!t?.sender?.userId)throw new Zr("sender.userId is required",{code:nt,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&t.sender.userId!==this.currentUserId)throw new Zr("sender.userId does not match current user",{code:it,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(st(t))throw new Qr("Stream message send is not supported",{code:ir,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.core||this.state!==s)throw new Qr("ChatClient is not connected",{code:St,details:{msgLocalId:t.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(t),this.core.sendMessage(t,r)}dispatchOwnInfoUpdated(e){this.eventHub.dispatch("onOwnInfoUpdated",e)}dispatchUserInfoUpdated(e){0!==e.length&&this.eventHub.dispatch("onUserInfoUpdated",[...e])}refreshConversationDisplayFromUserInfos(e,t="profile"){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromUserInfos(e).changed&&this.emitConversationListUpdate(t)}refreshConversationDisplayFromJoinedGroups(e,t="profile",r){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromJoinedGroups(e.map(e=>({groupId:e.groupId,name:e.name,avatarUrl:e.avatarUrl,remindType:e.remindType})),r).changed&&this.emitConversationListUpdate(t)}enqueueMissingGroupSessionSenderUserInfos(e){if(!this.isMessageProfileSyncEnabled()||!this.cacheManager||0===e.length)return;const t=new Set;for(const n of e){const e="groupChat"===n.conversationType?n.lastMessage?.sender:null;!e?.userId||e.nickname&&e.avatarUrl||t.add(e.userId)}if(0===t.size)return;const r=this.cacheManager.getUserInfoSummaries([...t],!1),s=new Set(r.map(e=>e.userId));for(const n of t)s.has(n)||this.userInfoHydrationQueue.enqueue(n)}dispatchUserGroupNamecardUpdated(e,t,r){e&&t&&this.eventHub.dispatch(Ce,{groupId:e,userId:t,namecard:r})}async downloadAndParseCombinePayload(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(t)}async sendMessageAction(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.downloadAttachment(t)}decodeServerMessageMeta(e){if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.decodeServerMessageMeta(e)}registerManagers(e){if(0===e.length)return;const t=new Set;for(const r of e){const e=this.resolveManagerKey(r);if(t.has(e))throw this.buildManagerValidationError(`Manager key duplicated: ${e}`,it,"managers.key","conflict",{managerKey:e});t.add(e)}for(const r of e)this.registerManagerInput(r)}registerManagerInput(t){return e.isManagerConstructor(t)?this.registerManagerConstructor(t):this.registerManagerInstance(t)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),r=this.managerRegistry.get(t);if(r){if(r.constructor===e)return r;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const s=new e;return s.bind(this,this.managerEventContext),this.managerRegistry.set(t,s),this.registerManagerCapabilities(s),this.attachManager(t,s),s}registerManagerInstance(e){const t=this.getManagerKeyFromInstance(e),r=this.managerRegistry.get(t);if(r){if(r===e)return e;if(r.constructor===e.constructor)throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"instance-conflict");throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"constructor-mismatch")}return e.bind(this,this.managerEventContext),this.managerRegistry.set(t,e),this.registerManagerCapabilities(e),this.attachManager(t,e),e}registerManagerCapabilities(e){for(const t of e.capabilities??[])this.managerCapabilities.set(t,e)}dispatchRawNotifyToCapability(e,t){const r=this.getManagerByCapability(e);return r?.handleRawNotify?.(t)}getUserInfoReadCapability(){const e=this.getManagerByCapability("userInfo:read");return e&&this.hasUserInfoReadCapability(e)?e:null}getGroupNamecardHydrationCapability(){const e=this.getManagerByCapability("group:namecard");return e&&this.hasGroupNamecardHydrationCapability(e)?e:null}validateOptionalCapabilityDependencies(){if(this.config.enableUserInfoSync&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","userInfo:read",["UserInfoManager"]);if(this.config.enableUserInfoSync&&!this.getGroupNamecardHydrationCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","group:namecard",["GroupManager"]);if(this.config.enableSyncData.includes("contact")&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableSyncData: ['contact']","userInfo:read",["UserInfoManager"]);if(this.config.enableSyncData.includes("group")&&!this.managerRegistry.has("groupManager"))throw this.buildMissingCapabilityError("enableSyncData: ['group']","rawNotify:group",["GroupManager"])}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}hasGroupNamecardHydrationCapability(e){return"function"==typeof e.hydrateMessageProfileGroupNamecards}buildMissingCapabilityError(e,t,r){return new Zr(`${e} requires explicit manager capability: ${t}`,{code:nt,details:{fields:[{path:e,message:`${e} requires explicit manager capability: ${t}`,rule:"dependency"}],capability:t,requiredManagers:r}})}resolveManagerKey(t){if(e.isManagerConstructor(t))return this.getManagerKeyFromConstructor(t);if("object"!=typeof t||null===t)throw this.buildManagerValidationError("Manager must be constructor or instance",it,"managers","type",{receivedType:typeof t});return this.getManagerKeyFromInstance(t)}getManagerKeyFromConstructor(e){const t=e.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",nt,"managers.key","required",{managerType:"constructor",managerName:this.getManagerNameFromConstructor(e)});return t}getManagerKeyFromInstance(e){const t=e.constructor.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",nt,"managers.key","required",{managerType:"instance",managerName:this.getManagerNameFromInstance(e)});return t}attachManager(e,t){Object.prototype.hasOwnProperty.call(this,e)||Object.defineProperty(this,e,{value:t,writable:!1,enumerable:!0})}isValidManagerKey(e){return"string"==typeof e&&e.trim().length>0}getManagerNameFromConstructor(e){return"string"==typeof e.name&&e.name.length>0?e.name:"AnonymousManager"}getManagerNameFromInstance(e){const t=e.constructor;return"string"==typeof t.name&&t.name.length>0?t.name:"AnonymousManager"}buildManagerValidationError(e,t,r,s,n){return new Zr(e,{code:t,details:{fields:[{path:r,message:e,rule:s}],...n}})}buildManagerConflictError(e,t,r,s){return this.buildManagerValidationError("Manager key conflict",it,"managers.key","conflict",{managerKey:e,existingName:t,incomingName:r,reason:s})}static isManagerConstructor(e){return"function"==typeof e}updateState(e){this.state!==e&&(this.state=e)}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new sg({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const r=this.cacheManager.loadSessionList().map(zg),s=this.buildConversationListPatch(this.conversationListSnapshot,r,t);(s.reset||0!==s.upserted.length||0!==s.removed.length||s.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=r,this.eventHub.dispatch(O,{version:this.conversationListVersion,items:r,reason:e,patch:s}))}buildConversationListPatch(e,t,r){const s=new Map(e.map(e=>[this.buildConversationListKey(e),e])),n=new Map(t.map(e=>[this.buildConversationListKey(e),e])),i=new Set,o=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=s.get(e);t&&this.isConversationListItemEqual(t,d)||(o.push(d),i.add(e))}for(const d of e){const e=this.buildConversationListKey(d);n.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),i.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)i.add(this.buildConversationListKey(d));return{reset:r,upserted:o,removed:a,affectedKeys:[...i],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,r)=>e===t.marks[r])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}triggerConfiguredSyncDataAfterLogin(e){this.config.enableSyncData.includes("contact")&&(Si("Triggering automatic contact sync after login",{userId:e}),this.triggerContactSync()),this.config.enableSyncData.includes("group")&&(Si("Triggering automatic group sync after login",{userId:e}),this.triggerGroupSync())}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new Xg(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const e=this.managerRegistry.get("contactManager");if(!e?.createSyncController)throw new Zr("ContactManager is required for contact sync",{code:nt,details:{fields:[{path:"contactManager",message:"ContactManager must be registered for enableSyncData: ['contact']",rule:"required"}]}});return this.contactSyncController=e.createSyncController({getContextState:()=>{const e=this.requireCacheManager();return{cacheMeta:e.loadContactCacheMeta(),versionState:e.loadContactVersionState(),cachedSnapshot:e.loadContactSnapshot("cache")}},queryMetadata:async e=>await hy(this.getContactSyncRestContext(),e,this.platformAdapter?.request),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),buildRosterRequest:({version:e})=>this.buildContactRosterRequest(e),applySyncResult:e=>{const t=this.requireCacheManager().applyContactSync(e);return this.refreshConversationDisplayFromUserInfos(t.snapshot.items.map(e=>({userId:e.userId})),"profile"),t},onStart:()=>{this.emitSyncDataStart("contact")},onFinish:e=>{this.emitSyncDataFinished({dataType:"contact",status:e?.error?"failed":"success",error:e?.error?{dataType:"contact",code:e.error.code,stage:e.error.stage,message:e.error.message,retryable:e.error.retryable}:void 0})}}),this.contactSyncController}ensureGroupSyncController(){if(this.groupSyncController)return this.groupSyncController;const e=this.managerRegistry.get("groupManager");if(!e?.createSyncController)throw new Zr("GroupManager is required for group sync",{code:nt,details:{fields:[{path:"groupManager",message:"GroupManager must be registered for enableSyncData: ['group']",rule:"required"}]}});return this.groupSyncController=e.createSyncController({getRestContext:()=>this.getRestContext(),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),getCacheManager:()=>this.requireCacheManager(),applyRuntimeSnapshot:e=>{const t=this.managerRegistry.get("groupManager");t?.applyJoinedGroupSnapshot?.(e),this.refreshConversationDisplayFromJoinedGroups(e.items,"profile")},getRuntimeSnapshot:()=>{const e=this.managerRegistry.get("groupManager");return e?.getJoinedGroupSnapshotForSync?.()??null},onStart:()=>{this.emitSyncDataStart("group")},onFinish:e=>{this.emitSyncDataFinished({dataType:"group",status:e.status,error:e.error})}}),this.groupSyncController}emitSyncDataStart(e){this.eventHub.dispatch(G,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(j,e)}requireCacheManager(){if(!this.cacheManager)throw new Zr("cacheManager is required",{code:nt,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;if(e)return this.buildAuthenticatedContactSyncUrls([e]);if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw Si("Automatic contact sync sync-ws is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw Si("Automatic contact sync sync-ws is unavailable without dns service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});try{const e=await kb(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=e.syncWebsocketUrls,this.contactSyncDnsResolved=!0}catch(t){throw Si("Automatic contact sync sync-ws DNS resolve failed",{userId:this.currentUserId,reason:t instanceof Error?t.message:String(t)}),new Hr("Contact sync websocket dns resolve failed",Cr,{details:{stage:"socket_connect",cause:t instanceof Error?t.message:String(t)}})}if(0===this.contactSyncWsUrls.length)throw Si("Automatic contact sync sync-ws is unavailable after DNS resolve",{userId:this.currentUserId,serviceConnectionMode:"dns"}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls)}buildAuthenticatedContactSyncUrls(e){const t=this.requireContactSyncToken();return this.shuffleContactSyncUrls(e.map(e=>this.buildContactSyncSocketUrl(e,t)))}buildAuthenticatedSessionListSyncUrls(e){if(0===e.length)return[];const t=this.requireContactSyncToken();return e.map(e=>this.buildContactSyncSocketUrl(e,t))}requireContactSyncToken(){if(this.authToken)return this.authToken;throw new Zr("token is required",{code:nt,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const r=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new Zr("sync websocket URL must use ws or wss protocol");const s=r.indexOf("#"),n=s>=0?r.slice(s):"",i=s>=0?r.slice(0,s):r,o=i.indexOf("?"),a=o>=0?i.slice(0,o):i,c=o>=0?i.slice(o+1):"",d=a.indexOf("://")+3,u=a.indexOf("/",d),l=u<0||"/"===a.slice(u)?`${a}/ws`:a,h=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),p=encodeURIComponent(t).replace(/%20/g,"+");return h.push(`token=${p}`),`${l}?${h.join("&")}${n}`}shuffleContactSyncUrls(e){const t=[...e];for(let r=t.length-1;r>0;r-=1){const e=Math.floor(Math.random()*(r+1)),s=t[r],n=t[e];s&&n&&(t[r]=n,t[e]=s)}return t}buildContactRosterRequest(e){const t=this.getContactSyncRestContext(),{orgName:r,appName:s}=Qn(t.appKey);return{type:Xb,header:{resource:t.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:r,app:s,username:t.userId,version:e,cursor:0}}resetCore(){this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core&&(this.core.destroy(),this.core=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.resetManagerSessionRuntimes())}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new Zr("appKey is unavailable before DNSConfig resolution",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new Zr("appKey is unavailable for the current session",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){const e=this.managerRegistry.get("groupManager");e?.resetSessionRuntime?.()}getContactSyncRestContext(){const e=this.getRestContext(),t=this.config.serviceConfig.serverUrls?.syncRestApiUrl;return t?{...e,restBaseUrl:t}:e}static isSameConfig(t,r){return t.appKey===r.appKey&&(t.appId===r.appId&&(!!e.isSameStringArray(t.enableSyncData,r.enableSyncData)&&(t.useCustomAttachmentUpload===r.useCustomAttachmentUpload&&(t.enableMd5Check===r.enableMd5Check&&(!!e.isSameServiceConfig(t.serviceConfig,r.serviceConfig)&&(t.useFixedDeviceId===r.useFixedDeviceId&&(t.deviceId===r.deviceId&&(t.useReplacedMessageContents===r.useReplacedMessageContents&&(t.customDeviceName===r.customDeviceName&&(t.customOSPlatform===r.customOSPlatform&&(t.platformAdapterOptions?.prefer===r.platformAdapterOptions?.prefer&&(t.platformAdapterOptions?.runtimeInput===r.platformAdapterOptions?.runtimeInput&&(t.platformAdapterOptions?.overrides===r.platformAdapterOptions?.overrides&&(t.uiKitVersion===r.uiKitVersion&&(t.cacheEncryptionMode===r.cacheEncryptionMode&&(t.enableUserInfoSync===r.enableUserInfoSync&&(t.deleteConversationOnGroupDestroyed===r.deleteConversationOnGroupDestroyed&&(t.syncConversationListConfig.includeEmpty===r.syncConversationListConfig.includeEmpty&&(t.profileSync.userInfoWindowMs===r.profileSync.userInfoWindowMs&&t.profileSync.userInfoBatchSize===r.profileSync.userInfoBatchSize&&t.profileSync.groupNamecardWindowMs===r.profileSync.groupNamecardWindowMs&&t.profileSync.groupNamecardMaxConcurrency===r.profileSync.groupNamecardMaxConcurrency)))))))))))))))))))}static normalizeServiceConfig(e){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??vb,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:e?.serverUrls}}static normalizeSyncDataTypes(e){const t=[];for(const r of e)t.includes(r)||t.push(r);return t}static isSameStringArray(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}static isSameServiceConfig(t,r){if(t.mode!==r.mode)return!1;if(t.dnsConfigUrls.length!==r.dnsConfigUrls.length)return!1;for(let e=0;e<t.dnsConfigUrls.length;e+=1)if(t.dnsConfigUrls[e]!==r.dnsConfigUrls[e])return!1;return e.isSameServerUrls(t.serverUrls,r.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl&&e.syncRestApiUrl===t.syncRestApiUrl&&e.syncWsUrl===t.syncWsUrl)}};hI.instance=null;let pI=hI;const mI=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),fI=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw(e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}))(t);return e.trim()},gI=e=>`mark_${String(e)}`,yI=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw mI(t,`${t} must be one of singleChat, groupChat, chatRoom`)},vI=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",bI=e=>"string"==typeof e&&e.length>0?e:void 0,II=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}},wI=e=>Bl(e)?e:void 0,CI=(e,t)=>{const r=wI(e);if(!r)return;const s=(e=>"string"==typeof e?$l(e,{}):wI(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],i=wI(n[0])??wI(s.body),o=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(i?.type??s.type);if(!i||!o)return;const a=((e,t)=>{if("text"===e)return{content:bI(t.msg)??bI(t.content)??""};if("custom"===e){const e=wI(t.customExts)??wI(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:bI(t.customEvent)??bI(t.event)??"",params:r}}if("cmd"===e)return{action:bI(t.action)??""};if("image"===e){const e=bI(t.url)??bI(t.remotePath)??"";return{localUrl:"",filename:bI(t.filename)??bI(t.displayName),filetype:bI(t.filetype)??"application/octet-stream",width:II(t.width),height:II(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:bI(t.bigImageUrl),thumbnailUrl:bI(t.thumbnailUrl)??bI(t.thumbnailRemotePath),secret:bI(t.secret)??bI(t.secretKey),fileLength:II(t.fileLength)}}return"file"===e?{url:bI(t.url)??bI(t.remotePath),filename:bI(t.filename)??bI(t.displayName),filetype:bI(t.filetype)??"application/octet-stream",fileSize:II(t.fileSize),fileLength:II(t.fileLength),secret:bI(t.secret)??bI(t.secretKey)}:"voice"===e?{url:bI(t.url)??bI(t.remotePath),filename:bI(t.filename)??bI(t.displayName),filetype:bI(t.filetype)??"application/octet-stream",duration:II(t.duration)??0,fileLength:II(t.fileLength),secret:bI(t.secret)??bI(t.secretKey)}:"video"===e?{url:bI(t.url)??bI(t.remotePath),filename:bI(t.filename)??bI(t.displayName),filetype:bI(t.filetype)??"application/octet-stream",duration:II(t.duration)??0,width:II(t.width),height:II(t.height),fileLength:II(t.fileLength),secret:bI(t.secret)??bI(t.secretKey),thumbnailUrl:bI(t.thumbnailUrl)??bI(t.thumbnailRemotePath)}:"location"===e?{latitude:II(t.latitude)??0,longitude:II(t.longitude)??0,address:bI(t.address),buildingName:bI(t.buildingName)}:null})(o,i);if(!a)return;const c=bI(s.from)??bI(r.from)??"",d=bI(s.to)??t.conversationId,u=wI(s.sender),l={userId:bI(u?.userId)??c,nickname:bI(u?.nickname),avatarUrl:bI(u?.avatarUrl)},h=wI(s.ext)??{},p=(e=>{const t=wI(e);if(!t)return;const r=bI(t.operatorId)??bI(t.operator),s=II(t.operationCount)??II(t.count),n=II(t.operationTime)??II(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??wI(s.meta)?.edit_msg);return{msgServerId:bI(r.id)??t.messageId,msgLocalId:bI(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:o,sendStatus:"sent",ext:h,timestamp:II(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},SI=e=>`${e.conversationType}:${e.conversationId}`,TI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},_I=async(e,t,r,s)=>{const n=TI(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw mI("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!Bl(e))throw mI(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:fI(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:yI(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:fI(t.conversationId,"params.conversationId"),conversationType:yI(t.conversationType,"params.conversationType")}]})(r),o=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw mI(t,`${t} must be an integer between 0 and 19`);return e})(r.mark,"params.mark"),a=await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channels/mark?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{mark:gI(o),targets:i.map(e=>({to:e.conversationId,type:vI(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!Bl(e))return;const r="string"==typeof e.to?e.to.trim():"",s=(e=>"chat"===e||"singleChat"===e?"singleChat":"groupchat"===e||"groupChat"===e?"groupChat":"chatroom"===e||"chatRoom"===e?"chatRoom":null)(e.type);r&&s&&t.add(SI({conversationId:r,conversationType:s}))}),t})((Bl(a)&&Bl(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of i){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(SI(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:o,operation:s?"addMark":"removeMark"}},RI=async(e,t,r,s)=>{const n=TI(t),i=fI(r.conversationId,"params.conversationId"),o=yI(r.conversationType,"params.conversationType"),a=fI(r.messageId,"params.messageId");return await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channel/pin?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{to:i,type:vI(o),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:o,messageId:a,operation:s?"pin":"unpin"}},AI=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],MI=(e,t)=>`${e}\0${t}`,EI=(e,t,r)=>{const s={userId:e};for(const n of AI){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},UI=e=>EI(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),NI=(e,t,r)=>{const s=new Map;if(!e?.getGroupNamecard||!r)return s;for(const n of t){const t=e.getGroupNamecard(n.groupId,n.user.userId,!1);t&&s.set(MI(n.groupId,n.user.userId),t.namecard)}return s},kI=async(e,t)=>{if(0===e.length||!t)return[];try{return await t({userIds:e})}catch(r){return Si("Group user info hydration failed",{userIds:e,error:r}),[]}},OI=async(e,t)=>{t&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,r])=>{try{await t(e,r)}catch(s){Si("Group namecard hydration failed",{groupId:e,userIds:r,error:s})}}))},xI=async e=>{const t=(e=>{const t=[],r=new Set;for(const s of e){const e=s.groupId.trim(),n=s.user.userId.trim();if(!e||!n)continue;const i=MI(e,n);r.has(i)||(r.add(i),t.push({groupId:e,user:{...s.user,userId:n}}))}return t})(e.contexts),r=(e=>{const t=[],r=new Set;for(const s of e)r.has(s.user.userId)||(r.add(s.user.userId),t.push(s.user.userId));return t})(t),s=((e,t)=>{const r=new Map;if(!e)return r;for(const n of t){const t=e.getRuntimeUserInfo?.(n,!1)??null;t&&r.set(n,t)}const s=t.filter(e=>!r.has(e));for(const n of e.getUserInfoSummaries?.(s,!1)??[])r.set(n.userId,UI(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),i=new Set(n),o=NI(e.cacheManager,t,e.includeNameCard),a=e.includeNameCard?((e,t,r)=>{const s=new Map;for(const n of e){const e=n.user.userId,i=MI(n.groupId,e);if(!t.has(e)||r.has(i))continue;const o=s.get(n.groupId)??[];o.includes(e)||o.push(e),s.set(n.groupId,o)}return s})(t,i,o):new Map,[c]=await Promise.all([kI(n,e.fetchUserInfos),OI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=NI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=MI(h.groupId,e),r=EI(e,h.user,d.get(e)??s.get(e)),n=u.get(t)??o.get(t);l.set(t,void 0!==n?{...r,nameCard:n}:r)}return{usersByContextKey:l,fetchedUserInfos:c,missingUserIds:n.filter(e=>!d.has(e))}},LI=async e=>{const t=await xI({...e,contexts:e.users.map(t=>({groupId:e.groupId,user:t}))}),r=new Map;for(const s of e.users){const n=s.userId.trim();if(!n||r.has(n))continue;const i=t.usersByContextKey.get(MI(e.groupId.trim(),n));i&&r.set(n,i)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},PI=nb(["singleChat","groupChat","chatRoom"]),DI=sb(Yv()).refine(e=>(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e),"ext must be an object").refine(e=>(e=>{try{return JSON.stringify(e),!0}catch{return!1}})(e),"ext must be JSON serializable"),qI=tb({path:Jv().min(1,"data.path is required"),size:Zv().optional(),name:Jv().optional(),type:Jv().optional()}),BI=tb({uri:Jv().min(1,"data.uri is required"),size:Zv().optional(),name:Jv().optional(),type:Jv().optional()}),$I=rb(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>Hv(t=>t instanceof e,t))(File):Xv(),qI,BI]),FI=tb({conversationId:Jv().min(1,"conversationId is required"),conversationType:PI,ext:DI.optional(),timestamp:Zv().int().positive("timestamp must be a positive integer").optional(),receiverList:eb(Jv().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:Qv().optional(),webhookEnv:Jv().optional(),priority:nb(["high","normal","low"]).optional(),needReadReceipt:Qv().optional(),isChatThread:Qv().optional()}),GI=tb({type:Jv().min(1,"messageList.type is required"),sender:tb({userId:Jv().min(1,"messageList.sender.userId is required"),nickname:Jv().optional(),avatarUrl:Jv().optional()}),conversationId:Jv().min(1,"messageList.conversationId is required"),conversationType:PI,timestamp:Zv().int().positive("messageList.timestamp must be positive"),body:sb(Yv()),combineLevel:Zv().int().min(0).max(10).optional()}).passthrough(),jI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:by.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:by.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:by.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),zI=jI(FI.extend({content:Jv().min(1,"content is required"),targetLanguages:eb(Jv().min(1)).optional()})),KI=jI(FI.extend({originalUrl:Jv().min(1,"originalUrl is required").optional(),filename:Jv().min(1,"filename is required").optional(),filetype:Jv().min(1,"filetype is required").optional(),width:Zv().positive("width must be positive").optional(),height:Zv().positive("height must be positive").optional(),isGif:Qv().optional(),isOriginalImage:Qv().optional(),fileLength:Zv().positive("fileLength must be positive").optional(),data:$I.optional(),thumbnailUrl:Jv().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),HI=jI(FI.extend({originalUrl:Jv().min(1,"originalUrl is required").optional(),filename:Jv().min(1,"filename is required").optional(),filetype:Jv().min(1,"filetype is required").optional(),fileSize:Zv().positive("fileSize must be positive").optional(),fileLength:Zv().positive("fileLength must be positive").optional(),data:$I.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),VI=jI(FI.extend({originalUrl:Jv().min(1,"originalUrl is required").optional(),filename:Jv().min(1,"filename is required").optional(),filetype:Jv().min(1,"filetype is required").optional(),duration:Zv().positive("duration must be positive"),fileLength:Zv().positive("fileLength must be positive").optional(),data:$I.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),WI=jI(FI.extend({originalUrl:Jv().min(1,"originalUrl is required").optional(),filename:Jv().min(1,"filename is required").optional(),filetype:Jv().min(1,"filetype is required").optional(),duration:Zv().positive("duration must be positive"),width:Zv().positive("width must be positive").optional(),height:Zv().positive("height must be positive").optional(),fileLength:Zv().positive("fileLength must be positive").optional(),thumbnailUrl:Jv().min(1).optional(),data:$I.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),JI=jI(FI.extend({latitude:Zv(),longitude:Zv(),address:Jv().min(1).optional(),buildingName:Jv().min(1).optional()})),ZI=jI(FI.extend({action:Jv().min(1,"action is required")})),QI=jI(FI.extend({event:Jv().min(1,"event is required"),params:sb(Jv()).optional()})),YI=jI(FI.extend({title:Jv().min(1,"title is required"),summary:Jv().min(1,"summary is required"),compatibleText:Jv().min(1).optional(),messageList:eb(GI).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),XI=e=>{const t=e?.userId?.trim();if(!t)throw new Zr("sender.userId is required",{code:nt,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:t,nickname:e?.nickname,avatarUrl:e?.avatarUrl}},ew=()=>dm(),tw=(e,t)=>{if(e)return e;if(!t)throw new Zr("url or data is required",{code:nt,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const r=cm(t);if(!r)throw new Zr("Failed to resolve local url",{code:it,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return r},rw=e=>!!e.isGif||(e.isOriginalImage??!1),sw=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??dm(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:r,sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:s,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}),nw=(e,t)=>{const r=ib.validateOrThrow(YI,e),s=r.messageList,n=XI(t);Mm(s);const i=Em(s);Um(i);const o={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:i},a=sw(r,n,"combine",o);return((e,t)=>{t&&Th.set(e,t)})(a,r.compatibleText),a},iw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},ow=e=>{const t=new Uint8Array(Vc.util.base64.length(e));return Vc.util.base64.decode(e,t,0),t},aw=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),cw=async e=>{try{return await e()}catch(t){if(!(t instanceof ts))throw t;const e=(e=>{const t="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case qt:case Ar:return"Translation service is not enabled";case Rr:return t?.includes("too long")?"Translation text is too long":t?.includes("target language")?"Invalid target language":"Invalid translation request";case Mr:return"Translation quota has been reached";case Er:return"Translation service error";default:return}})(t);if(!e)throw t;throw new ts(`REST business error: ${e}`,{code:t.code,details:t.details})}},dw=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",uw=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},lw=e=>({userId:e}),hw=(e,t)=>{if(!aw(e)||!aw(e.data))throw ay({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},pw=(e,t)=>{if(!aw(e)||!Array.isArray(e.data))throw ay({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},mw=(e,t)=>Array.isArray(e)?e:pw(e,t),fw={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},gw={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},yw={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},vw=(e,t,r)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:n}=Qn(e.appKey),i=t.indexOf("/chatfiles/"),o=i>=0?t.slice(i):t,a=`${e.restBaseUrl}/${s}/${n}${o}`;return ri(a,r)},bw=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e))return e;const t=Object.values(e),r=[];for(const s of t)Array.isArray(s)&&r.push(...s);return r.length>0?r:void 0},Iw=(e,t,r)=>{const s=dw(r.contentType??r.type),n=gw[s];if(!n)return null;const i=aw(r.content)?r.content:{},o=((e,t)=>{const r=dw(t.conversationType);if("groupchat"===r||"chatroom"===r)return dw(t.receiverId);const s=dw(t.senderId);return s===e?dw(t.receiverId):s})(t,r),a=yw[dw(r.conversationType)]??"singleChat",c={msgServerId:dw(r.messageId),msgLocalId:dw(r.messageId),from:dw(r.senderId),to:dw(r.receiverId),conversationId:o,conversationType:a,type:n,ext:aw(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(dw(r.sentTime)).getTime(),sender:{userId:dw(r.senderId)},highlight:bw(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=dw(i.remotePath??i.url),l=dw(i.secret??i.secretKey);switch(n){case"txt":d={type:"txt",content:dw(i.message??r.text)};break;case"img":{const t=vw(e,u,l);d={type:"img",url:t,thumb:i.thumb?vw(e,dw(i.thumb),dw(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(i.width??(aw(i.size)?i.size.width:0))||0,height:Number(i.height??(aw(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":d={type:"video",url:vw(e,u,l),thumb:i.thumb||i.thumbnailRemotePath?vw(e,dw(i.thumb??i.thumbnailRemotePath),dw(i.thumb_secret??i.thumbnailSecretKey)):"",secret:l,filename:dw(i.filename??i.displayName),duration:Number(i.length??i.duration??0),fileLength:Number(i.file_length??i.fileLength??0)};break;case"file":d={type:"file",url:vw(e,u,l),secret:l,filename:dw(i.filename??i.displayName),fileLength:Number(i.file_length??i.fileLength??0)};break;case"loc":d={type:"loc",latitude:Number(i.lat??i.latitude??0),longitude:Number(i.lng??i.longitude??0),address:dw(i.addr??i.address),buildingName:dw(i.buildingName)};break;case"custom":d={type:"custom",customEvent:dw(i.customEvent),customExts:aw(i.customExts)?i.customExts:{}};break;default:return null}return{...c,body:d}},ww=async(e,t,r)=>{const s=`${iw(t)}/users/${t.userId}/messages/search/get`,n=((e,t)=>{const{option:r,pageNum:s=1,pageSize:n=20}=e,i=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),o={searchMode:"default",highlightEnable:!0,page:s,size:n};return 1===i.length?o.keyword=i[0]:(o.keywords=i,o.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?o.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?o.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(o.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(o.contentType=r.msgTypes.map(e=>fw[e]??e).join(",")),void 0!==r.startTime&&(o.startTime=r.startTime),void 0!==r.endTime&&(o.endTime=r.endTime),r.searchScope&&(o.searchExt=r.searchScope),r.direction&&(o.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:o}})(r,t.userId),i=await e.post(s,n,{operation:"searchMessages"}),o=aw(i)?i:{},a=aw(o.data)?o.data:o,c=aw(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=aw(c.pagination)?c.pagination:c,l=Number(u.pageNum??u.page??r.pageNum??1),h=Number(u.pageSize??u.size??r.pageSize??20),p=Number(u.totalPages??0),m=1===u.isFinished||l>=p,f=[];for(const g of d){if(!aw(g))continue;const e=Iw(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:h,totalPages:p,isLast:m}},Cw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/api/sdk/v1/${t}/${r}`},Sw=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Tw=e=>Sw(e)&&"string"==typeof e.path&&e.path.trim().length>0,_w=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||Tw(e),Rw=e=>{if(!Sw(e))return;return{data:Sw(e.data)?e.data:void 0,error:Sw(e.error)?e.error:void 0}},Aw=(e,t)=>{const r=Rw(e),s=r?.data?.text;if("string"!=typeof s)throw new Hr(`${t} response data is invalid`,fr,{details:{api:t,response:e}});return s},Mw=(e,t,r,s="sdk")=>"auth"===s?new Jr(e,{code:t,details:r}):"validation"===s?new Zr(e,{code:t,details:r}):new Hr(e,t,{details:r}),Ew=e=>!(void 0===e||Sw(e)&&!Array.isArray(e))||(void 0!==e?.format&&"string"!=typeof e.format||(void 0!==e?.sampleRate&&"number"!=typeof e.sampleRate||(void 0!==e?.bitsPerSample&&"number"!=typeof e.bitsPerSample||void 0!==e?.channels&&"number"!=typeof e.channels))),Uw=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},Nw=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof Hr&&Sw(e.details)?e.details:void 0,r=Rw(t?.rawResponse??t?.response??e),s=t?.serverCode??r?.error?.code,n=t?.serverMessage??r?.error?.message;return{serviceCode:"string"==typeof s||"number"==typeof s?String(s):void 0,serviceMessage:"string"==typeof n?n:void 0}})(e);if(e instanceof rs)return Mw("File upload failed",qr,{cause:e.details});if(e instanceof Hr&&!t)return e;if(t)switch(t){case"4041001":return Mw("File not found",Or,{serviceCode:t,serviceMessage:r});case"4001002":return Mw("Invalid file",Ur,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return Mw("File upload failed",qr,{serviceCode:t,serviceMessage:r});case"4001003":return Mw("Voice duration exceeds 60 seconds",Nr,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return Mw("Voice-to-text service is not enabled",qt,{serviceCode:t,serviceMessage:r});case"4031002":return Mw("Beta service usage limit exceeded",Fr,{serviceCode:t,serviceMessage:r});case"4001001":return"string"==typeof(s=r)&&s.toLowerCase().includes("uploaded file exceeds")?Mw("File too large",xr,{serviceCode:t,serviceMessage:r}):Mw(r||"Missing or invalid request parameter",nt,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return Mw("Voice-to-text failed",kr,{serviceCode:t,serviceMessage:r});case"4011001":return Mw(r||"Unauthorized or invalid token",dt,{serviceCode:t,serviceMessage:r},"auth");default:return Mw(r||(e instanceof Error?e.message:"Voice-to-text failed"),kr,{serviceCode:t,serviceMessage:r})}var s;return e instanceof Hr?Mw(e.message,e.code,e.details):Mw(e instanceof Error?e.message:"Voice-to-text failed",kr)},kw=(e,t)=>{if(!Sw(r=e)||"string"!=typeof r.filename||"string"!=typeof r.filetype||"number"!=typeof r.duration||"type"in r&&void 0!==r.type&&"voice"!==r.type)throw Mw("Invalid file",Ur,{path:"voiceMessageBody"},"validation");var r;if(Ew(t))throw Mw("Invalid file",Ur,{path:"voiceParams"},"validation");if(!e.url)throw Mw("File not found",Or,{path:"voiceMessageBody.url"});if(!Uw(e.url))throw Mw("Invalid file",Ur,{path:"voiceMessageBody.url"},"validation");return e},Ow=(e,t)=>{if(Ew(t))throw Mw("Invalid file",Ur,{path:"voiceParams"},"validation");if(!_w(e))throw Mw("Invalid file",Ur,{path:"file"},"validation");return e},xw=async(e,t,r,s)=>{const n=kw(r,s),i=Uw(n.url);if(!i)throw((e,t,r,s="invalid")=>new Zr(e,{code:t,details:{fields:[{path:r,message:e,rule:s}]}}))("File not found",Or,"voiceMessageBody.url");try{const r=await e.post(`${Cw(t)}/speech/transcriptions`,{data:{fileId:i,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:Aw(r,"voiceMessageToText")}}catch(o){throw Nw(o)}},Lw=tb({keywordList:eb(Jv()).min(1,"keywordList must not be empty").max(5,"keywordList must have at most 5 keywords").refine(e=>e.map(e=>e.trim()).filter(e=>e.length>0).length>0,"keywordList must contain at least one non-empty keyword"),keywordListMatchType:nb(["or","and"]).optional(),conversationId:Jv().min(1).optional(),conversationType:nb(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:eb(nb(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Zv().optional(),endTime:Zv().optional(),searchScope:nb(["none","with","only"]).optional(),direction:nb(["up","down"]).optional()}).refine(e=>void 0!==e.conversationId===(void 0!==e.conversationType),{message:"conversationId and conversationType must be provided together"}).refine(e=>void 0!==e.startTime===(void 0!==e.endTime),{message:"startTime and endTime must be provided together"}).refine(e=>void 0===e.startTime||void 0===e.endTime||e.endTime>=e.startTime,{message:"endTime must be >= startTime"}),Pw=tb({option:Lw,pageNum:Zv().int().min(1).default(1),pageSize:Zv().int().min(1).max(100).default(20)}),Dw=Gb(jb,{common:{},apis:{sendMessage:{range:"1,4,100,108,110,202,210,213-215,219-222,300-301,303,305,402,405-406,500-501,505-510,602-603,606-607,1200,1299",localErrors:{sendMessage:{operation_cancelled:{code:1,retryable:!1},upload_invalid_appkey:{code:100,retryable:!1},validation_invalid:{code:110,retryable:!1},not_connected:{code:300,retryable:!0},request_timeout:{code:301,retryable:!0},send_failed:{code:303,retryable:!1},upload_failed:{code:402,retryable:!0},file_too_large:{code:405,retryable:!1},file_content_improper:{code:406,retryable:!1},encode_failed:{code:500,retryable:!1}}},errors:{SERVICE_LIMIT_EXCEEDED:{code:4,retryable:!1},TOKEN_EXPIRED:{code:108,retryable:!1},AUTH_FAILED:{code:202,retryable:!1},PERMISSION_DENIED:{code:210,retryable:!1},BIND_ANOTHER_DEVICE:{code:213,retryable:!1},TOO_MANY_DEVICES:{code:214,retryable:!1},USER_MUTED:{code:215,retryable:!1},USER_MUTED_BY_ADMIN:{code:219,retryable:!1},USER_DEVICE_CHANGED:{code:220,retryable:!1},USER_NOT_ON_ROSTER:{code:221,retryable:!1},BLOCKED_BY_RECIPIENT:{code:222,retryable:!1,aliases:["blocked"]},SERVER_SERVING_DISABLED:{code:305,retryable:!1},MESSAGE_INCLUDE_ILLEGAL_CONTENT:{code:501,retryable:!1},SERVICE_NOT_ENABLED:{code:505,retryable:!1},MESSAGE_EXPIRED:{code:506,retryable:!1},MESSAGE_ILLEGAL_WHITELIST:{code:507,retryable:!1},MESSAGE_EXTERNAL_LOGIC_BLOCKED:{code:508,retryable:!1},MESSAGE_CURRENT_LIMITING:{code:509,retryable:!0},MESSAGE_SIZE_LIMIT:{code:510,retryable:!1},GROUP_NOT_JOINED:{code:602,retryable:!1},GROUP_PERMISSION_DENIED:{code:603,retryable:!1},GROUP_NOT_EXIST:{code:606,retryable:!1},GROUP_DISABLED:{code:607,retryable:!1},MESSAGE_BLOCKED:{code:1200,retryable:!1},THIRD_DEFAULT_FAILED:{code:1299,retryable:!1}}},getHistoryMessages:{range:"4,110,202,505",localErrors:{getHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},page_size_exceeded:{code:110,aliases:["pull number cannot be greater","limit is to large"],retryable:!1}}},removeHistoryMessages:{range:"110,112,202,505",localErrors:{removeHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},query_param_reaches_limit:{code:112,aliases:["delete msg list limit"],retryable:!1}}},getGroupMessageReadUsers:{range:"4,110,500",localErrors:{getGroupMessageReadUsers:{validation_invalid:{code:110,retryable:!1}}},errors:{message_not_found:{code:500,retryable:!1}}},recallMessage:{range:"110,201,300,504,505",localErrors:{recallMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},recall_time_limit:{code:504,retryable:!1},recall_disabled:{code:505,retryable:!1}}},updateMessage:{range:"110,111,201,210,300,511",localErrors:{modifyMessage:{validation_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1},not_login:{code:201,retryable:!0},permission_denied:{code:210,retryable:!1},not_connected:{code:300,retryable:!0},edit_failed:{code:511,retryable:!0}}},downloadMessageAttachment:{range:"400,401,403,407",localErrors:{downloadAttachment:{validation_invalid:{code:401,retryable:!1}}},errors:{not_found:{code:400,httpStatus:404,retryable:!1},invalid:{code:401,retryable:!1},download_failed:{code:403,retryable:!0},expired:{code:407,httpStatus:404,retryable:!1}}},downloadAndParseCombineMessage:{range:"110,401,403,500",localErrors:{downloadAndParseCombineMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_param:{code:110,retryable:!1},invalid_type:{code:500,retryable:!1},parse_failed:{code:401,retryable:!0},download_failed:{code:403,retryable:!0}}},addReaction:{range:"110,302,505,600,602,1300-1302",localErrors:{addReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{reaction_already_operated:{code:1301,retryable:!1},reaction_reach_limit:{code:1300,retryable:!1},group_not_joined:{code:602,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1},service_not_enabled:{code:505,retryable:!1},server_busy:{code:302,retryable:!0}}},removeReaction:{range:"110,505,1301,1302",localErrors:{removeReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},getReactionList:{range:"110,505,600",localErrors:{getReactionList:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},group_invalid_id:{code:600,retryable:!1}}},getReactionDetail:{range:"110,505,1302",localErrors:{getReactionDetail:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},pinMessage:{range:"4,110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_limit:{code:4,aliases:["91101"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102"],retryable:!1}}},unpinMessage:{range:"110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getPinnedMessageList:{range:"110,111",errors:{operation_unsupported:{code:111,aliases:["15002"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getSupportedTranslationLanguages:{range:"505",errors:{service_not_enabled:{code:505,aliases:["service not open!"],retryable:!1}}},translateMessage:{range:"505,1110-1113",localErrors:{translateMessage:{validation_invalid:{code:1110,retryable:!1}}},errors:{translate_text_too_long:{code:1110,runtimeMessage:"Translation text is too long",retryable:!1},translate_param_invalid:{code:1110,runtimeMessage:"Invalid target language",retryable:!1},service_not_enabled:{code:1111,runtimeMessage:"Translation service is not enabled",aliases:["service not open!"],retryable:!1},translate_usage_limit:{code:1112,runtimeMessage:"Translation quota has been reached",aliases:["The request has reached the maximum limit"],retryable:!1},translate_failed:{code:1113,runtimeMessage:"Translation service error",aliases:["The request failed, please try again later."],retryable:!1}}},voiceMessageToText:{range:"4,110,202,407-411,505",localErrors:{voiceMessageToText:{validation_invalid:{code:407,retryable:!1},file_not_found:{code:410,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},file_not_found:{code:410,retryable:!1,aliases:["4041001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},voiceFileToText:{range:"4,110,202,402,407-411,505",localErrors:{voiceFileToText:{validation_invalid:{code:407,retryable:!1},upload_required:{code:110,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},upload_failed:{code:402,retryable:!0,aliases:["5021001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},getConversationList:{range:"110",localErrors:{getConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPinnedConversationList:{range:"110",localErrors:{getPinnedConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getConversationListByMark:{range:"110",localErrors:{getConversationListByMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},deleteConversation:{range:"110",localErrors:{deleteConversation:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearConversationUnreadMessageCount:{range:"110,201,300,500",localErrors:{clearConversationUnreadMessageCount:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},clearAllConversationUnreadMessageCount:{range:"201,300,500",errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},sendMessageReadReceipts:{range:"110,300",localErrors:{sendMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_direction:{code:110,retryable:!1},not_connected:{code:300,retryable:!0}}},getGroupMessageReadReceipts:{range:"110,202,210,303",localErrors:{getGroupMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},auth_bad_access_token:{code:202,httpStatus:401,retryable:!1},forbidden_op:{code:210,httpStatus:403,retryable:!1},unknown_exception_error:{code:303,httpStatus:500,retryable:!0}}},setConversationPinned:{range:"110",localErrors:{setConversationPinned:{validation_invalid:{code:110,retryable:!1}}},errors:{}},addConversationMark:{range:"110",localErrors:{addConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},removeConversationMark:{range:"110",localErrors:{removeConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearAllMessagesAndConversations:{range:"",errors:{}},searchMessages:{range:"110,202,303,505",localErrors:{searchMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{parameter_error:{code:110,httpStatus:400,retryable:!1,aliases:["4000005","4000006"]},token_invalid:{code:202,httpStatus:401,retryable:!1,aliases:["4010101"]},service_not_enabled:{code:505,httpStatus:403,retryable:!1,aliases:["4030204"]},app_not_found:{code:110,httpStatus:404,retryable:!1,aliases:["4040302"]},server_error:{code:303,httpStatus:500,retryable:!0,aliases:["5000701","5020801"]}}}}}),qw=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}async sendMessage(e,t){return this.getClientOrThrow().sendMessage(e,t)}createTextMessage(e){return((e,t)=>{const r=ib.validateOrThrow(zI,e),s=XI(t),n=ew(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),sw(r,s,"text",i,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=ib.validateOrThrow(KI,e),n=XI(t),i=ew(),o=s.data?tw(void 0,s.data):"",a=s.originalUrl?ni(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&am.set(i,s.data);const c=s.isGif??!1,d={localUrl:o,filename:s.filename,filetype:s.filetype,width:s.width,height:s.height,isGif:c,isOriginalImage:rw({isGif:c,isOriginalImage:s.isOriginalImage})};return a?.originalImageUrl&&(d.originalImageUrl=a.originalImageUrl,d.bigImageUrl=a.bigImageUrl,d.thumbnailUrl=a.thumbnailUrl),void 0!==s.fileLength&&(d.fileLength=s.fileLength),s.thumbnailUrl&&(d.thumbnailUrl=s.thumbnailUrl),sw(s,n,"image",d,i)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=ib.validateOrThrow(HI,e),s=XI(t),n=ew(),i=tw(r.originalUrl,r.data);r.data&&am.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(o.fileSize=r.fileSize),void 0!==r.fileLength&&(o.fileLength=r.fileLength),sw(r,s,"file",o,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=ib.validateOrThrow(VI,e),s=XI(t),n=ew(),i=tw(r.originalUrl,r.data);r.data&&am.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(o.fileLength=r.fileLength),sw(r,s,"voice",o,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=ib.validateOrThrow(WI,e),s=XI(t),n=ew(),i=tw(r.originalUrl,r.data);r.data&&am.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(o.width=r.width),void 0!==r.height&&(o.height=r.height),void 0!==r.fileLength&&(o.fileLength=r.fileLength),r.thumbnailUrl&&(o.thumbnailUrl=r.thumbnailUrl),sw(r,s,"video",o,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=ib.validateOrThrow(JI,e),s=XI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),sw(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=ib.validateOrThrow(ZI,e),s=XI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),sw(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=ib.validateOrThrow(QI,e),s=XI(t),n={event:r.event};return r.params&&(n.params=r.params),sw(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return nw(e,this.buildMessageSenderOrThrow())}getConversationList(e){if(void 0!==e?.mark&&(!Number.isInteger(e.mark)||e.mark<0||e.mark>19))throw new Zr("filter.mark must be an integer between 0 and 19",{code:it,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const t=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(t=>null!==t.lastMessage&&((void 0===e?.isPinned||t.isPinned===e.isPinned)&&!(void 0!==e?.mark&&!((e,t)=>e.marks.includes(t))(t,e.mark)))).map(zg);return this.getClientOrThrow().markConversationAccess(t.map(e=>({conversationId:e.conversationId,type:e.conversationType}))),t}setCurrentConversation(e){this.validateConversationLocator(e),this.getClientOrThrow().getCacheManager()?.setCurrentConversation({conversationId:e.conversationId,type:e.conversationType})}resetCurrentConversation(){this.getClientOrThrow().getCacheManager()?.resetCurrentConversation()}getCurrentConversation(){const e=this.getClientOrThrow().getCacheManager()?.getCurrentConversation()??null;return e?{conversationId:e.conversationId,conversationType:e.type}:null}refreshSessionList(e){return this.getClientOrThrow().refreshSessionList(e)}async deleteConversation(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=TI(t),n=fI(r.conversationId,"params.conversationId"),i=yI(r.conversationType,"params.conversationType"),o=r.deleteRoamingMessages??!1;if("boolean"!=typeof o)throw mI("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${s.orgName}/${s.appName}/user/${s.encodedUserId}/user_channel?resource=${s.encodedResource}`,{method:"DELETE",body:{channel:n,type:"groupChat"===i?"groupChat":vI(i),delete_roam:o},operation:"deleteConversation"}),{conversationId:n,conversationType:i,operation:"delete"}})(this.getRestClient(t),t,e),s=this.getClientOrThrow(),n=s.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return n?.changed&&s.emitConversationListUpdate("local"),r}async setConversationPinned(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=TI(t),n=fI(r.conversationId,"params.conversationId"),i=yI(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw mI("params.pinned","params.pinned must be a boolean");const o="groupChat"===i?"groupChat":vI(i),a=r.pinned?await e.post(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?resource=${s.encodedResource}`,{type:o,to:n},{operation:"setConversationPinned"}):await e.delete(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?type=${encodeURIComponent(o)}&to=${encodeURIComponent(n)}&resource=${s.encodedResource}`,{operation:"setConversationPinned"}),c=Bl(a)&&Bl(a.data)?a.data:{};return{conversationId:n,conversationType:i,operation:"setPinned",isPinned:"boolean"==typeof c.is_top?c.is_top:r.pinned,pinnedTime:"number"==typeof c.update_top_status_time?c.update_top_status_time:r.pinned?Date.now():0}})(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationPinnedMutation({conversationId:r.conversationId,type:r.conversationType,isPinned:r.isPinned??e.pinned,pinnedTime:r.pinnedTime});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>_I(e,t,r,!0))(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async removeConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>_I(e,t,r,!1))(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async clearAllMessagesAndConversations(){const e=this.getRestContextOrThrow();await(async(e,t)=>{const r=TI(t);await e.post(`/${r.orgName}/${r.appName}/sdk/message/roaming/user/${r.encodedUserId}/delete/all?resource=${r.encodedResource}`,void 0,{operation:"clearAllMessagesAndConversations"})})(this.getRestClient(e),e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversations();r?.changed&&t.emitConversationListUpdate("local")}async pinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>RI(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>RI(e,t,r,!1))(this.getRestClient(t),t,e))}async getPinnedMessageList(e){const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=TI(t),n=fI(r.conversationId,"params.conversationId"),i=yI(r.conversationType,"params.conversationType"),o=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(vI(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=Bl(o)&&Bl(o.data)?o.data:{};return{items:(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!Bl(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:Bl(r.message)&&"string"==typeof r.message.id?r.message.id:"";if(!s)return e;const o="number"==typeof r.pin_opt_at?r.pin_opt_at:0,a=CI(r.message,{messageId:s,conversationId:n,conversationType:i,currentUserId:t.userId,timestamp:o});return a?(e.push({messageId:s,conversationId:n,conversationType:i,operatorId:"string"==typeof r.pin_operator?r.pin_operator:void 0,pinnedAt:o,message:a}),e):e},[])}})(this.getRestClient(t),t,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(e){this.validateUnreadConversationLocator(e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:e.conversationId,type:e.conversationType});r?.changed&&t.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(s){if(!r?.matched)throw s;Si("Conversation unread remote sync failed after local clear",{conversationId:e.conversationId,conversationType:e.conversationType,error:s})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(e){if(this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),"text"!==e.message.type&&"custom"!==e.message.type)throw new Zr("only text and custom messages are editable",{code:Ut});await this.requireConnectedClient().sendMessageAction({kind:"update",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,body:e.message.body,messageType:e.message.type,ext:e.message.ext},(e,t)=>this.buildActionError(e,t));const t=Date.now(),r=this.getCurrentUserIdOrThrow(),s={operatorId:r,operationCount:1,operationTime:t};return{msgServerId:e.messageId,msgLocalId:"",from:r,to:e.conversationId,sender:{userId:r},conversationId:e.conversationId,conversationType:e.conversationType,type:e.message.type,sendStatus:"sent",ext:e.message.ext,timestamp:t,body:e.message.body,direct:"SEND",modifiedInfo:s}}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=`${iw(t)}/users/${t.userId}/messageroaming`,i=await e.post(n,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),o=hw(i,"getHistoryMessages"),a=Array.isArray(o.msgs)?o.msgs:[],c=[];for(const d of a){if(!aw(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(ow(d.msg));e&&c.push(e)}return{items:c,cursor:uw(o.next_key),hasMore:!0!==o.is_last&&c.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=ib.validateOrThrow(Pw,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>ww(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s="singleChat"===r.conversationType?"userId":"groupId",n="singleChat"===r.conversationType?"chat":"group",i=encodeURIComponent(t.clientResource),o=r.messageIds?`${iw(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${iw(t)}/sdk/message/roaming/${n}/user/${t.userId}/time?${s}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${i}`;await e.delete(o,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const s=gb();s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${iw(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,i=await e.get(n,{operation:"getGroupMessageReadUsers"}),o=hw(i,"getGroupMessageReadUsers"),a=aw(o.group_ack)?o.group_ack:o,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>aw(e)&&"string"==typeof e.username?{userId:e.username,user:lw(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof o.ackmid?o.ackmid:r.messageId,users:c,count:"number"==typeof a.total?a.total:c.length,cursor:uw(a.next_key),hasMore:!0!==a.is_last&&c.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${iw(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return pw(n,"getGroupMessageReadReceipts").map(e=>aw(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${iw(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${iw(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(s,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=gb(),n="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");s.set("msgIdList",n),s.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&s.set("groupId",r.groupId);const i=await e.get(`${iw(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return pw(i,"getReactionList").map(e=>{if(!aw(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>aw(e)&&"string"==typeof e.reaction?{reaction:e.reaction,count:"number"==typeof e.count?e.count:0,isAddedBySelf:!0===e.state,userIds:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[]}:null).filter(e=>null!==e)}}).filter(e=>null!==e)})(this.getRestClient(t),t,e))}async getReactionDetail(e){if(this.validateReactionParams(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=gb();s.set("msgId",r.messageId),s.set("message",r.reaction),s.set("cursor",r.cursor??""),s.set("limit",String(r.pageSize??20));const n=await e.get(`${iw(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),i=hw(n,"getReactionDetail"),o=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>aw(e)&&"string"==typeof e.userId?{userId:e.userId,user:lw(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],a=Array.isArray(i.userList)?i.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:lw(e)})):[],c=o.length>0?o:a;return{reaction:"string"==typeof i.reaction?i.reaction:r.reaction,count:"number"==typeof i.count?i.count:c.length,isAddedBySelf:!0===i.state,reactionUsers:c,cursor:uw(i.cursor),hasMore:uw(i.cursor).length>0,createdAt:"string"==typeof i.createdAt?i.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await cw(()=>e.get(`${iw(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return mw(r,"getSupportedTranslationLanguages").map(e=>aw(e)&&"string"==typeof e.code?{code:e.code,name:"string"==typeof e.name?e.name:e.code,nativeName:"string"==typeof e.nativeName?e.nativeName:e.code}:null).filter(e=>null!==e)})(this.getRestClient(e),e))}async translateMessage(e){if("text"!==e.message.type)throw new Zr("only text messages can be translated",{code:Rr,details:{fields:[{path:"message.type",message:"must be text",rule:"message_type"}]}});const t=e.message.body.content.trim();if(0===t.length)throw new Zr("message text is required",{code:Rr,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(e.targetLanguages)||0===e.targetLanguages.length)throw new Zr("targetLanguages is required",{code:Rr,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(e.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new Zr("targetLanguages contains invalid language code",{code:Rr,details:{fields:[{path:"targetLanguages",message:"contains invalid language code",rule:"language_code"}]}});const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=await cw(()=>e.post(`${iw(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=mw(s,"translateMessage"),i=aw(n[0])?n[0]:null;if(!i)throw ay({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(i.translations)?i.translations:[],a=aw(i.detectedLanguage)?i.detectedLanguage:void 0;return{detectedLanguage:a&&"string"==typeof a.language?{language:a.language,score:"number"==typeof a.score?a.score:Number(a.score??0)}:void 0,translations:o.map(e=>aw(e)&&"string"==typeof e.text&&"string"==typeof e.to?{text:e.text,to:e.to}:null).filter(e=>null!==e)}})(this.getRestClient(r),r,{text:t,targetLanguages:e.targetLanguages}))}async voiceMessageToText(e,t){kw(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>xw(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){Ow(e,t);const r=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new Hr("Upload capability is missing for current platform",Lr);return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=Ow(r,s),i=Gn({file:n,fallbackName:Tw(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${Cw(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[Ml]:Al()},source:i.source,fields:{username:t.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let n=r.body;try{n=JSON.parse(r.body)}catch{n=r.body}if(r.status<200||r.status>=300)throw new Hr("Voice-to-text failed",kr,{details:{httpStatus:r.status,rawResponse:n}});return{text:Aw(n,"voiceFileToText")}}catch(o){if(o instanceof Hr)throw Nw(o);throw Nw(ll(o))}})(s,r,e,t))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(e){if("message"in e){if("combine"!==e.message.type)throw new Zr("message must be a combine message",{code:it});const t=e.message.body;return{url:t.url??"",secret:t.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}return{url:e.url,secret:e.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(e,t){return e===ct||e===dt?new Jr(t??"authentication failed",{code:e}):e===gt||e===ft?new Wr(t??"connection unavailable",{code:e}):107===e||110===e||205===e||500===e||e===nt||e===it?new Zr(t??"invalid parameter",{code:e}):e===Dt?new Hr(t??"message recall time limit reached",e):e===zt?new Hr(t??"message update failed",e):e===Ut?new Zr(t??"operation unsupported",{code:e}):new Hr(t??"message action failed",e)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(e,t){return new Zr(e,{code:it,details:{fields:[{path:t,message:e,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("ChatManager is not bound to event context",{code:nt});return this.eventContext}getClientOrThrow(){if(!this.client)throw new Zr("ChatManager is not bound to client",{code:nt});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:Dw,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireConnectedClient(){const e=this.getClientOrThrow();if(e.getConnectionState()!==s)throw new Wr("client is not connected",{code:gt});return e}getCurrentUserIdOrThrow(){const e=this.getClientOrThrow().getCurrentUserId();if(!e)throw new Jr("user is not logged in",{code:ct});return e}buildMessageSenderOrThrow(){const e=this.getClientOrThrow(),t=this.getCurrentUserIdOrThrow(),r=e.getCacheManager()?.getUserInfoSummaries([t],!1)[0];return{userId:t,nickname:r?.nickname,avatarUrl:r?.avatarUrl}}async hydrateGroupMessageReadUsers(e,t){const r=this.getClientOrThrow();if(!r.isUserInfoSyncEnabled()||0===t.users.length)return t;const s=r.getCacheManager(),n=await LI({groupId:e,users:t.users.map(e=>e.user),includeNameCard:!0,cacheManager:s,fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoReadCapability(r);return t?await t.getUserInfoByUserId({userIds:e}):[]},hydrateGroupNamecards:async(e,t)=>{const s=this.getGroupNamecardHydrationCapability(r);s&&await s.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))}});return this.dispatchFetchedUserInfoUpdates(r,n.fetchedUserInfos),{...t,users:t.users.map(e=>{const t=n.usersById.get(e.userId)??e.user;return{...e,user:t}})}}getUserInfoReadCapability(e){const t=e.getManagerByCapability("userInfo:read");return t&&"function"==typeof t.getUserInfoByUserId?t:null}getGroupNamecardHydrationCapability(e){const t=e.getManagerByCapability("group:namecard");return t&&"function"==typeof t.hydrateMessageProfileGroupNamecards?t:null}dispatchFetchedUserInfoUpdates(e,t){if(0===t.length)return;const r=e.getCurrentUserId(),s=t.find(e=>e.userId===r),n=t.filter(e=>e.userId!==r);s&&e.dispatchOwnInfoUpdated(s),e.dispatchUserInfoUpdated(n),t.length>0&&e.refreshConversationDisplayFromUserInfos(t.map(e=>({userId:e.userId})),"profile")}async executeRestOperation(e){try{return await e()}catch(t){throw this.mapRestError(t)}}mapRestError(e){return e instanceof Zr||e instanceof Jr||e instanceof Wr||e instanceof Vr?e:e instanceof es?new Vr(e.message,{code:e.code,details:e.details}):e instanceof ts||e instanceof Hr?e:new Hr(String(e),Gr)}};qw.key="chatManager";let Bw=qw;class $w{constructor(e,t){this.chatThreadId=e,this.manager=t}getInfo(){return this.manager.getChatThreadInfo({chatThreadId:this.chatThreadId})}refresh(){return this.getInfo()}join(){return this.manager.joinChatThread({chatThreadId:this.chatThreadId})}leave(){return this.manager.leaveChatThread({chatThreadId:this.chatThreadId})}destroy(){return this.manager.destroyChatThread({chatThreadId:this.chatThreadId})}updateName(e){return this.manager.updateChatThreadName({chatThreadId:this.chatThreadId,name:e.name})}getMemberList(e={}){return this.manager.getChatThreadMemberList({chatThreadId:this.chatThreadId,...e})}removeMember(e){return this.manager.removeChatThreadMember({chatThreadId:this.chatThreadId,memberId:e.memberId})}}const Fw=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),Gw=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),jw=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw Fw(t);return e.trim()},zw=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw Gw(t,`${t} must be a string`);return e},Kw=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw Gw(t,`${t} must be an integer between 1 and 50`);return e},Hw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},Vw=e=>Bl(e)?e:null,Ww=e=>{const t=Vw(e);return t?.data??e},Jw=e=>{const t=Vw(e);if(Array.isArray(t?.entities))return t.entities;const r=Ww(e);if(Array.isArray(r))return r;const s=Vw(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},Zw=e=>{const t=Vw(e),r=Vw(t?.data),s=Vw(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof s?.cursor?s.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},Qw=e=>{const t=Vw(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const s="number"==typeof t.timestamp?t.timestamp:0,n=t.payload,i="string"==typeof n?$l(n,{}):Vw(n)??{},o=Array.isArray(i.bodies)?i.bodies:[],a=Vw(o[0])??{};return{msgId:r,type:("string"==typeof a.type?a.type:void 0)??("string"==typeof i.type?i.type:void 0)??"",body:a,timestamp:s}},Yw=e=>{const t=Vw(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0)??("string"==typeof t.chatThreadId?t.chatThreadId:void 0),s=("string"==typeof t.parentId?t.parentId:void 0)??("string"==typeof t.groupId?t.groupId:void 0)??("string"==typeof t.group_id?t.group_id:void 0),n="string"==typeof t.name?t.name:"";return r&&s&&n?{chatThreadId:r,parentId:s,name:n,ownerId:"string"==typeof t.owner?t.owner:void 0,memberCount:"number"==typeof t.affiliationsCount?t.affiliationsCount:"number"==typeof t.affiliations_count?t.affiliations_count:void 0,messageCount:"number"==typeof t.messageCount?t.messageCount:"number"==typeof t.message_count?t.message_count:void 0,createdAt:"number"==typeof t.created?t.created:"number"==typeof t.createTimestamp?t.createTimestamp:void 0,lastMessage:Qw(t.lastMessage??t.last_message)}:null},Xw=e=>({items:Jw(e).map(e=>Yw(e)).filter(e=>null!==e),cursor:Zw(e)}),eC=async(e,t,r)=>{const s=Hw(t),n=jw(r,"chatThreadId");return(e=>{const t=Ww(e),r=Array.isArray(t)?t[0]:t,s=Yw(r);if(!s)throw Gw("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},tC=async(e,t,r)=>{const s=Hw(t),n=jw(r.chatThreadId,"params.chatThreadId"),i=Kw(r.pageSize,"params.pageSize"),o=zw(r.cursor,"params.cursor"),a=gb({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:Jw(d=c).map(e=>{if("string"==typeof e)return{memberId:e};const t=Vw(e);if(!t)return null;const r=("string"==typeof t.memberId?t.memberId:void 0)??("string"==typeof t.user?t.user:void 0)??("string"==typeof t.username?t.username:void 0);return r?{memberId:r,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null}).filter(e=>null!==e),cursor:Zw(d)};var d},rC=async(e,t,r)=>{const s=Hw(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw Fw("params.chatThreadIds");if(r.chatThreadIds.length>20)throw Gw("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>jw(e,`params.chatThreadIds[${t}]`)),i=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:Jw(i).map(e=>{const t=Vw(e);if(!t)return null;const r=("string"==typeof t.chatThreadId?t.chatThreadId:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0);return r?{chatThreadId:r,lastMessage:Qw(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},sC=Gb(jb,{common:{},apis:{createChatThread:{range:"4,110,201,210,301,303,606",localErrors:{createChatThread:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getJoinedChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getJoinedChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadInfo:{range:"110,201,210,301,303,606",localErrors:{getChatThreadInfo:{validation_invalid:{code:110,retryable:!1}},getInfo:{validation_invalid:{code:110,retryable:!1}},refresh:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},joinChatThread:{range:"4,110,201,210,301,303,606",localErrors:{joinChatThread:{validation_invalid:{code:110,retryable:!1}},join:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},leaveChatThread:{range:"110,201,210,301,303,606",localErrors:{leaveChatThread:{validation_invalid:{code:110,retryable:!1}},leave:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},destroyChatThread:{range:"110,201,210,301,303,606",localErrors:{destroyChatThread:{validation_invalid:{code:110,retryable:!1}},destroy:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},updateChatThreadName:{range:"110,201,210,301,303,606",localErrors:{updateChatThreadName:{validation_invalid:{code:110,retryable:!1}},updateName:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadMemberList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadMemberList:{validation_invalid:{code:110,retryable:!1}},getMemberList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},removeChatThreadMember:{range:"110,201,210,301,303,606",localErrors:{removeChatThreadMember:{validation_invalid:{code:110,retryable:!1}},removeMember:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadLastMessageList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadLastMessageList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}}}}),nC=class{constructor(){this.capabilities=["rawNotify:chatThread"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.registry=new Map}bind(e,t){this.client=e,this.eventContext=t??null,this.registry.clear()}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}handleRawNotify(e){if("chatThread"!==e.type)return;const t=this.buildChatThreadPublicEvent(e.payload);t&&this.eventContext?.dispatch?.(t.eventName,t.payload)}getChatThread(e){const t=e.trim();if(0===t.length)throw new Zr("chatThreadId is required",{code:nt,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const r=this.registry.get(t);if(r)return r;const s=new $w(t,this);return this.registry.set(t,s),s}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=Hw(t),n=jw(r.parentId,"params.parentId"),i=jw(r.name,"params.name"),o=jw(r.messageId,"params.messageId"),a=await e.post(`/${s.orgName}/${s.appName}/thread?resource=${s.encodedResource}`,{name:i,msg_id:o,group_id:n,owner:t.userId},{operation:"createChatThread"}),c=Vw(Ww(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw Gw("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:d}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=Hw(t),n=jw(r.parentId,"params.parentId"),i=Kw(r.pageSize,"params.pageSize"),o=zw(r.cursor,"params.cursor"),a=gb({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return Xw(c)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const s=Hw(t),n=Kw(r.pageSize,"params.pageSize"),i=zw(r.cursor,"params.cursor"),o=gb({limit:String(n),cursor:i}),a="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${s.encodedUserId}?${o.toString()}`:`/${s.orgName}/${s.appName}/threads/user/${s.encodedUserId}?${o.toString()}`,c=await e.get(a,{operation:"getJoinedChatThreadList"});return Xw(c)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return eC(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Hw(t),n=jw(r,"chatThreadId");await e.post(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/user/${s.encodedUserId}/join?resource=${s.encodedResource}`,void 0,{operation:"joinChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async leaveChatThread(e){return this.runOperation("leaveChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Hw(t),n=jw(r,"chatThreadId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/user/${s.encodedUserId}/quit?resource=${s.encodedResource}`,{operation:"leaveChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async destroyChatThread(e){return this.runOperation("destroyChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Hw(t),n=jw(r,"chatThreadId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.encodedResource}`,{operation:"destroyChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async updateChatThreadName(e){return this.runOperation("updateChatThreadName",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Hw(t),n=jw(r.chatThreadId,"params.chatThreadId"),i=jw(r.name,"params.name");await e.put(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.encodedResource}`,{name:i},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return tC(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Hw(t),n=jw(r.chatThreadId,"params.chatThreadId"),i=jw(r.memberId,"params.memberId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users/${encodeURIComponent(i)}?resource=${s.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return rC(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new Zr("ChatThreadManager is not bound to client",{code:nt,details:{fields:[{path:"chatThreadManager.client",message:"ChatThreadManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("ChatThreadManager is not bound to event context",{code:nt,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:sC,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}async runOperation(e,t){try{return await t()}catch(r){if(r instanceof Hr)throw r;const t=r instanceof Error?r.message:String(r);throw new Hr(`ChatThreadManager ${e} failed: ${t}`,Gr)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",s="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!s)return null;const n="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,i="string"==typeof t.name?t.name:void 0,o="number"==typeof t.message_count?t.message_count:void 0,a=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,c="number"==typeof t.timestamp?t.timestamp:0,d="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:s,name:i??"",messageId:n,messageCount:o,lastMessage:a};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,thread:u,timestamp:c}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,messageCount:o,lastMessage:a,thread:u,timestamp:c}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:s,operatorId:d,timestamp:c}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:s,operatorId:d,memberId:t.userIds?.[0],timestamp:c}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};nC.key="chatThreadManager";let iC=nC;class oC{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const aC=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],cC=e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},dC=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),uC=e=>({userId:e}),lC=(e,t,r)=>{const s={userId:r};for(const n of aC){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},hC=async(e,t)=>{const r=cC(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,dC(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,uC(o));return s},pC=e=>Bl(e)?e:null,mC=e=>"string"==typeof e?e:void 0,fC=e=>{const t=mC(e)?.trim();return t||void 0},gC=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}},yC=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},vC=e=>{const t=pC(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},bC=e=>{const t=pC(e);return t?pC(t.data)?t.data:t:null},IC=(e,t)=>{const r=pC(e),s=r&&pC(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return gC(n[0])},wC=e=>fC(e.chatRoomId)??fC(e.chatroomid)??fC(e.id)??"",CC=e=>mC(e.name)??mC(e.title)??mC(e.groupname)??"",SC=e=>uC(e),TC=(e,t)=>{const r=pC(e);if(!r)return null;const s=wC(r);if(!s)return null;const n=t?.stripOwnerAppKeyPrefix?(e=>{if(!e)return;const t=e.indexOf("_");return t<0?e:e.slice(t+1)})(fC(r.owner)):fC(r.owner);return{chatRoomId:s,name:CC(r),owner:n?SC(n):void 0,memberCount:gC(r.memberCount)??gC(r.affiliations_count),disabled:yC(r.disabled)}},_C=(e,t)=>{const r=(e=>{const t=pC(e);return t?gC(t.count):void 0})(e),s=vC(e).map(e=>TC(e,t)).filter(e=>null!==e),n=IC(e,"pagenum"),i=IC(e,"pagesize");return{items:s,pageNum:n,pageSize:i,total:r,hasMore:void 0!==r&&void 0!==n&&void 0!==i?n*i<r:void 0}},RC=(e,t)=>{const r=vC(e),s=pC(r[0])??bC(e)??{},n=TC(s)??{chatRoomId:wC(s),name:CC(s)},i=((e,t)=>{if(!t)return;if(fC(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const s of r){const e=pC(s);if(e){if(fC(e.owner)===t)return"owner";if(fC(e.admin)===t)return"admin";if(fC(e.member)===t)return"member"}}})(s,t),o=gC(s.muteExpireAt)??gC(s.mute_expire)??gC(s.expire),a=yC(s.inAllowlist)??yC(s.white)??yC(s.in_whitelist),c=yC(s.muted);return{...n,description:mC(s.description),maxMembers:gC(s.maxMembers)??gC(s.maxusers)??gC(s.max_users),createdAt:gC(s.createdAt)??gC(s.created),ext:mC(s.ext)??mC(s.custom),announcement:mC(s.announcement),permissionType:i,currentUserStatus:void 0!==a||void 0!==c||void 0!==o||void 0!==i?{inAllowlist:a,muted:c,muteExpireAt:o,permissionType:i}:void 0}},AC=e=>vC(e).map(e=>fC(e)).filter(e=>Boolean(e)).map(e=>SC(e)),MC=(e,t)=>{const r=bC(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=pC(r.errorKeys)??{},i={};for(const[o,a]of Object.entries(n))"string"==typeof a&&(i[o]={code:UC(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:i}},EC=e=>{const t=pC(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],i=[];return s.forEach(e=>{const t=pC(e),r=(e=>{const t=pC(e);if(!t)return null;const r=fC(t.user),s=fC(t.chatRoomId)??fC(t.chatroomid)??fC(t.id),n=mC(t.action),i=yC(t.result);return r&&s&&void 0!==n&&void 0!==i?{chatRoomId:s,user:SC(r),action:n,reason:mC(t.reason),...i?{}:{reason:mC(t.reason)??"failed"}}:null})(e);if(!r||!t)return;yC(t.result)?n.push(r):i.push(r)}),{succeeded:n,failed:i}},UC=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?Fr:e.includes("is not part of you")?Ir:e.includes("is not Legal")||e.includes("is not exist")?nt:fr,NC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},kC=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),OC=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),xC=(e,t)=>`/${e.orgName}/${e.appName}${t}`,LC=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw OC(t,`${t} must be a string`);return e}},PC=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw OC(t,`${t} must be a number`);return e}},DC=(e,t)=>{const r=gb();"number"==typeof e?.pageNum&&r.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&r.set("pagesize",String(e.pageSize));const s=r.toString();return s?`?${s}`:""},qC=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw kC(t);return e.trim()},BC=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw kC(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw OC(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw kC(t);return r},$C=(e,t)=>BC(e,t),FC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i={},o=LC(r.name,"params.name"),a=LC(r.description,"params.description"),c=PC(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.maxusers=c),0===Object.keys(i).length)throw kC("params");const d=xC(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=bC(e)??{};return{nameUpdated:yC(t.groupname),descriptionUpdated:yC(t.description),maxMembersUpdated:yC(t.maxusers)}})(await e.put(d,i,{operation:"updateChatRoomInfo"}))},GC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=gb();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const r=t.toString();return r?`?${r}`:""})(r)}`);return(e=>{const t=[];for(const n of vC(e)){const e=pC(n);if(!e)continue;const r=fC(e.owner),s=fC(e.admin),i=fC(e.member),o=r??s??i;o&&t.push({user:SC(o),role:r?"owner":s?"admin":"member",joinedAt:gC(e.joinedAt)??gC(e.joined_time)})}const r=pC(e),s=r?fC(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(i,{operation:"getChatRoomMemberList"}))},jC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/admin`),o=await e.get(i,{operation:"getChatRoomAdminList"});return AC(o)},zC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=gb();i.set("version","v3"),"number"==typeof r.pageNum&&i.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&i.set("pagesize",String(r.pageSize));const o=xC(s,`/chatrooms/${encodeURIComponent(n)}/mute?${i.toString()}`);return(e=>{const t=vC(e);if(t.every(e=>"string"==typeof e))return AC(e).map(e=>({user:e}));const r=[];for(const s of t){const e=pC(s);if(!e)continue;const t=fC(e.user)??fC(e.member)??fC(e.owner)??fC(e.admin);t&&r.push({user:SC(t),muteExpire:gC(e.muteExpire)??gC(e.expire)??gC(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(o,{operation:"getChatRoomMuteList"}))},KC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=bC(e)??{};return{muted:yC(t.muted)??yC(t.value)??Boolean(t.data),muteExpireAt:gC(t.muteExpireAt)??gC(t.expire)??gC(t.mute_expire)}})(await e.get(i,{operation:"isCurrentUserMutedInChatRoom"}))},HC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=DC(r),o=i?"&":"",a=xC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return AC(c).map(e=>({user:e}))},VC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),o=await e.get(i,{operation:"getChatRoomAllowlist"});return AC(o).map(e=>({user:e}))},WC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=bC(e)??{};return yC(t.value)??yC(t.white)??!1})(await e.get(i,{operation:"checkIfInChatRoomAllowList"}))},JC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=bC(e)??{};return{announcement:mC(t.announcement)??""}})(await e.get(i,{operation:"getChatRoomAnnouncement"}))},ZC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=bC(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(i,{keys:r.keys?$C(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},QC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw OC(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw kC(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw OC(t,`${t} contains invalid key`);if("string"!=typeof r)throw OC(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:o=!0,isForced:a=!1}=r,c=a?"/forced":"",d=xC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:i,autoDelete:o?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return MC(u,n)},YC={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},XC=(e,t,r)=>new Zr(e,{code:"required"===r?nt:it,details:{fields:[{path:t,message:e,rule:r}]}}),eS=(e,t)=>{if("string"!=typeof e)throw XC(`${t} must be a string`,t,"invalid_format");return e},tS=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw XC(`${t} must be a string, number, or boolean`,t,"invalid_format")},rS=(e,t="attribute")=>{const r=YC[e];if(!r)throw XC(`${t} is invalid`,t,"invalid_format");return r},sS=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw XC(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=eS(i,`${t}[${n}]`).trim();e&&(s.has(e)||(s.add(e),r.push(e)))}if(0===r.length)throw XC(`${t} is required`,t,"required");return r},nS=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw XC(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=eS(i,`${t}[${n}]`);if(!(e in YC))throw XC(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw XC(`${t} is required`,t,"required");return r},iS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/get`},oS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},aS=e=>({targets:sS(e)}),cS=e=>!!Bl(e)&&("nickname"in e||"avatarurl"in e||"avatarUrl"in e||"mail"in e||"phone"in e||"gender"in e||"sign"in e||"birth"in e||"ext"in e),dS=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!Bl(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},uS=(e,t)=>{const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r},lS=(e,t)=>{const r=(e=>{const t=new Map,r=Bl(e)?e:null;if(r?.data&&Bl(r.data))for(const[s,n]of Object.entries(r.data))cS(n)&&t.set(s,n);return dS(r?.entities,t),dS(r?.data&&Bl(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=Bl(e)?e:null;if(!r?.lastModified||!Bl(r.lastModified))return t;for(const[s,n]of Object.entries(r.lastModified))"number"==typeof n&&t.set(s,n);return t})(e),n=[];for(const i of t){const e=r.get(i);e&&n.push({profile:uS(i,e),lastModified:s.get(i)})}return n},hS=(e,t)=>lS(e,t).map(e=>e.profile),pS=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,eS(r,s)]):e.push([t,String(tS(r,s))]))},mS=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),fS={onChatRoomDestroyed:Se,onMembersJoined:Te,onMembersExited:_e,onRemovedFromChatRoom:Re,onMuteListAdded:Ae,onMuteListRemoved:Me,onAllowListAdded:Ee,onAllowListRemoved:Ue,onAllMemberMuteStateChanged:Ne,onAdminAdded:ke,onAdminRemoved:Oe,onOwnerChanged:xe,onAnnouncementChanged:Le,onChatRoomInfoChanged:Pe,onAttributesUpdate:De,onAttributesRemoved:qe},gS=Gb(jb,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomInfo:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},destroyChatRoom:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},joinChatRoom:{range:"4,705,704,707",errors:{exceed_limit:{code:4,httpStatus:403,retryable:!1},members_full:{code:704,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"member list is full"},user_in_blocklist:{code:707,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"is in the blacklist"},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},leaveChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMemberList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addChatRoomMembers:{range:"110,204,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAdminList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAdmin:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomAdmin:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMuteList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteChatRoomMembers:{range:"110,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},isCurrentUserMutedInChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomBlocklist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},blockChatRoomMembers:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},unblockChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAllowlist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addUsersToChatRoomAllowlist:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeUsersFromChatRoomAllowlist:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},checkIfInChatRoomAllowList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAnnouncement:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomAnnouncement:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomSharedFileList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},deleteChatRoomSharedFile:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAttributes:{range:"110,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},setChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}}}}),yS=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=new Map}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){const r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{const r=fS[e];return r&&t?[[r,t]]:[]}));this.eventContext?.addEventHandler(e,r)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("chatroom"!==e.type)return;const t=e.payload,r=await this.buildIncomingEventPayload(t.eventName,t);if(!r)return;const s=fS[t.eventName];s&&this.eventContext?.dispatch?.(s,r)}async buildIncomingEventPayload(e,t){const r=t.payload,s=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(e){case"onChatRoomDestroyed":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName};case"onMembersJoined":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),s),ext:r.ext};case"onMembersExited":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),s)};case"onRemovedFromChatRoom":return{reason:r.reasonCode??0,chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,participant:this.pickEventUser(r.participantId,s)};case"onMuteListAdded":return{chatRoomId:r.chatRoomId,mutes:this.pickEventMuteEntries(r.userIds,r.muteExpire,s),muteExpire:r.muteExpire};case"onMuteListRemoved":return{chatRoomId:r.chatRoomId,mutes:this.pickEventUsers(r.userIds,s)};case"onAllowListAdded":case"onAllowListRemoved":return{chatRoomId:r.chatRoomId,allowlist:this.pickEventUsers(r.userIds,s)};case"onAllMemberMuteStateChanged":return{chatRoomId:r.chatRoomId,isMuted:Boolean(r.isMuted)};case"onAdminAdded":case"onAdminRemoved":return{chatRoomId:r.chatRoomId,admin:this.pickEventUser(r.adminId,s)};case"onOwnerChanged":return{chatRoomId:r.chatRoomId,newOwner:this.pickEventUser(r.newOwnerId,s),oldOwner:this.pickEventUser(r.oldOwnerId,s)};case"onAnnouncementChanged":return{chatRoomId:r.chatRoomId,announcement:r.announcement??""};case"onChatRoomInfoChanged":return{chatRoomId:r.chatRoomId,chatRoomInfo:await this.resolveChatRoomDetailForEvent(r)};case"onAttributesUpdate":return{chatRoomId:r.chatRoomId,attributes:r.attributes??{},from:this.pickEventUser(r.from,s)};case"onAttributesRemoved":return{chatRoomId:r.chatRoomId,keyList:r.keyList??[],from:this.pickEventUser(r.from,s)};default:return null}}async getChatRoomList(e={}){return this.runOperation("getChatRoomList",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r={})=>{const s=NC(t),n=xC(s,`/chatrooms${DC(r)}`),i=await e.get(n,{operation:"getChatRoomList"});return _C(i)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(e){this.requireClient();const t=e.trim();if(0===t.length)throw new Zr("chatRoomId is required",{code:nt,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const r=this.chatRoomRegistry.get(t);if(r)return r;const s=new oC(t,this);return this.chatRoomRegistry.set(t,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true`),o=await e.get(i,{operation:"getChatRoomInfo"});return RC(o,t.userId)})(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return FC(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=qC(e.chatRoomId,"params.chatRoomId"),s=this.normalizeOptionalString(e.ext,"params.ext"),n=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:s,leaveOtherRooms:n})).chatRoomInfo??{}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=qC(e.chatRoomId,"params.chatRoomId");await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await GC(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(r.items)}})}async removeMembers(e){return this.runOperation("removeMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeChatRoomMembers"});return EC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await jC(this.getRestClient(t),t,e);return this.hydrateUserInfos(r)})}async addAdmin(e){return this.runOperation("addAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=qC(r.userId,"params.userId"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/admin?resource=${s.encodedResource}`);await e.post(o,{newadmin:i},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=qC(r.userId,"params.userId"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/admin/${encodeURIComponent(i)}?resource=${s.encodedResource}`);await e.delete(o,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await zC(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async muteMembers(e){return this.runOperation("muteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=PC(r.duration,"params.duration"),a=xC(s,`/chatrooms/${encodeURIComponent(n)}/mute?resource=${s.encodedResource}`);await e.post(a,{usernames:i,mute_duration:o},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/mute/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.post(i,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return KC(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await HC(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async blockMembers(e){return this.runOperation("blockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=1===i.length,a=xC(s,o?`/chatrooms/${encodeURIComponent(n)}/blocks/users/${encodeURIComponent(i[0]??"")}?resource=${s.encodedResource}`:`/chatrooms/${encodeURIComponent(n)}/blocks/users?resource=${s.encodedResource}`),c=await e.post(a,o?void 0:{usernames:i},{operation:"blockChatRoomMembers"});return EC(c)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async unblockMembers(e){return this.runOperation("unblockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"unblockChatRoomMembers"});return EC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await VC(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async addUsersToAllowlist(e){return this.runOperation("addUsersToAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(o,{usernames:i},{operation:"addUsersToChatRoomAllowlist"});return EC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async removeUsersFromAllowlist(e){return this.runOperation("removeUsersFromAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeUsersFromChatRoomAllowlist"});return EC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return WC(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return JC(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=LC(r.announcement,"params.announcement");if(void 0===i)throw kC("params.announcement");const o=xC(s,`/chatrooms/${encodeURIComponent(n)}/announcement?resource=${s.encodedResource}`);await e.post(o,{announcement:i},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return ZC(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await QC(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async removeAttributes(e){return this.runOperation("removeAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=$C(r.keys,"params.keys"),{isForced:o=!1}=r,a=o?"/forced":"",c=xC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:i},operation:"removeChatRoomAttributes"});return MC(d,n)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Si(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`ChatRoomManager ${e} failed: ${t.message}`,Gr):new Hr(`ChatRoomManager ${e} failed`,Gr)}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new Hr(e.message,e.code)}return e}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:gS,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 Hr("ChatRoomManager is not bound to client",nt);return this.client}normalizeOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw new Zr(`${t} must be a string`,{code:it,details:{fields:[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]}});return e}}normalizeOptionalBoolean(e,t){if(void 0!==e){if("boolean"!=typeof e)throw new Zr(`${t} must be a boolean`,{code:it,details:{fields:[{path:t,message:`${t} must be a boolean`,rule:"invalid_format"}]}});return e}}getCacheManager(){return this.client?.getCacheManager()??null}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 hC(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Si("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=cC(e),s=await hC(r,t);return r.map(e=>lC(void 0,s.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Si("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=aS(e),s=await this.getRestClient(t).request(iS(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return hS(s,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return lC(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>lC(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){Si("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:lC(e.user,r.get(e.user.userId),e.user.userId)}))}async hydrateActionListResult(e){return{succeeded:await this.hydrateEntriesWithUsers(e.succeeded),failed:await this.hydrateEntriesWithUsers(e.failed)}}async hydrateSummaryOwners(e){const t=e.map(e=>e.owner?.userId).filter(e=>"string"==typeof e),r=await this.resolveUserInfoMap(t);return e.map(e=>e.owner?.userId?{...e,owner:lC(e.owner,r.get(e.owner.userId),e.owner.userId)}:e)}async hydrateChatRoomDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveUserInfoMap([e.owner.userId]);return{...e,owner:lC(e.owner,t.get(e.owner.userId),e.owner.userId)}}};yS.key="chatRoomManager";let vS=yS;const bS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},IS=e=>Bl(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):[],wS=(e,t)=>{if(!Array.isArray(e.userIds)||0===e.userIds.length)throw new Zr(`${t} is required`,{code:nt,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});const r=e.userIds.map((e,r)=>{if("string"!=typeof e)throw new Zr(`${t}[${r}] must be a string`,{code:it,details:{fields:[{path:`${t}[${r}]`,message:"userId must be a string",rule:"invalid_format"}]}});return e.trim()}),s=(e=>{const t=[],r=new Set;for(const s of e)s&&!r.has(s)&&(r.add(s),t.push(s));return t})(r);if(0===s.length)throw new Zr(`${t} is required`,{code:nt,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});return s.length!==r.length&&Bl(e),s},CS=async(e,t)=>{const r=bS(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return IS(n).map(e=>({userId:e}))},SS=async(e,t,r)=>{const s=bS(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`,i=await e.post(n,{usernames:r},{operation:"addUsersToBlocklist"});return{succeeded:IS(i).map(e=>({userId:e})),failed:[]}},TS={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 _S=!1,RS=null;const AS=()=>RS||(_S||(Vc.util.Long=mo,Vc.configure(),_S=!0),Sd(),RS=Vc.Root.fromJSON(TS),Cd(RS),RS),MS=e=>"number"==typeof e?e:mo.isLong(e)?e.toNumber():0,ES=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:MS(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:MS(t.protocolVersion)}};class US{encodeRequest(e){const t=AS().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=rI){const t=AS().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Yb,status:e})).finish()}decode(e){const t=AS(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case Qb:return{type:Qb};case Yb:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Yb,status:MS(r.status)}}case eI:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:eI,header:ES(r.header),data:Array.isArray(r.data)?r.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:MS(t.createdAt),updatedAt:MS(t.updatedAt),metadataUpdatedAt:MS(t.metadataUpdatedAt)}})(e)):[],cursor:MS(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:MS(r.responseType)||sI}}case tI:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:tI,header:ES(r.header),code:"string"==typeof r.code?r.code:"",message:"string"==typeof r.message?r.message:"Unknown roster error"}}default:return{type:"number"==typeof r.type?r.type:Zb}}}}class NS{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(e){const t=e.header?.requestId;if(t&&t!==this.requestId)throw new Hr("Roster response requestId mismatched",Tr,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:t}});if(this.completed)throw new Hr("Roster response received after completion",Sr,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new Hr("Roster response type changed in same session",Sr,{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 Hr("Roster cursor duplicated",Sr,{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===nI?"incremental":"full",version:this.version,pages:this.pages}}}const kS=e=>e.type===eI,OS=e=>"message"in e&&"code"in e;class xS{constructor(e){this.codec=new US,this.sharedSession=e}async sync(e){const t=new NS(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(e,t){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:e.header.requestId,encode:()=>{const r=this.buildAttemptRequest(e,t.getNextCursor());return this.codec.encodeRequest(r)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:kS(t)||OS(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===Qb)return void(await r.send(this.codec.encodePong()));if(kS(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(OS(e))throw(e=>{const t=e.header?.requestId,r=r=>({stage:"sync_page",serverCode:e.code,requestId:t,retryable:r});switch(Number.parseInt(e.code,10)){case oI:return new Jr(e.message,{code:dt,details:r(!1)});case aI:return new Hr(e.message,Fr,{details:r(!0)});case iI:return new Hr(e.message,nt,{details:r(!1)});case cI:return new Hr(e.message,it,{details:r(!1)});case dI:return new Hr(e.message,fr,{details:r(!0)});case uI:return new Hr(e.message,Cr,{details:r(!1)});default:return new Hr(e.message,Cr,{details:r(!0)})}})(e);return}catch(s){throw s instanceof Hr?s:new Hr("Roster frame decode failed",Tr,{details:{stage:"response_decode",cause:s instanceof Error?s.message:String(s)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const LS=e=>e.versionState.version?"incremental":"full",PS=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?LS(s):"full",version:n}:t.requiresSync||"complete"!==s.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===s.cacheMeta.cacheIntegrity&&n?{decision:"incremental",version:t.version||n}:{decision:"full",version:t.version||n}:{decision:"skip",version:t.version||n}},DS=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{}}},qS=e=>{const t=(e=>{if(!(e instanceof Hr&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},BS=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),$S=e=>{Si("Contact sync duration",e)};class FS{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(),t=Date.now();let r;this.dependencies.onStart();try{const s=await this.dependencies.queryMetadata(e.versionState.version);if(r=PS({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void $S({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(qS(s)){const r=PS({metadataFailed:!0,state:e}),n=s instanceof Hr?s:new Hr("Contact metadata request failed",wr,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:BS("metadata",n.code,n.message,!1)}),void $S({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:e.versionState.version,stage:"metadata",hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}if(r=PS({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:BS("metadata",wr,s instanceof Error?s.message:String(s),!0)}),void $S({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const s=await this.dependencies.getSyncUrls(),n=this.dependencies.buildRosterRequest({decision:r.decision,version:e.versionState.version}),i=await new xS(this.dependencies.getSharedSyncSession()).sync({urls:s,request:n}),o=(e=>{const t=[];for(const r of e)for(const e of r.data){const r=DS(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:r.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:r.nickname,avatarUrl:r.avatarUrl,sign:r.sign,ext:r.ext}})}return t})(i.pages),a=this.dependencies.applySyncResult({mode:i.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:i.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),$S({outcome:"finish",decision:r.decision,durationMs:Date.now()-t,version:i.version,source:"sync",changed:a.changed,hasUsableSnapshot:a.snapshot.complete})}catch(s){const n=s instanceof Hr?s:new Hr("Contact sync failed",Cr,{details:{stage:"sync_page",cause:s instanceof Error?s.message:String(s)}}),i=n.details??{},o="string"==typeof i.stage?i.stage:"sync_page";this.dependencies.onFinish({error:BS(o,n.code,n.message,!0)}),$S({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:o,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const GS={items:[],loaded:!1,source:"server"},jS=Gb(jb,{common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,223",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:223,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}}),zS=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=GS,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=GS,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"),r=this.validateOptionalString(e.message,"params.message"),s=this.getRestContextOrThrow(),n=this.getRestClient(s);Ci("ContactManager addContact",{userId:t,hasMessage:"string"==typeof r&&r.length>0}),await(async(e,t,r)=>{const s=bS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/apply?resource=${s.encodedResource}`;await e.post(n,{usernames:[r.userId],reason:r.message??""},{operation:"addContact"})})(n,s,{userId:t,message:r})})}async deleteContact(e){return this.runOperation("deleteContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Ci("ContactManager deleteContact",{userId:t}),await(async(e,t,r)=>{const s=bS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.delete(n,{operation:"deleteContact"})})(s,r,{userId:t});const n=this.client?.getCacheManager()?.removeContact(t);Ci("ContactManager deleteContact patched cache",{userId:t,changed:n?.changed??!1})})}async acceptContactInvite(e){return this.runOperation("acceptContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Ci("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,r)=>{const s=bS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/accept/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"acceptContactInvite"})})(s,r,{userId:t}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(e){return this.runOperation("declineContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Ci("ContactManager declineContactInvite",{userId:t}),await(async(e,t,r)=>{const s=bS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/decline/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"declineContactInvite"})})(s,r,{userId:t})})}async setContactRemark(e){return this.runOperation("setContactRemark",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.validateRemark(e.remark,"params.remark"),s=this.getRestContextOrThrow(),n=this.getRestClient(s);Ci("ContactManager setContactRemark",{userId:t,remarkLength:r.length}),await(async(e,t,r)=>{const s=bS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.put(n,{remark:r.remark},{operation:"setContactRemark"})})(n,s,{userId:t,remark:r});const i=this.client?.getCacheManager()?.updateContactRemark(t,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),Ci("ContactManager setContactRemark patched cache",{userId:t,changed:i?.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 r=await this.enrichBlocklistUsers(await CS(t,e));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},Ci("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=wS(e,"params.userIds"),s=this.getRestClient(t);Ci("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await SS(s,t,r),i=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(i),{succeeded:i,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=wS(e,"params.userIds"),s=this.getRestClient(t);Ci("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length}),await(async(e,t,r)=>{const s=bS(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`;await e.request(n,{method:"DELETE",body:{usernames:r},operation:"removeUserFromBlocklist"})})(s,t,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Si(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`ContactManager ${e} failed: ${t.message}`,Gr):new Hr(`ContactManager ${e} failed`,Gr)}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 ly(e.restBaseUrl,{errorMap:jS,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=GS)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const r of e)t.set(r.userId,r);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 r of e)t.delete(r);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 r=e.trim();if(!r)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return r}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(e,t){const r=t.some(e=>"invalid_format"===e.rule)?it:nt;return new Zr(e,{code:r,details:{fields:t}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await Vb(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 Si("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=aS(e),s=await this.getRestClient(t).request(iS(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return hS(s,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 FS(e)}};zS.key="contactManager";let KS=zS;class HS{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 VS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},WS=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),JS=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),ZS=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw WS(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw JS(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw WS(t);return r},QS=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw WS(t);return e.trim()},YS=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw JS(t,`${t} must be a string`);return e}},XS=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw JS(t,`${t} must be a boolean`);return e}},eT=(e,t)=>`/${e.orgName}/${e.appName}${t}`,tT=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),rT=e=>{const t=gb();"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}`:""},sT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Ql(e),r=Hl(t[0]),s=Yl(e)??r;return{groupId:s&&th(s)||r&&th(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?ZS(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"}))},nT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i=eT(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfo"});return sh(o)},iT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i={},o=YS(r.name,"params.name"),a=YS(r.description,"params.description"),c=YS(r.avatar,"params.avatar"),d=YS(r.ext,"params.ext"),u=XS(r.public,"params.public"),l=XS(r.joinApprovalRequired,"params.joinApprovalRequired"),h=XS(r.allowInvites,"params.allowInvites"),p=XS(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw JS(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.avatar=c),void 0!==d&&(i.custom=d),void 0!==u&&(i.public=u),void 0!==l&&(i.membersonly=l),void 0!==h&&(i.allowinvites=h),void 0!==p&&(i.invite_need_confirm=p),void 0!==m&&(i.maxusers=m),0===Object.keys(i).length)throw WS("params");const f=eT(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,i,{operation:"updateGroupInfo"})},oT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/users${(e=>{const t=gb();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 i of Ql(e)){const e=Hl(i);if(!e)continue;const r=Wl(e.owner),s=Wl(e.admin),n=Wl(e.member),o=r??s??n;if(!o)continue;const a=Jl(e.joinedAt)??Jl(e.joined_time);t.push({user:nh(o),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=Xl(e,"pagenum"),s=Xl(e,"pagesize"),n=eh(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},aT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/admin`),i=await e.get(n,{operation:"getGroupAdminList"});return ih(i)},cT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i=rT(r),o=i?"&":"",a=eT(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${o}${i.replace("?","")}`);return(e=>{const t=[];for(const r of Ql(e)){const e=Wl(r);if(e){t.push({user:nh(e)});continue}const s=Hl(r);if(!s)continue;const n=Wl(s.user);if(!n)continue;const i=Jl(s.expire);t.push({user:nh(n),...void 0===i?{}:{muteExpire:i}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},dT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i=rT(r),o=i?"&":"",a=eT(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return ih(c).map(e=>({user:e}))},uT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/white/users`),i=await e.get(n,{operation:"getGroupAllowlist"});return ih(i).map(e=>({user:e}))},lT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=Yl(e)??{};return{announcement:Vl(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},hT=async(e,t,r)=>{const s=VS(t),n=gb();n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const i=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=Xl(e,"pagenum"),r=Xl(e,"pagesize"),s=eh(e,r);return{items:Ql(e).map(e=>oh(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(i,{operation:"getGroupSharedFileList"}))},pT=(e,t)=>{const r=VS(e);return eT(r,`/chatgroups/${encodeURIComponent(QS(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(QS(t.fileId,"params.fileId"))}`)},mT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i=QS(r.userId,"params.userId"),o=((e,t,r)=>{if(t!==e.userId)return null;const s=Object.entries(r);if(0===s.length)return null;let n;for(const[i,o]of s){if(!tT.has(i)||"string"!=typeof o)return null;if(void 0!==n){if(n!==o)return null}else n=o}return void 0===n?null:{nameCard:n}})(t,i,r.memberAttributes);if(o){const t=eT(s,`/sdk/chatgroups/${encodeURIComponent(n)}/nameCard`);return await e.put(t,o,{operation:"setGroupMemberAttributes"})}const a=eT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(n)}/user/${encodeURIComponent(i)}?resource=${s.encodedResource}`);return await e.put(a,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},fT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/get`);return(e=>{const t=Yl(e)??{},r=Hl(t.data)??t,s={};for(const[n,i]of Object.entries(r)){const e=Hl(i);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:ZS(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},gT=e=>{const t=Bl(e)?e:{},r=t.data,s=Bl(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return yT(n);const i=Bl(r)?r:t,o=Bl(i.namecards)?i.namecards:i,a={};for(const[c,d]of Object.entries(o)){if("string"==typeof d){a[c]={namecard:d};continue}if(!Bl(d))continue;const e=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof e&&(a[c]={namecard:e,namecardUpdateTime:vT(d)})}return a},yT=e=>{const t={};return e.forEach(e=>{if(!Bl(e))return;const r=e.username??e.userId??e.userid??e.user_id,s=e.name_card??e.namecard??e.nameCard??e.groupNamecard??e.group_namecard??e.group_name_card;"string"==typeof r&&r.trim()&&"string"==typeof s&&(t[r.trim()]={namecard:s,namecardUpdateTime:vT(e)})}),t},vT=e=>Hh("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),bT=e=>{if(Bl(e))return Hh("number"==typeof e.timestamp?e.timestamp:"number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0)};class IT{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 wT=e=>({...e}),CT=e=>({...e,owner:e.owner?{...e.owner}:void 0});class ST{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=wT({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=CT({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=wT(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?wT(this.summarySnapshot):this.detailSnapshot?wT(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?CT(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 TT{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 _T{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new TT,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 ST(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 s=t?.items.find(t=>t.groupId===e);return s?{...s}: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 s={...r,...t,groupId:e};return this.joinedGroupById.set(e,s),this.mergeSummary(this.toGroupSummary(s)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...s}:{...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 RT=0,AT=5,MT=12,ET=13,UT=0,NT=1,kT=2,OT=0,xT=1,LT=2,PT=3,DT=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(s=e.role,s===UT?"owner":s===NT?"admin":s===kT?"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===OT?"DEFAULT":r===xT?"ALL":r===LT?"AT":r===PT?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},qT=e=>e.updatedAt??0,BT=(e,t)=>{if(!e)return!0;return qT(t)>=qT(e)},$T={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 FT=null,GT=!1;const jT=()=>FT||(GT||(Vc.util.Long=mo,Vc.configure(),GT=!0),Sd(),FT=Vc.Root.fromJSON($T),Cd(FT),FT),zT=e=>jT().lookupType(e),KT=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(mo.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}},HT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:KT(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:KT(t.protocol_version)??KT(t.protocolVersion)??0}};class VT{constructor(){this.requestType=zT("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=zT("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=zT("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 s=this.tryDecodeRequest(e);return s||{type:RT}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=KT(t.type);return r!==MT?null:{type:r,header:HT(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:KT(t.last_sync_time)??KT(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=KT(t.type);return r!==ET?null:{type:r,header:HT(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:KT(t.members_count)??KT(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:KT(t.role),mute_expiration:KT(t.mute_expiration)??KT(t.muteExpiration),remind_type:KT(t.remind_type)??KT(t.remindType),create_at:KT(t.create_at)??KT(t.createAt),update_at:KT(t.update_at)??KT(t.updateAt),joined_timestamp:KT(t.joined_timestamp)??KT(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:KT(t.last_sync_finished_ts)??KT(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=KT(t.type);return r!==AT?null:{type:r,header:HT(t.header),code:KT(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class WT{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==ET)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new Hr("Joined groups response received after completion",fr,{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 Hr("Joined groups final batch missing lastSyncFinishedTs",fr,{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 JT=e=>e.type===ET,ZT=e=>e.type===AT;class QT{constructor(e){this.codec=new VT,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new WT(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,t,r){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:t,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,t,r.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:JT(t)||ZT(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(JT(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(ZT(e))throw(e=>{const t=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new Hr(e.message,nt,{details:t("request_send",!1)});case 1602:return new Hr(e.message,fr,{details:t("batch_merge",!0)});case 1002:return new Jr(e.message,{code:dt,details:t("auth",!1)});case 1003:return new Hr(e.message,Fr,{details:t("server_limit",!0)});default:return new Hr(e.message,fr,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof Hr?t:new Hr("Joined groups frame decode failed",Tr,{details:{stage:"response_decode",cause:t instanceof Error?t.message:String(t)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class YT{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const r=await this.dependencies.getSyncUrls();if(0===r.length)throw new Hr("Group sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect",retryable:!0}});const s=this.buildRequest(),n=await new QT(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),i=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=DT(r);e&&t.push(e)}return t})(e.groups)),o=this.dependencies.getRuntimeSnapshot(),a=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=new Map;for(const n of e.incomingItems){const e=r.get(n.groupId)??t.get(n.groupId);BT(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=Of;return{items:Array.from(s?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:s?"limited":"synced",limited:s,storageLimit:kf,serverLimit:Of,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:o?.items??[],incomingItems:i,lastSyncFinishedTs:n.lastSyncFinishedTs}),c=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(a);const d=this.dependencies.getRuntimeSnapshot()??a;try{await c.commitJoinedGroupPreviewSnapshot(d);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(d,e)&&await c.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw o&&this.dependencies.applyRuntimeSnapshot(o),new Xr("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}Si("Group sync finished",{durationMs:Date.now()-e,itemCount:a.items.length,limited:a.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof Hr?e:new Hr("Group sync failed",fr,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},s=r.serverCode;return{dataType:"group",code:t.code,stage:(n=r.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:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof s||"string"==typeof s?s:void 0};var n})(t);Si("Group sync failed",{durationMs:Date.now()-e,stage:r.stage,code:r.code,serverCode:r.serverCode}),this.dependencies.onFinish({status:"failed",error:r})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:t,appName:r}=Qn(e.appKey);return{type:MT,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const XT=Gb(jb,{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:{}}}}),e_=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 _T,this.groupEventSync=new IT(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,s=await this.buildIncomingEventPayload(r,t);if(!s)return;if(this.eventContext?.dispatch?.(r,s),r!==we)return;if(!("attribute"in s)||!("user"in s))return;const n=this.extractGroupNamecard(s.attribute);if(void 0===n||!s.user?.userId)return;const i=this.client?.getCurrentUserId();s.user.userId!==i&&(this.getCacheManager()?.setGroupNamecards([{groupId:s.groupId,userId:s.user.userId,namecard:n,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(Ce,{groupId:s.groupId,userId:s.user.userId,namecard:n}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await sT(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const t=e.trim();if(0===t.length)throw new Zr("groupId is required",{code:nt,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const r=this.groupRegistry.get(t);if(r)return r;this.getGroupSummaryForHandle(t),this.getGroupRepository().getOrCreate(t);const s=new HS(t,this);return this.groupRegistry.set(t,s),s}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await nT(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(s)})}async getGroupInfoList(e){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=VS(t),n=ZS(r.groupIds,"params.groupIds"),i=eT(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfoList"});return(Bl(o)&&Array.isArray(o.data)?o.data:[]).map(e=>sh({data:[e]}))})(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailsUsers(r);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,s=e===ne?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case Q:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case Y:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case X:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case ee:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case te:case re:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case se:return{groupId:r.groupId,groupName:r.groupName};case ne:return{groupId:r.groupId,groupName:r.groupName??s};case ie:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case oe:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case ae:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case ce:case de:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case ue:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case le:case he:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case pe:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case me:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,n)};case fe:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,n)};case ge:return{groupId:r.groupId,announcement:r.announcement??""};case ye:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case ve:return{groupId:r.groupId,fileId:r.fileId??""};case be:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case Ie:{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 we: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 t=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},r=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:t,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(n){Si("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:n})}if(r)return r;const s=this.getGroupRepository().getDetailSnapshot(e.groupId);return s||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await iT(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:QS(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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}?version=v3&resource=${s.encodedResource}`);await e.delete(n,{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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/quit?resource=${s.encodedResource}`);await e.delete(n,{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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/apply?resource=${s.encodedResource}`);await e.post(n,{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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:ZS(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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:QS(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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:QS(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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{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 oT(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 s=VS(t),n=ZS(r.userIds,"params.userIds"),i=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await aT(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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/admin?resource=${s.encodedResource}`);await e.post(n,{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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`);await e.delete(n,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await cT(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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:ZS(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 s=VS(t),n=ZS(r.userIds,"params.userIds"),i=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/mute/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/ban?resource=${s.encodedResource}`);await e.post(n,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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/ban?resource=${s.encodedResource}`);await e.delete(n,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await dT(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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:ZS(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 s=VS(t),n=ZS(r.userIds,"params.userIds"),i=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/blocks/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await uT(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 s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:ZS(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 s=VS(t),n=ZS(r.userIds,"params.userIds"),i=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/white/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(e){return this.runOperation("checkIfInGroupAllowList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof i?i:Bl(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async checkIfInGroupMuteList(e){return this.runOperation("checkIfInGroupMuteList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=VS(t),n=eT(s,`/sdk/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof i?i:Bl(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return lT(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/announcement?resource=${s.encodedResource}`);await e.post(n,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await hT(this.getRestClient(t),t,e),s=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?s.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const t=this.getRestContextOrThrow(),r=pT(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=Gn({file:e.file}),n=nm({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=n?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const o=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[Ml]:Al()},source:s.source,timeoutMs:3e5,onProgress:e.onFileUploadProgress}));if(!o)throw new Error("platform upload adapter is unavailable");if(o.status<200||o.status>=300)throw new Hr("uploadGroupSharedFile failed",mr,{details:{status:o.status}});i?.finish({code:o.status,success:!0}),n?.finish({code:0,success:!0}),e.onFileUploadComplete?.(o.body)}catch(o){const t=ll(o);throw i?.finish({code:t.code,success:!1,description:t.message}),n?.finish({code:t.code,success:!1,description:t.message}),t.code===$r&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(t),t}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(QS(r.fileId,"params.fileId"))}?resource=${s.encodedResource}`);await e.delete(n,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let t,r;try{const s=this.getRestContextOrThrow(),n=`${s.restBaseUrl}${pT(s,e)}`;t=nm({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:n});const i=this.requireClient().getRequestAdapter();if(!i)throw new Hr("downloadGroupSharedFile request adapter is unavailable",hr);const o=await i.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[Ml]:Al()},responseType:"arraybuffer",timeoutMs:6e4});if(o.status<200||o.status>=300)throw r?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),new Hr("downloadGroupSharedFile failed",mr);r?.finish({code:o.status,success:!0}),t?.finish({code:0,success:!0});const a="undefined"!=typeof Blob?new Blob([o.data]):o.data;e.onFileDownloadComplete?.(a)}catch(s){const n=s instanceof Hr?s.code:hr,i=s instanceof Error?s.message:String(s);throw r?.finish({code:n,success:!1,description:i}),t?.finish({code:n,success:!1,description:i}),e.onFileDownloadError?.(s),s}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await mT(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return fT(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,t){0!==t.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const r=this.getRestContextOrThrow(),s=t.map(e=>e.userId),n=await(async(e,t,r)=>{const s=VS(t),n=eT(s,`/sdk/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/nameCard/batch/get`),i=await e.post(n,{members:ZS(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:gT(i),responseTimestamp:bT(i)}})(this.getRestClient(r),r,{groupId:e,userIds:s}),i=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),o=[],a=new Set;for(const[t,d]of Object.entries(n.items))a.add(t),o.push({groupId:e,userId:t,namecard:d.namecard,namecardUpdateTime:i.get(t)??d.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const c=s.filter(e=>!a.has(e));c.length>0&&"number"==typeof n.responseTimestamp&&o.push(...c.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:n.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(o);for(const e of o)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(Ce,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});c.length>0&&"number"!=typeof n.responseTimestamp&&Si("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:s,missingUserIds:c})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Si(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`GroupManager ${e} failed: ${t.message}`,Gr):new Hr(`GroupManager ${e} failed`,Gr)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:XT,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 Hr("GroupManager is not bound to client",nt);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new _T),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new IT(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 s=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return s||void 0}async resolveMembersJoinedGroupName(e){const t=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(t)return t;const r=this.resolveUsableGroupName(e.groupName,e.groupId);if(r)return r;const s=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await nT(this.getRestClient(t),t,{groupId:e.groupId}),n=this.getGroupRepository();if(n.getSessionKey()!==s)return;return n.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(n){return void Si("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,t,r){if(t.userId!==e)return;const s=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof s)return;const n=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof n&&Si("Group member attributes update response missing server update time",{groupId:t.groupId,userId:t.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:t.groupId,userId:t.userId,namecard:s,namecardUpdateTime:n,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const s of r){const e=Hh("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!Bl(e))return;r.push(e.lastModified,e.last_modified,e.timestamp,e.updateTime,e.update_time,e.updatedAt,e.updated_at);const s=e.data;if(Bl(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];Bl(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;Bl(n)&&r.push(n[t])}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 Kl(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Si("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return zl(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>zl(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:zl(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case ue:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case pe:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case X:case ie:return void this.addCurrentUserJoinedGroupFromEvent(t);case me:{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 fe: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 se:case ne:return void(await this.removeJoinedGroupLocal(t.groupId));case oe:case ae:case ce:case de:case le:case he:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case me:case fe:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const s=this.getGroupRepository().getDetailSnapshot(e);return!(!s||"number"!=typeof s.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,s.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(s){return Si("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(s){return Si("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 s=await nT(this.getRestClient(r),r,{groupId:e}),n=this.getGroupRepository();if(n.getSessionKey()!==t)return!1;n.mergeDetail(s);const i=n.getJoinedGroupSummarySnapshot(e);if(!i)return!1;const o=n.mergeJoinedGroupSummary(e,{...i.name||!s.name?{}:{name:s.name},...void 0!==i.description||void 0===s.description?{}:{description:s.description},...void 0!==i.memberCount||void 0===s.memberCount?{}:{memberCount:s.memberCount},...void 0!==i.role||void 0===s.role?{}:{role:s.role},...void 0!==i.disabled||void 0===s.disabled?{}:{disabled:s.disabled},...i.ownerId||!s.owner?.userId?{}:{ownerId:s.owner.userId},...void 0!==i.avatarUrl||void 0===s.avatarUrl?{}:{avatarUrl:s.avatarUrl},...void 0!==i.muteAllMembers||void 0===s.muteAllMembers?{}:{muteAllMembers:s.muteAllMembers},...void 0!==i.createdAt||void 0===s.createdAt?{}:{createdAt:s.createdAt},...void 0!==i.joinedAt||void 0===s.joinedAt?{}:{joinedAt:s.joinedAt}});if(o){this.persistJoinedGroupSnapshot(o);const t=n.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:s.name||t.name,avatarUrl:s.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void Si("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{Si("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=aS(e),s=await this.getRestClient(t).request(iS(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return hS(s,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(MI(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await LI({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 xI({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(),s=e.find(e=>e.userId===r),n=e.filter(e=>e.userId!==r);s&&t.dispatchOwnInfoUpdated?.(s),t.dispatchUserInfoUpdated?.(n),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new YT(e)}};e_.key="groupManager";let t_=e_;const r_=Gb(jb,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),s_=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(e){return this.runOperation("publishPresence",async()=>{this.validateDescription(e.customStatus);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${t.clientResource}/1`,o={ext:e.customStatus};Ci("Call publishPresence",{customStatus:e.customStatus}),await r.request(i,{method:"POST",body:o,operation:"publishPresence"})})}async subscribePresence(e){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(e.userIds),this.validateExpiry(e.expiry);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${e.expiry}`,o={usernames:e.userIds};Ci("Call subscribePresence",{userIds:e.userIds,expiry:e.expiry});const a=await r.request(i,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(a)})}async unsubscribePresence(e){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`;Ci("Call unsubscribePresence",{userIds:e.userIds}),await r.request(i,{method:"DELETE",body:e.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(e){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(e.pageNum,e.pageSize);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/sublist?pageNum=${e.pageNum}&pageSize=${e.pageSize}`;Ci("Call getSubscribedPresenceList",{pageNum:e.pageNum,pageSize:e.pageSize});const o=await r.request(i,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(e){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`,o={usernames:e.userIds};Ci("Call getPresenceStatus",{userIds:e.userIds});const a=await r.request(i,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(a)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Si(`PresenceManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`PresenceManager ${e} failed: ${t.message}`,Gr):new Hr(`PresenceManager ${e} failed`,Gr)}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("PresenceManager is not bound to event context",{code:nt,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new Zr("PresenceManager is not bound to client",{code:nt,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:r_,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,n]of Object.entries(e))if("number"==typeof n&&Number.isFinite(n))r[s]=Math.trunc(n);else if("string"==typeof n&&n.trim().length>0){const e=Number(n);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new Zr("Invalid parameters",{code:it,details:{fields:e}})}};s_.key="presenceManager";let n_=s_;const i_=Gb(jb,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),o_=["singleChat","groupChat"],a_=["ALL","AT","NONE","DEFAULT"],c_=["ALL","AT","NONE"],d_=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),u_=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}`;Ci("Call uploadPushToken",{deviceId:e.deviceId,notifierName:e.notifierName}),await r.request(i,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken"})})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);Ci("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await r.request(i,{method:"PUT",body:o,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/user/${e.userId}`;Ci("Call getGlobalSilentMode");const i=await t.request(n,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(i))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);Ci("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const c=await r.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(c),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}`;Ci("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;Ci("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),o=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${s}/${n}/users/${t.userId}/notification?user=${i}&group=${o}`;Ci("Call getConversationSilentModes",{count:e.conversationList.length});const c=await r.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(c,"user"),u=this.resolveConversationRuleMap(c,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:u[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/language`;Ci("Call setPushLanguage",{language:e.language}),await r.request(i,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/language`;Ci("Call getPushLanguage");const i=await t.request(n,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(i,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{Ci("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),r=Vg({items:t.getCacheManager()?.loadSessionList()??[],pageSize:e.pageSize,cursor:e.cursor});return Promise.resolve(r)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof Hr?e:e instanceof Error?new Hr(`PushManager operation failed: ${e.message}`,Gr):new Hr("PushManager operation failed",Gr)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:i_,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new Hr("PushManager is not bound to client",nt);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!o_.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,r)=>{this.validateConversationId(e.conversationId,`${t}[${r}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${r}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!d_(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!c_.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,r){const s=Object.keys(e).find(e=>!r.includes(e));if(s)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${s}`,message:`${s} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!d_(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const r=this.parseRuleView(e);return r?t?{...this.toRuleViewFromFallback(t),...r}:r:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!d_(e))return null;const t={},r=this.normalizeRemindType(e.type);null!==r&&(t.remindType=r);const s=e.ignoreDuration;"number"==typeof s&&Number.isInteger(s)&&s>0&&(t.expireTimestamp=s);const n=e.ignoreInterval;if("string"==typeof n){const e=this.parseInterval(n);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const r=Number(t[1]),s=Number(t[2]),n=Number(t[3]),i=Number(t[4]);return Number.isInteger(r)&&Number.isInteger(s)&&Number.isInteger(n)&&Number.isInteger(i)?r<0||r>23||n<0||n>23||s<0||s>59||i<0||i>59?null:{startTime:{hours:r,minutes:s},endTime:{hours:n,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(d_(e.data)){const r=e.data[t];if(d_(r))return r}const r=e[t];return d_(r)?r:{}}resolveSilentModeRuleSource(e){if(!d_(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return d_(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":a_.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(d_(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const r=e.data.language;if("string"==typeof r&&r.length>0)return r}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(e,t){return new Zr(e,{code:it,details:{fields:t}})}};u_.key="pushManager";let l_=u_;const h_=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},p_=(e,t="params.userIds")=>sS(e,t),m_=e=>{const t=p_(e);if(t.length>100)throw((e,t,r,s=it)=>new Zr(e,{code:s,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",Fr);return{usernames:t}},f_=(e,t)=>{const r=(e=>p_(e))(t);return`${h_(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},g_=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},y_=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],v_=Gb(jb,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),b_=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,r=t?.getCacheManager();if(!t||!r||!t.getCurrentUserId())return;const s=e.payload,n=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=g_(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const i=r.applyUserInfoNotifyPatch(n);if(!i.applied)return void Ci("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:i.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const o=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(Z,{userInfo:i.record.profile,contact:o})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=aS(sS(e.userIds,"params.userIds")),n=iS(t);Ci("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const i=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),o=this.normalizeFetchEnvelope(i,s.targets);return this.writeCache(o),o.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(n=sS(e.userIds,"params.userIds"),i=nS(e.attributes,"params.attributes"),{targets:sS(n),properties:nS(i).map(e=>rS(e,"params.attributes"))});var n,i;const o=iS(t);Ci("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const a=await r.request(o,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),c=this.normalizeFetchEnvelope(a,s.targets);return this.writeCache(c),c.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>h_(e))(t),n=m_(e.userIds);Ci("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=f_(t,e.userIds);Ci("UserInfoManager unsubscribeUsersInfo",{userIds:sS(e.userIds,"params.userIds")}),await r.request(s,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),r=(e=>h_(e))(e);Ci("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>{const t=[];if(pS(t,"nickname",e.nickname,"params.nickname"),pS(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),pS(t,"mail",e.mail,"params.mail"),pS(t,"phone",e.phone,"params.phone"),pS(t,"gender",e.gender,"params.gender"),pS(t,"sign",e.sign,"params.sign"),pS(t,"birth",e.birth,"params.birth"),pS(t,"ext",e.ext,"params.ext"),0===t.length)throw XC("params must include at least one updatable field","params","required");return mS(t)})(e),n=oS(t);Ci("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),o=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([o]),this.dispatchSelfUpdate(o.profile),o.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=((e,t)=>{const r=rS(e,"attribute"),s=tS(t,"value");if("gender"!==r&&"string"!=typeof s)throw XC("value must be a string","value","invalid_format");return mS([[r,String(s)]])})(e,t),i=oS(r);Ci("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const o=await s.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),a=this.normalizeUpdateEnvelope(o,r.userId,{userId:r.userId,[e]:t});return this.writeCache([a]),this.dispatchSelfUpdate(a.profile),a.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof Hr?t:(Si("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new Hr(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new Zr("UserInfoManager is not bound to client",{code:nt,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:v_,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return lS(e,t)}normalizeUpdateEnvelope(e,t,r){const s=Bl(e)?e:null,n=(s&&Bl(s.data)?s.data:null)??(s&&this.looksLikeUserInfoAttributes(s)?s:null),i=s&&"number"==typeof s.lastModified?s.lastModified:void 0;return{profile:n?this.toUserInfo(t,n):{userId:t,...r??{}},lastModified:i}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(e){return!!Bl(e)&&("nickname"in e||"avatarurl"in e||"avatarUrl"in e||"mail"in e||"phone"in e||"gender"in e||"sign"in e||"birth"in e||"ext"in e)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of y_)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return y_.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=Hh(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:r,lastSyncAt:t,lastAccess:t,lastUpdate:e.lastModified??t}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};b_.key="userInfoManager";let I_=b_;return e.AuthenticationError=Jr,e.CONVERSATION_MARK={MARK_0:0,MARK_1:1,MARK_2:2,MARK_3:3,MARK_4:4,MARK_5:5,MARK_6:6,MARK_7:7,MARK_8:8,MARK_9:9,MARK_10:10,MARK_11:11,MARK_12:12,MARK_13:13,MARK_14:14,MARK_15:15,MARK_16:16,MARK_17:17,MARK_18:18,MARK_19:19},e.CacheManager=sg,e.ChatClient=pI,e.ChatManager=Bw,e.ChatRoom=oC,e.ChatRoomManager=vS,e.ChatThread=$w,e.ChatThreadManager=iC,e.ConnectionError=Wr,e.ContactManager=KS,e.Group=HS,e.GroupManager=t_,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.MessageReceiveError=Yr,e.MessageSendError=Qr,e.NetworkError=Vr,e.PresenceManager=n_,e.PushManager=l_,e.RUNTIME_PLATFORMS=Mi,e.RestBusinessError=ts,e.RestTransportError=es,e.SDKError=Hr,e.StorageError=Xr,e.StreamMessageStatus=rt,e.UploadError=rs,e.UserInfoManager=I_,e.ValidationError=Zr,e.createPlatformAdapter=ul,e.detectRuntimePlatform=(e,t)=>co(t,e).platform,e.isSDKError=function(e){if(e instanceof Hr)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},e.setLogLevel=function(e){yi instanceof gi&&yi.setLevel(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});