easemob-websdk 5.0.0-beta.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/chunks/index-CK3GHdGU.cjs +1 -0
- package/chunks/index-CjofwvEQ.js +1 -0
- package/index.cjs +1 -1
- package/index.js +2 -2
- package/managers/group/index.cjs +1 -1
- package/managers/group/index.js +1 -1
- package/package.json +1 -1
- package/rest/error-maps/group.d.ts +17 -2
- package/chunks/index-Bv_iHYxI.cjs +0 -1
- package/chunks/index-CtDL3xV2.js +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",B="onMultiDeviceContact",G="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",Be="onMembersJoined",Ge="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,Bt=507,Gt=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,Br=1,Gr=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,Bs=0,Gs=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]:Gr,[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]:Gr,[In]:Gr,[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":Gr,"not in group or chatroom white list":Bt,nonroster:Yt,"group is disabled":br,"roaming is not open":$t,"Sorry, message does not exist":nt,"Sorry, edit limit reached":Gr,"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",Gr],["no permission to recall message",ut]],kn={[Tn]:Gr,[_n]:Gr,[Rn]:Gr,"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?Gt:e===nn?mt:void 0}})(e,t);return{code:r??(An[e]??Fr),retryable:!Mn.has(e)}},On={[Gr]:"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",[Bt]:"The user is not in the group or chat room allowlist",[Gt]:"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}},Bn=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=Gn({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}},Gn=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 Bn({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=Gn({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=Gn({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=Gn({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",Bo="PLATFORM_SOCKET_FAILED",Go="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=e=>{if(e)return e;const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,r={..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}};if(!t)return r;try{Object.assign(t,r)}catch{}return t},Wo={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},Jo=(e,t)=>{if("object"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Zo=e=>(e=>Jo(e,"canIUse")&&Jo(e,"getSystemInfo"))(e)||(e=>Jo(e,"request")&&Jo(e,"connectSocket"))(e),Qo=(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,Yo=e=>{const t=e?.miniGlobal;return Zo(t)?t:e},Xo=e=>void 0!==e.window&&void 0!==e.document,ei=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),ti=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;try{if(!Jo(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},ri=e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return Wo[r]??Eo.UNIAPP}catch{return Eo.UNIAPP}return Xo(e)?Eo.WEB:Eo.UNIAPP},si=(e,t)=>{const r=e??Vo();if(t){const e=t===Eo.UNIAPP||ti(r);return{platform:t,hostPlatform:e?ri(r):t,framework:e?"uniapp":Xo(r)?"web":"native",global:e&&r.uni?r.uni:Yo(Qo(r,t))??r}}return ti(r)?{platform:Eo.UNIAPP,hostPlatform:ri(r),framework:"uniapp",global:r.uni??r}:Zo(r.swan)?{platform:Eo.BAIDU_MINIAPP,hostPlatform:Eo.BAIDU_MINIAPP,framework:"native",global:Yo(r.swan)??r.swan}:Zo(r.tt)?{platform:Eo.TOUTIAO_MINIAPP,hostPlatform:Eo.TOUTIAO_MINIAPP,framework:"native",global:Yo(r.tt)??r.tt}:Zo(r.dd)?{platform:Eo.DINGTALK_MINIAPP,hostPlatform:Eo.DINGTALK_MINIAPP,framework:"native",global:Yo(r.dd)??r.dd}:Zo(r.my)?{platform:Eo.ALIPAY_MINIAPP,hostPlatform:Eo.ALIPAY_MINIAPP,framework:"native",global:Yo(r.my)??r.my}:Zo(r.wx)?{platform:Eo.WECHAT_MINIAPP,hostPlatform:Eo.WECHAT_MINIAPP,framework:"native",global:Yo(r.wx)??r.wx}:Zo(r.qq)?{platform:Eo.QQ_MINIAPP,hostPlatform:Eo.QQ_MINIAPP,framework:"native",global:Yo(r.qq)??r.qq}:Zo(r.jd)?{platform:Eo.JD_MINIAPP,hostPlatform:Eo.JD_MINIAPP,framework:"native",global:Yo(r.jd)??r.jd}:Zo(r.ks)?{platform:Eo.KUAISHOU_MINIAPP,hostPlatform:Eo.KUAISHOU_MINIAPP,framework:"native",global:Yo(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:Xo(r)?Eo.ELECTRON_RENDERER:Eo.ELECTRON_MAIN,hostPlatform:Xo(r)?Eo.ELECTRON_RENDERER:Eo.ELECTRON_MAIN,framework:"electron",global:r}:ei(r)||Xo(r)?{platform:Eo.WEB,hostPlatform:Eo.WEB,framework:ei(r)?"worker":"web",global:r}:{platform:Eo.UNKNOWN,hostPlatform:Eo.UNKNOWN,framework:"native",global:r}},ni=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,oi=["request","upload","socket","proto"],ii=(e,t=oi)=>{const r=((e,t=oi)=>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 ai=null;try{ai=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 ci(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function di(e){return!0===(e&&e.__isLong__)}function ui(e){var t=Math.clz32(e&-e);return e?31-t:t}ci.prototype.__isLong__,Object.defineProperty(ci.prototype,"__isLong__",{value:!0}),ci.isLong=di;var li={},hi={};function pi(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=hi[e])?s:(r=fi(e,0,!0),n&&(hi[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=li[e])?s:(r=fi(e,e<0?-1:0,!1),n&&(li[e]=r),r)}function mi(e,t){if(isNaN(e))return t?Ti:Si;if(t){if(e<0)return Ti;if(e>=Ii)return Ei}else{if(e<=-wi)return Ui;if(e+1>=wi)return Mi}return e<0?mi(-e,t).neg():fi(e%bi|0,e/bi|0,t)}function fi(e,t,r){return new ci(e,t,r)}ci.fromInt=pi,ci.fromNumber=mi,ci.fromBits=fi;var gi=Math.pow;function yi(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?Ti:Si;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 yi(e.substring(1),t,r).neg();for(var n=mi(gi(r,8)),o=Si,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=mi(gi(r,a));o=o.mul(d).add(mi(c))}else o=(o=o.mul(n)).add(mi(c))}return o.unsigned=t,o}function vi(e,t){return"number"==typeof e?mi(e,t):"string"==typeof e?yi(e,t):fi(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}ci.fromString=yi,ci.fromValue=vi;var bi=4294967296,Ii=bi*bi,wi=Ii/2,Ci=pi(1<<24),Si=pi(0);ci.ZERO=Si;var Ti=pi(0,!0);ci.UZERO=Ti;var _i=pi(1);ci.ONE=_i;var Ri=pi(1,!0);ci.UONE=Ri;var Ai=pi(-1);ci.NEG_ONE=Ai;var Mi=fi(-1,2147483647,!1);ci.MAX_VALUE=Mi;var Ei=fi(-1,-1,!0);ci.MAX_UNSIGNED_VALUE=Ei;var Ui=fi(0,-2147483648,!1);ci.MIN_VALUE=Ui;var ki=ci.prototype;ki.toInt=function(){return this.unsigned?this.low>>>0:this.low},ki.toNumber=function(){return this.unsigned?(this.high>>>0)*bi+(this.low>>>0):this.high*bi+(this.low>>>0)},ki.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Ui)){var t=mi(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=mi(gi(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}},ki.getHighBits=function(){return this.high},ki.getHighBitsUnsigned=function(){return this.high>>>0},ki.getLowBits=function(){return this.low},ki.getLowBitsUnsigned=function(){return this.low>>>0},ki.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ui)?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},ki.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},ki.isZero=function(){return 0===this.high&&0===this.low},ki.eqz=ki.isZero,ki.isNegative=function(){return!this.unsigned&&this.high<0},ki.isPositive=function(){return this.unsigned||this.high>=0},ki.isOdd=function(){return!(1&~this.low)},ki.isEven=function(){return!(1&this.low)},ki.equals=function(e){return di(e)||(e=vi(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},ki.eq=ki.equals,ki.notEquals=function(e){return!this.eq(e)},ki.neq=ki.notEquals,ki.ne=ki.notEquals,ki.lessThan=function(e){return this.comp(e)<0},ki.lt=ki.lessThan,ki.lessThanOrEqual=function(e){return this.comp(e)<=0},ki.lte=ki.lessThanOrEqual,ki.le=ki.lessThanOrEqual,ki.greaterThan=function(e){return this.comp(e)>0},ki.gt=ki.greaterThan,ki.greaterThanOrEqual=function(e){return this.comp(e)>=0},ki.gte=ki.greaterThanOrEqual,ki.ge=ki.greaterThanOrEqual,ki.compare=function(e){if(di(e)||(e=vi(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},ki.comp=ki.compare,ki.negate=function(){return!this.unsigned&&this.eq(Ui)?Ui:this.not().add(_i)},ki.neg=ki.negate,ki.add=function(e){di(e)||(e=vi(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,fi((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},ki.subtract=function(e){return di(e)||(e=vi(e)),this.add(e.neg())},ki.sub=ki.subtract,ki.multiply=function(e){if(this.isZero())return this;if(di(e)||(e=vi(e)),ai)return fi(ai.mul(this.low,this.high,e.low,e.high),ai.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Ti:Si;if(this.eq(Ui))return e.isOdd()?Ui:Si;if(e.eq(Ui))return this.isOdd()?Ui:Si;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(Ci)&&e.lt(Ci))return mi(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,fi((l&=65535)<<16|(h&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},ki.mul=ki.multiply,ki.divide=function(e){if(di(e)||(e=vi(e)),e.isZero())throw Error("division by zero");var t,r,s;if(ai)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?fi((this.unsigned?ai.div_u:ai.div_s)(this.low,this.high,e.low,e.high),ai.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Ti:Si;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Ti;if(e.gt(this.shru(1)))return Ri;s=Ti}else{if(this.eq(Ui))return e.eq(_i)||e.eq(Ai)?Ui:e.eq(Ui)?_i:(t=this.shr(1).div(e).shl(1)).eq(Si)?e.isNegative()?_i:Ai:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(Ui))return this.unsigned?Ti:Si;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=Si}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:gi(2,n-48),i=mi(t),a=i.mul(e);a.isNegative()||a.gt(r);)a=(i=mi(t-=o,this.unsigned)).mul(e);i.isZero()&&(i=_i),s=s.add(i),r=r.sub(a)}return s},ki.div=ki.divide,ki.modulo=function(e){return di(e)||(e=vi(e)),ai?fi((this.unsigned?ai.rem_u:ai.rem_s)(this.low,this.high,e.low,e.high),ai.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},ki.mod=ki.modulo,ki.rem=ki.modulo,ki.not=function(){return fi(~this.low,~this.high,this.unsigned)},ki.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},ki.clz=ki.countLeadingZeros,ki.countTrailingZeros=function(){return this.low?ui(this.low):ui(this.high)+32},ki.ctz=ki.countTrailingZeros,ki.and=function(e){return di(e)||(e=vi(e)),fi(this.low&e.low,this.high&e.high,this.unsigned)},ki.or=function(e){return di(e)||(e=vi(e)),fi(this.low|e.low,this.high|e.high,this.unsigned)},ki.xor=function(e){return di(e)||(e=vi(e)),fi(this.low^e.low,this.high^e.high,this.unsigned)},ki.shiftLeft=function(e){return di(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fi(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):fi(0,this.low<<e-32,this.unsigned)},ki.shl=ki.shiftLeft,ki.shiftRight=function(e){return di(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fi(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):fi(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},ki.shr=ki.shiftRight,ki.shiftRightUnsigned=function(e){return di(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fi(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):fi(32===e?this.high:this.high>>>e-32,0,this.unsigned)},ki.shru=ki.shiftRightUnsigned,ki.shr_u=ki.shiftRightUnsigned,ki.rotateLeft=function(e){var t;return di(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?fi(this.high,this.low,this.unsigned):e<32?(t=32-e,fi(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),fi(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},ki.rotl=ki.rotateLeft,ki.rotateRight=function(e){var t;return di(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?fi(this.high,this.low,this.unsigned):e<32?(t=32-e,fi(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),fi(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},ki.rotr=ki.rotateRight,ki.toSigned=function(){return this.unsigned?fi(this.low,this.high,!1):this},ki.toUnsigned=function(){return this.unsigned?this:fi(this.low,this.high,!0)},ki.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},ki.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]},ki.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]},ci.fromBytes=function(e,t,r){return r?ci.fromBytesLE(e,t):ci.fromBytesBE(e,t)},ci.fromBytesLE=function(e,t){return new ci(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},ci.fromBytesBE=function(e,t){return new ci(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&&(ci.fromBigInt=function(e,t){return fi(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},ci.fromValue=function(e,t){return"bigint"==typeof e?ci.fromBigInt(e,t):vi(e,t)},ki.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var Ni,Oi,xi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Li={exports:{}},Pi={},Di={};function $i(){if(Oi)return Ni;return Oi=1,Ni=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))}})},Ni}var qi,Bi,Gi,Fi,ji,zi,Ki,Hi={};function Vi(){return Ki?zi:(Ki=1,zi=function(){return null})}var Wi,Ji,Zi,Qi,Yi,Xi,ea,ta,ra,sa,na,oa,ia,aa,ca={};function da(){return Xi||(Xi=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=$i(),r.base64=(qi||(qi=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)}}(Hi)),Hi),r.EventEmitter=function(){if(Gi)return Bi;function e(){this._listeners={}}return Gi=1,Bi=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},Bi}(),r.float=function(){if(ji)return Fi;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,Fi=e(e)}(),r.inquire=Vi(),r.utf8=(Wi||(Wi=1,(t=ca).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}),ca),r.pool=Zi?Ji:(Zi=1,Ji=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(Yi)return Qi;Yi=1,Qi=t;var e=da();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},Qi}(),r.isNode=Boolean(void 0!==xi&&xi&&xi.process&&xi.process.versions&&xi.process.versions.node),r.global=r.isNode&&xi||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||Di,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}}(Di)),Di}function ua(){if(ta)return ea;ta=1,ea=c;var e,t=da(),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()},ea}function la(){if(oa)return na;oa=1,na=o;var e,t=da(),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)}})},na}var ha,pa,ma,fa,ga,ya,va={};function ba(){return ma||(ma=1,va.Service=function(){if(pa)return ha;pa=1,ha=t;var e=da();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},ha}()),va}function Ia(){return ga?fa:(ga=1,fa={})}function wa(){return ya||(ya=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=ua(),t.BufferWriter=function(){if(sa)return ra;sa=1,ra=r;var e=ua();(r.prototype=Object.create(e.prototype)).constructor=r;var t=da();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(),ra}(),t.Reader=la(),t.BufferReader=function(){if(aa)return ia;aa=1,ia=r;var e=la();(r.prototype=Object.create(e.prototype)).constructor=r;var t=da();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(),ia}(),t.util=da(),t.rpc=ba(),t.roots=Ia(),t.configure=r,r()}(Pi)),Pi}var Ca,Sa,Ta,_a,Ra={},Aa={exports:{}};var Ma,Ea,Ua,ka,Na,Oa,xa,La,Pa,Da,$a,qa,Ba,Ga,Fa,ja={};function za(){if(Ua)return Ea;Ua=1,Ea=c;var e=Mc();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=Rc(),o=Tc(),i=Ac();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},Ea}function Ka(){if(Na)return ka;Na=1,ka=s;var e=Rc();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=_c(),r=Tc();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))}},ka}function Ha(){if(xa)return Oa;xa=1,Oa=r;var e=Mc();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=Tc();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))},Oa}function Va(){if(Pa)return La;Pa=1,La=n;var e=za();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=Ha(),r=Tc(),s=ba();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},La}function Wa(){if($a)return Da;$a=1,Da=t;var e=da();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)},Da}function Ja(){if(Ba)return qa;Ba=1,qa=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=Ec(),t=_c(),r=Tc();function s(e){return"missing required '"+e.name+"'"}return qa}function Za(){if(Fa)return Ga;Fa=1,Ga=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=Ec(),t=Tc();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 Ga}var Qa,Ya={};function Xa(){return Qa||(Qa=1,function(e){var t=e,r=Ec(),s=Tc();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")}}(Ya)),Ya}var ec,tc,rc,sc,nc,oc,ic,ac,cc,dc,uc,lc,hc,pc,mc,fc,gc,yc,vc,bc,Ic={};function wc(){return ec||(ec=1,e=Ic,t=Wa(),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)}}),Ic;var e,t}function Cc(){if(rc)return tc;rc=1,tc=f;var e=za();((f.prototype=Object.create(e.prototype)).constructor=f).className="Type";var t=Ec(),r=Ac(),s=Rc(),n=Ka(),o=Va(),i=Wa(),a=la(),c=ua(),d=Tc(),u=Uc(),l=Ja(),h=Za(),p=Xa(),m=wc();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)}},tc}function Sc(){if(nc)return sc;nc=1,sc=c;var e=za();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=Rc(),o=Ec(),i=Ac(),a=Tc();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},sc}function Tc(){if(oc)return Aa.exports;oc=1;var e,t,r,s,n,o=Aa.exports=da(),i=Ia();o.codegen=function(){if(Sa)return Ca;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 Sa=1,Ca=e,e.verbose=!1,Ca}(),o.fetch=function(){if(_a)return Ta;_a=1,Ta=r;var e=$i(),t=Vi()("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()},Ta}(),o.path=(Ma||(Ma=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=Cc());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=Ec());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(Sc()))}}),Aa.exports}function _c(){return ic||(ic=1,function(e){var t=e,r=Tc(),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])}(Ra)),Ra}function Rc(){if(cc)return ac;cc=1,ac=i;var e=Mc();((i.prototype=Object.create(e.prototype)).constructor=i).className="Field";var t,r=Ec(),s=_c(),n=Tc(),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},ac}function Ac(){if(uc)return dc;uc=1,dc=s;var e=Mc();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=Rc(),r=Tc();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)})}},dc}function Mc(){if(hc)return lc;hc=1,lc=i,i.className="ReflectionObject";const e=Ac();var t,r=Tc(),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},lc}function Ec(){if(mc)return pc;mc=1,pc=s;var e=Mc();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=za(),r=Tc();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)},pc}function Uc(){if(gc)return fc;gc=1,fc=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=Ec(),t=_c(),r=Tc();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 fc}var kc=bc?vc:(bc=1,vc=function(){if(yc)return Li.exports;yc=1;var e=Li.exports=wa();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=Uc(),e.decoder=Ja(),e.verifier=Za(),e.converter=Xa(),e.ReflectionObject=Mc(),e.Namespace=za(),e.Root=Sc(),e.Enum=Ec(),e.Type=Cc(),e.Field=Rc(),e.OneOf=Ac(),e.MapField=Ka(),e.Service=Va(),e.Method=Ha(),e.Message=Wa(),e.wrappers=wc(),e.types=_c(),e.util=Tc(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),Li.exports}());const Nc={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}}}}}}}}}},Oc=e=>{if(!e||0===e.trim().length)throw Fo("Proto type name is required.",{code:Go,stage:xo,retryable:!1,details:{typeName:e}})};class xc{constructor(){this.codecMap=new Map}register(e,t){Oc(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:Go,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 Oc(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Fo("Proto codec not found.",{code:Go,stage:xo,retryable:!1,details:{typeName:e}})}}const Lc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Pc=e=>{class t extends kc.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},Dc=e=>ci.isLong(e),$c=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,qc=e=>Object.prototype.hasOwnProperty.call(kc.types.packed,e),Bc=e=>{const t=e.resolve();return t.resolvedType instanceof kc.Enum||qc(t.type)},Gc=(e,t)=>t in e?e[t]:void 0,Fc=e=>{const t=e.resolve();return t.resolvedType instanceof kc.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(kc.types.basic,r)?kc.types.basic[t.type]:2);var r},jc=(e,t)=>Dc(e)||"number"==typeof e||"string"==typeof e?e:Lc(e)&&"number"==typeof e.low&&"number"==typeof e.high?new ci(e.low,e.high,t):t?ci.UZERO:ci.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:$c(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}`)}},Kc=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},Hc=(e,t)=>{const r=e.uint32();return Kc(e,r,t),r},Vc=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return Kc(e,8,r),void e.skip(8);case 2:{const t=Hc(e,r);return void e.skip(t)}case 5:return Kc(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},Wc=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof kc.Type){const t=e.fork();return Zc(n,Lc(r)?r:{},t),t.ldelim(),e}return n instanceof kc.Enum?(e.int32("number"==typeof r?r:Number(r)),e):zc(e,s.type,r)},Jc=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(qc(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)Wc(e,t,s);return e.ldelim(),e}const n=Fc(t);for(const o of r)e.uint32(t.id<<3|n),Wc(e,t,o);return e},Zc=(e,t,r=kc.Writer.create())=>{const s=e.fieldsArray.slice().sort(kc.util.compareFieldsById);for(const n of s){const e=Gc(t,n.name);null!=e&&(n.repeated?Jc(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|Fc(n)),Wc(r,n,e)))}return r},Qc=(e,t,r,s)=>{const n=t.resolve(),o=n.resolvedType;return o instanceof kc.Type?2!==r?void Vc(e,r,s):Yc(o,e,Hc(e,s)):o instanceof kc.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)},Yc=(e,t,r)=>{const s=t instanceof kc.Reader?t:kc.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){Vc(s,d,n);continue}if(c.repeated){const e=Array.isArray(o[c.name])?o[c.name]:[];if(Bc(c)&&2===d){const t=Hc(s,n)+s.pos;for(;s.pos<t;)e.push(Qc(s,c,0,t))}else{const t=Qc(s,c,d,n);void 0!==t&&e.push(t)}o[c.name]=e;continue}const e=Qc(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},Xc=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,ed=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof kc.Type)return null;if(r.resolvedType instanceof kc.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&&Dc(r.typeDefault)?Xc(r.typeDefault,t):r.typeDefault},td=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof kc.Type?Lc(t)?rd(s.resolvedType,t,r):t:s.resolvedType instanceof kc.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&Dc(t)?Xc(t,r):"bytes"===s.type&&$c(t)?((e,t)=>t?.bytes===String?kc.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},rd=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(kc.util.compareFieldsById)){const e=Gc(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>td(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=ed(n,r)):s[n.name]=td(n,e,r)}return s},sd=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>Zc(e,Lc(t)?t:{},r),e.decode=(t,r)=>Yc(e,t,r),e.fromObject=e=>Lc(e)?e:{},e.toObject=(t,r)=>rd(e,Lc(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},nd=e=>{sd(e);for(const t of e.nestedArray)if(t instanceof kc.Type)nd(t);else if(t instanceof kc.Namespace)for(const e of t.nestedArray)e instanceof kc.Type&&nd(e)},od=e=>{for(const t of e.nestedArray)t instanceof kc.Type?nd(t):t instanceof kc.Namespace&&od(t)},id=()=>{const e=kc.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>Pc(e),kc.Type.prototype.setup=function(){return sd(this),this},kc.Type.prototype.create=function(e){return e?{...e}:{}},kc.Type.prototype.encode=function(e,t){return Zc(this,Lc(e)?e:{},t)},kc.Type.prototype.decode=function(e,t){return Yc(this,e,t)},kc.Type.prototype.fromObject=function(e){return Lc(e)?e:{}},kc.Type.prototype.toObject=function(e,t){return rd(this,Lc(e)?e:{},t)},kc.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let ad=!1,cd=null,ud=null,ld=null;const hd=e=>e.startsWith(".")?e.slice(1):e,pd=e=>e instanceof kc.Namespace,md=e=>e instanceof kc.Type,fd=e=>{for(const t of e.nestedArray)md(t)?nd(t):pd(t)&&fd(t)},gd=()=>{ad||(kc.util.Long=ci,kc.configure(),ad=!0),id();const e=kc.Root.fromJSON(Nc);return fd(e),e},yd=(e,t)=>{const r=e.nestedArray;for(const s of r){if(md(s)){const e=hd(s.fullName);nd(s),t.registerType(e,s);continue}pd(s)&&yd(s,t)}},vd=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return Fo(`Static proto ${r} failed.`,{code:Go,stage:xo,retryable:!1,details:{typeName:e,operation:r,cause:s}})},bd=()=>cd||(cd=gd(),cd),Id=()=>{if(ld)return ld;const e=(()=>{if(ud)return ud;const e=new xc,t=bd();return yd(t,e),ud=e,e})();return ld={encode(t,r){try{return e.getOrThrow(hd(t)).encode(r)}catch(s){throw vd(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(hd(t)).decode(r)}catch(s){throw vd(t,s,"decode")}}},ld},wd=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},Cd=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:wd(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)}}}},Sd=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Td=e=>"function"==typeof e.on&&"function"==typeof e.off,_d=(e,t,r)=>{if(Sd(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(Td(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw Fo("Socket event listener API is unsupported.",{code:Bo,stage:Oo,retryable:!1,details:{event:t}})},Rd=(e,t,r)=>{if(Sd(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(Td(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=_d(e,t,(...e)=>{n(),r(...e)}),n}throw Fo("Socket one-time listener API is unsupported.",{code:Bo,stage:Oo,retryable:!1,details:{event:t}})},Ad=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?Ad(e.data):null;var t},Md=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return _d(e,"open",()=>{t.forEach(e=>{e()})}),_d(e,"message",(...e)=>{const t=Ad(e[0]);null!==t&&r.forEach(e=>{e(t)})}),_d(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),_d(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:Bo,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)})}},Ed=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:Bo,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:Bo,stage:Oo,retryable:!0,details:{url:e.url,reason:"timeout"}})))};i=Rd(n,"open",()=>{c||(c=!0,i(),a(),d(),r(Md(n)))}),a=Rd(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:Bo,stage:Oo,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(o=setTimeout(u,e.timeoutMs))})}},Ud=(e,t)=>{throw Fo("Upload adapter execution failed.",{code:qo,stage:No,retryable:"abort"!==e,details:{reason:e,url:t.url}})},kd=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},Nd=(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{Ud("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),o.addEventListener("timeout",()=>{try{Ud("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),o.addEventListener("error",()=>{try{Ud("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=kd(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)}}))}}),Od=(e,t)=>e?"timeout":"abort",xd=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 Nd(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=kd(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?Od(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}})}}},Ld=(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},Pd=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=Ld(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)}}}},Dd=(e,t)=>e+t&4294967295,$d=(e,t,r,s,n,o)=>{return Dd((i=Dd(Dd(t,e),Dd(s,o)))<<(a=n)|i>>>32-a,r);var i,a},qd=(e,t,r,s,n,o,i)=>$d(t&r|~t&s,e,t,n,o,i),Bd=(e,t,r,s,n,o,i)=>$d(t&s|r&~s,e,t,n,o,i),Gd=(e,t,r,s,n,o,i)=>$d(t^r^s,e,t,n,o,i),Fd=(e,t,r,s,n,o,i)=>$d(r^(t|~s),e,t,n,o,i),zd=(e,t)=>{let[r,s,n,o]=e;r=qd(r,s,n,o,t[0]??0,7,-680876936),o=qd(o,r,s,n,t[1]??0,12,-389564586),n=qd(n,o,r,s,t[2]??0,17,606105819),s=qd(s,n,o,r,t[3]??0,22,-1044525330),r=qd(r,s,n,o,t[4]??0,7,-176418897),o=qd(o,r,s,n,t[5]??0,12,1200080426),n=qd(n,o,r,s,t[6]??0,17,-1473231341),s=qd(s,n,o,r,t[7]??0,22,-45705983),r=qd(r,s,n,o,t[8]??0,7,1770035416),o=qd(o,r,s,n,t[9]??0,12,-1958414417),n=qd(n,o,r,s,t[10]??0,17,-42063),s=qd(s,n,o,r,t[11]??0,22,-1990404162),r=qd(r,s,n,o,t[12]??0,7,1804603682),o=qd(o,r,s,n,t[13]??0,12,-40341101),n=qd(n,o,r,s,t[14]??0,17,-1502002290),s=qd(s,n,o,r,t[15]??0,22,1236535329),r=Bd(r,s,n,o,t[1]??0,5,-165796510),o=Bd(o,r,s,n,t[6]??0,9,-1069501632),n=Bd(n,o,r,s,t[11]??0,14,643717713),s=Bd(s,n,o,r,t[0]??0,20,-373897302),r=Bd(r,s,n,o,t[5]??0,5,-701558691),o=Bd(o,r,s,n,t[10]??0,9,38016083),n=Bd(n,o,r,s,t[15]??0,14,-660478335),s=Bd(s,n,o,r,t[4]??0,20,-405537848),r=Bd(r,s,n,o,t[9]??0,5,568446438),o=Bd(o,r,s,n,t[14]??0,9,-1019803690),n=Bd(n,o,r,s,t[3]??0,14,-187363961),s=Bd(s,n,o,r,t[8]??0,20,1163531501),r=Bd(r,s,n,o,t[13]??0,5,-1444681467),o=Bd(o,r,s,n,t[2]??0,9,-51403784),n=Bd(n,o,r,s,t[7]??0,14,1735328473),s=Bd(s,n,o,r,t[12]??0,20,-1926607734),r=Gd(r,s,n,o,t[5]??0,4,-378558),o=Gd(o,r,s,n,t[8]??0,11,-2022574463),n=Gd(n,o,r,s,t[11]??0,16,1839030562),s=Gd(s,n,o,r,t[14]??0,23,-35309556),r=Gd(r,s,n,o,t[1]??0,4,-1530992060),o=Gd(o,r,s,n,t[4]??0,11,1272893353),n=Gd(n,o,r,s,t[7]??0,16,-155497632),s=Gd(s,n,o,r,t[10]??0,23,-1094730640),r=Gd(r,s,n,o,t[13]??0,4,681279174),o=Gd(o,r,s,n,t[0]??0,11,-358537222),n=Gd(n,o,r,s,t[3]??0,16,-722521979),s=Gd(s,n,o,r,t[6]??0,23,76029189),r=Gd(r,s,n,o,t[9]??0,4,-640364487),o=Gd(o,r,s,n,t[12]??0,11,-421815835),n=Gd(n,o,r,s,t[15]??0,16,530742520),s=Gd(s,n,o,r,t[2]??0,23,-995338651),r=Fd(r,s,n,o,t[0]??0,6,-198630844),o=Fd(o,r,s,n,t[7]??0,10,1126891415),n=Fd(n,o,r,s,t[14]??0,15,-1416354905),s=Fd(s,n,o,r,t[5]??0,21,-57434055),r=Fd(r,s,n,o,t[12]??0,6,1700485571),o=Fd(o,r,s,n,t[3]??0,10,-1894986606),n=Fd(n,o,r,s,t[10]??0,15,-1051523),s=Fd(s,n,o,r,t[1]??0,21,-2054922799),r=Fd(r,s,n,o,t[8]??0,6,1873313359),o=Fd(o,r,s,n,t[15]??0,10,-30611744),n=Fd(n,o,r,s,t[6]??0,15,-1560198380),s=Fd(s,n,o,r,t[13]??0,21,1309151649),r=Fd(r,s,n,o,t[4]??0,6,-145523070),o=Fd(o,r,s,n,t[11]??0,10,-1120210379),n=Fd(n,o,r,s,t[2]??0,15,718787259),s=Fd(s,n,o,r,t[9]??0,21,-343485551),e[0]=Dd(r,e[0]),e[1]=Dd(s,e[1]),e[2]=Dd(n,e[2]),e[3]=Dd(o,e[3])},Kd=(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},Hd=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},Vd=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)zd(t,Kd(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(Hd).join("")},Wd=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})},Jd=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},Zd=()=>({async getImageInfo(e){const t=Jd(e),r=await Wd(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=Jd(e),s=await Wd(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=Jd(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 Vd(new Uint8Array(r))}}),Qd=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)},Yd=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},Xd=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"}})},eu=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},tu=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(Qd(e)))}})}).catch(e=>{throw Fo("Miniapp image info read failed",{code:qo,stage:Lo,retryable:!1,details:{src:t,cause:Qd(e)}})}),ru=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,su=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await tu(e,t);return ru(t,r)},nu=e=>({async getImageInfo(t){const r=Yd(t),s=await tu(e,r),n=eu(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=Yd(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 tu(e,s),o=ru(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(Qd(e)))}})}).catch(e=>{throw Fo("Miniapp image compress failed",{code:qo,stage:Lo,retryable:!1,details:{src:o,cause:Qd(e)}})}),c=await su(e,a),d=await tu(e,c),u=eu(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=Xd(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(Qd(e)))}})}).catch(e=>{throw Fo("Miniapp file info read failed",{code:qo,stage:Lo,retryable:!1,details:{filePath:t,cause:Qd(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=Yd(t),s=await su(e,r),n=await(async(e,t)=>{const r=Xd(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(Qd(e)))}})}).catch(e=>{throw Fo("Miniapp file read failed",{code:qo,stage:Lo,retryable:!1,details:{filePath:t,cause:Qd(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 Vd(n)}}),ou="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",iu=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),au=e=>e===Eo.ALIPAY_MINIAPP||e===Eo.DINGTALK_MINIAPP,cu=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=ou.indexOf(t[i]??""),r=ou.indexOf(t[i+1]??""),a=t[i+2]??"=",c=t[i+3]??"=",d="="===a?0:ou.indexOf(a),u="="===c?0:ou.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},du=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),uu=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},lu=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(du(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?lu(r.data,t+1):e},hu=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return uu(e);if(du(e))try{return uu(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return uu(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=hu(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=hu(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)}},pu=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(au(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+=ou[i>>18&63],t+=ou[i>>12&63],t+=void 0===n?"=":ou[i>>6&63],t+=void 0===o?"=":ou[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:iu(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},mu=(e,t)=>{const r=lu(e.data);if("string"==typeof r){if(!au(t))return r;const s=cu(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:iu(n.subarray(0,8)),decodedSuffixHex:iu(n.subarray(Math.max(0,n.length-8)))}),s}const s=hu(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(!au(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:iu(s.subarray(0,8))}),s.buffer;const o=cu(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:iu(i.subarray(0,8)),decodedSuffixHex:iu(i.subarray(Math.max(0,i.length-8)))}),o},fu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),gu=(e,t)=>fu(e)&&"function"==typeof e[t],yu=e=>e instanceof Error?e.message:fu(e)&&"string"==typeof e.errMsg?e.errMsg:fu(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),vu=e=>e?{...e}:{},bu=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},Iu=e=>{try{e.close()}catch{}},wu=(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:yu(r)}})))},a=e.downloadFile?.({url:t.url,header:vu(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=hu(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=bu(t.signal,()=>{a?.abort(),i("Mini program file download aborted.","abort",!1)})}),Cu=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:vu(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:yu(e)}}))}});n=bu(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"}}))})}):wu(e,t)}),Su=(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&&Iu(o),n(Fo(t,{code:Bo,stage:Oo,retryable:s,details:{url:r.url,cause:yu(e)}})))},u=e=>{if(!(gu(r=e,"send")&&gu(r,"close")&&gu(r,"onOpen")&&gu(r,"onMessage")&&gu(r,"onError")&&gu(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 Iu(n);o=n;const i=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?Iu(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=mu(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:Bo,stage:Oo,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:pu(r,t),success:s,fail:e=>{n(Fo("Mini program socket send failed.",{code:Bo,stage:Oo,retryable:!0,details:{cause:yu(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))})}),Tu=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:vu(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:yu(e)}}))}});i.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),o=bu(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"}}))})})}),_u=e=>({async getItem(t){if(gu(e,"getStorageSync"))try{const r=e.getStorageSync(t);return"string"==typeof r&&r.length>0?r:null}catch{return null}return gu(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,r){if(gu(e,"setStorageSync"))e.setStorageSync(t,r);else if(gu(e,"setStorage"))return new Promise((s,n)=>{e.setStorage({key:t,data:r,success:s,fail:e=>{n(e instanceof Error?e:new Error(yu(e)))}})})},async removeItem(t){if(gu(e,"removeStorageSync"))e.removeStorageSync(t);else if(gu(e,"removeStorage"))return new Promise((r,s)=>{e.removeStorage({key:t,success:r,fail:e=>{s(e instanceof Error?e:new Error(yu(e)))}})})}}),Ru=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>gu(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 gu(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),gu(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{gu(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return gu(e,"onAppShow")&&e.onAppShow(r),gu(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{gu(e,"offAppShow")&&e.offAppShow(r),gu(e,"offAppHide")&&e.offAppHide(s)}}}),Au=(e,t=Eo.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(gu(e,"request")&&gu(e,"connectSocket")&&gu(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?nu(s):void 0;return{request:Cu(s),socket:Su(s,r),upload:Tu(s),runtime:Ru(s,t),storage:_u(s),imageProcessor:n}},Mu=[Eo.WEB,Eo.ELECTRON_RENDERER,Eo.REACT_NATIVE],Eu=(e,t)=>{if("object"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Uu=e=>Mu.includes(e),ku=(e,t)=>(e!==Eo.UNIAPP||!Ou(t))&&(Uu(e)||e===Eo.UNIAPP&&Xo(t)),Nu=e=>Eu(e,"getImageInfo")&&Eu(e,"getFileSystemManager"),Ou=e=>"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),xu=(e,t)=>{if(Uu(e)&&e!==Eo.REACT_NATIVE)return Zd();if(ni(e)&&Nu(t))return nu(t);if(e===Eo.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Xo(e))return Zd();if(Nu(e.uni))return nu(e.uni);if(Nu(e.wx))return nu(e.wx)}},Lu=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())}},Pu=(e,t,r,s)=>{if(e===Eo.UNIAPP&&Ou(r)&&void 0!==r.uni&&Zo(r.uni))return{...Au(r.uni,e,t),proto:Id()};if(((e,t)=>!ku(e,t)&&ni(e))(e,r)&&Zo(s))return{...Au(s,e,t),proto:Id()};const n=r.XMLHttpRequest,o=ku(e,r),i=o?Cd({fetchImpl:r.fetch}):void 0,a=o?Ed({webSocketCtor:r.WebSocket}):void 0,c=e===Eo.REACT_NATIVE?Pd({fetchImpl:r.fetch,formDataCtor:r.FormData}):o?xd({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:Id(),storage:Lu(r),imageProcessor:o&&e!==Eo.REACT_NATIVE?Zd():xu(e,s)}},Du=(e,t)=>{if(void 0!==e)return e;throw Fo("Platform adapter initialization failed.",{code:Po,stage:Uo,retryable:!1,details:{capability:t}})},$u=e=>{const t=Vo(e?.runtimeInput),r=si(t,e?.prefer),s=r.platform,n=Pu(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);ii(a);return{platform:s,platformId:s,capability:a,request:Du(i.request,"request"),upload:Du(i.upload,"upload"),socket:Du(i.socket,"socket"),runtime:Du(i.runtime,"runtime"),proto:Du(i.proto,"proto"),storage:Du(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:Br,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}})},Bu={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Gu{constructor(e={}){this.attemptCount=0,this.config={...Bu,...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 Fu={interval:3e4,timeout:6e4},ju="function"==typeof TextDecoder?new TextDecoder:null;class zu{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(!zu.isRecord(r))return;"pong"===zu.readString(r.type)&&(this.markAlive(),So("Pong received"))},this.config={...Fu,...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)?ju?.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 Ku=null;function Hu(){return Ku||(Ku=bd()),Ku}const Vu="websdk2:device-info",Wu="webim",Ju="web",Zu=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,o=Vo().localStorage,i=()=>{if(!o)return null;try{const t=o.getItem(Vu);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(Vu,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===Wu){const e=`${Ju}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${Ju}_${r}`,deviceName:r,deviceUuid:`${Ju}_${t}`});return a(e),e}const n={deviceId:`webim_${Ju}_${r}`,deviceName:`webim_${Ju}_${r}`,deviceUuid:`webim_${Ju}_${r}`};return a(n),n}if(r===Wu){const e=`random_${Ju}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${Ju}_${r}`,deviceName:r,deviceUuid:`random_${Ju}_${t}`})}return{deviceId:`webim_${Ju}_${r}`,deviceName:`webim_${Ju}_${r}`,deviceUuid:`webim_${Ju}_${r}`}},Qu=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Yu=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 ci(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Xu=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},el=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},tl=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,rl="X-Request-Id",sl=new Set(["mute"]),nl={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},ol=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},il=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},al=(e,t)=>{const r=e?.map(e=>ol(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},cl=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=il(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},dl=e=>{const t=il(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=nl[s];if(!e)continue;let t=n;if(sl.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},ul=e=>{const t=il(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:ol(t.operator)??ol(t.username)}},ll=(e,t)=>({eventName:e,payload:t}),hl=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=ol(e.from?.name),s=(n=e.to,ol(n?.[0]?.name));var n;switch(e.operation){case 1:return ll(qe,t);case 10:return ll(Fe,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return ll(Be,{...t,memberIds:al(e.members,r),ext:e.ext??e.eventExt});case 18:return ll(Ge,{...t,memberIds:al(e.members,r)});case 20:return ll(Ze,{...t,oldOwnerId:r,newOwnerId:s});case 21:return ll(We,{...t,adminId:s??r});case 22:return ll(Je,{...t,adminId:s??r});case 23:{const r=(e=>{const t=il(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):al(e.members,s),o=46388736e5;return ll(je,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,o])),muteExpire:cl(e.reason,e.eventExt)??o})}case 24:return ll(ze,{...t,userIds:al(e.members,s)});case 25:return ll(Qe,{...t,announcement:e.reason??""});case 26:return ll(Qe,{...t,announcement:""});case 29:return ll(Ke,{...t,userIds:al(e.members,s)});case 30:return ll(He,{...t,userIds:al(e.members,s)});case 31:return ll(Ve,{...t,isMuted:!0});case 32:return ll(Ve,{...t,isMuted:!1});case 14:return ll(Ye,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:dl(e.eventExt)});case 43:{const s=ul(e.eventExt);return ll(Xe,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=ul(e.eventExt);return ll(et,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},pl=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ml=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},fl=e=>!!e&&("undefined"!=typeof DOMException&&e instanceof DOMException?"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name:e instanceof Error&&("QuotaExceededError"===e.name||e.message.includes("quota"))),gl=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],yl=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),vl=e=>({userId:e}),bl=(e,t,r)=>{const s={userId:r};for(const n of gl){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Il=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,yl(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,vl(i));return s},wl=e=>pl(e)?e:null,Cl=e=>{if("string"==typeof e)return e},Sl=e=>{const t=Cl(e)?.trim();return t||void 0},Tl=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}},_l=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Rl=e=>{const t=wl(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Al=e=>{const t=wl(e);return t?wl(t.data)?t.data:t:null},Ml=(e,t)=>{const r=wl(e),s=r&&wl(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Tl(n[0])},El=(e,t)=>{const r=(e=>{const t=wl(e);return t?Tl(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},Ul=e=>Sl(e.groupId)??Sl(e.groupid)??Sl(e.id)??"",kl=e=>Cl(e.name)??Cl(e.groupname)??Cl(e.groupName)??"",Nl=e=>{const t=Rl(e),r=wl(t[0])??Al(e)??{},s=(e=>{const t=wl(e);if(!t)return null;const r=Ul(t);return r?{groupId:r,name:kl(t),description:Cl(t.description),memberCount:Tl(t.memberCount)??Tl(t.affiliations_count),public:_l(t.public),joinApprovalRequired:_l(t.joinApprovalRequired)??_l(t.approval)??_l(t.membersonly)??_l(t.members_only),allowInvites:_l(t.allowInvites)??_l(t.allowinvites)??_l(t.allow_user_invites),maxMembers:Tl(t.maxMembers)??Tl(t.maxusers),role:Sl(t.role)??Sl(t.permission),disabled:_l(t.disabled)}:null})(r)??{groupId:Ul(r),name:kl(r)},n=Sl(r.owner)??Sl(r.admin)??Sl(r.member),o=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>wl(e)).filter(e=>null!==e).map(e=>Tl(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?vl(n):void 0,inviteNeedConfirm:_l(r.inviteNeedConfirm)??_l(r.invite_need_confirm),muteAllMembers:_l(r.mute),ext:Cl(r.ext)??Cl(r.custom),createdAt:Tl(r.createdAt)??Tl(r.created),joinedAt:o,avatarUrl:Cl(r.avatar),messageBlocked:_l(r.messageBlocked)??_l(r.isMessageBlocked)??_l(r.shieldgroup)}},Ol=e=>vl(e),xl=e=>Rl(e).map(e=>Sl(e)).filter(e=>Boolean(e)).map(e=>Ol(e)),Ll=e=>{const t=wl(e);if(!t)return null;const r=Sl(t.fileId)??Sl(t.file_id);if(!r)return null;const s=Cl(t.fileName)??Cl(t.file_name)??r,n=Sl(t.fileOwner)??Sl(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?Ol(n):void 0,fileSize:Tl(t.fileSize)??Tl(t.file_size),createdAt:Tl(t.createdAt)??Tl(t.created)}},Pl=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Dl={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},$l=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},ql=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=>$l(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Gl=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=ql(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},Fl=e=>{const t=ql(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Dl[s];if(!e)continue;let t=n;if(Pl.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},jl=(e,t)=>{const r=ql(t)??ql(e);return Ll(r??void 0)??void 0},zl=(e,t)=>{const r=ql(t)??ql(e);return $l(r?.fileId)??$l(r?.file_id)??$l(e)??""},Kl=(e,t)=>({eventName:e,payload:t}),Hl=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=$l(e.from?.name),s=(n=e.to,$l(n?.[0]?.name));var n;switch(e.operation){case 4:return Kl(Y,{...t,applicantId:r,reason:e.reason});case 5:return Kl(X,{...t,accepterId:r});case 6:return Kl(ee,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return Kl(Q,{...t,inviterId:r,reason:e.reason});case 8:return Kl(te,{...t,inviteeId:r,reason:e.reason});case 9:return Kl(re,{...t,inviteeId:r,reason:e.reason});case 10:return Kl(se,t);case 1:return Kl(ne,t);case 19:return Kl(oe,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=ql(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=$l(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):Bl(e.members,s);return Kl(ie,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??Gl(e.reason,e.eventExt)})}case 24:return Kl(ae,{...t,userIds:Bl(e.members,s)});case 29:return Kl(ce,{...t,userIds:Bl(e.members,s)});case 30:return Kl(de,{...t,userIds:Bl(e.members,s)});case 31:return Kl(ue,{...t,isMuted:!0});case 32:return Kl(ue,{...t,isMuted:!1});case 21:return Kl(le,{...t,administratorId:s??r});case 22:return Kl(he,{...t,administratorId:s??r});case 20:return Kl(pe,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=Bl(e.members,r);return Kl(me,{...t,memberIds:s})}case 18:{const s=Bl(e.members,r);return Kl(fe,{...t,memberIds:s})}case 25:return Kl(ge,{...t,announcement:e.reason??""});case 26:return Kl(ge,{...t,announcement:""});case 27:return Kl(ye,{...t,sharedFile:jl(e.reason,e.eventExt)});case 28:return Kl(ve,{...t,fileId:zl(e.reason,e.eventExt)});case 14:return Kl(be,{...t,shouldFetchGroupDetail:!0,groupPatch:Fl(e.eventExt)});case 41:return Kl(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Kl(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=ql(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:$l(t.username),attribute:s}})(e.eventExt);return Kl(we,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},Vl=new WeakMap,Wl=(e,t)=>{Vl.set(e,t)},Jl=e=>Vl.get(e)??null,Zl=(e,t)=>{const r=Jl(e);r&&Wl(t,r)},Ql=new WeakMap,Yl=e=>Ql.get(e),Xl=new WeakMap,eh=e=>Xl.get(e),th=(e,t)=>{const r=Xl.get(e);r&&Xl.set(t,r)},rh="singleChat",sh="groupChat",nh=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},oh=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}},ih=e=>{if(!Array.isArray(e))return;const t=e.map(e=>nh(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},ah=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ch=(...e)=>{for(const t of e){const e=nh(t);if(e)return e}},dh=(e,t)=>Boolean(e&&t&&e===t),uh=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),lh=(e,t,r)=>{const s=ih(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>nh(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const o=nh(r?.name);return o?[o]:[]},hh=e=>{const t=oh(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}}},ph=(e,t)=>{const r=ch(e.to?.[0]?.clientResource);if(1!==e.to?.length||nh(e.to[0]?.name)!==t.userId||!uh(t.userId,r,t))return null;const s=(n=e.from,nh(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}},mh=(e,t)=>{if(!e.groupId)return To("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=ch(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!uh(nh(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=lh(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:nh(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},fh=(e,t)=>{if(!e.threadId)return To("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=ch(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!uh(nh(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=lh(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:nh(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},gh=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=ch(e.res,e.raw?.resource,e.raw?.clientResource);if(dh(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?rh:sh;var n;const o=nh(e.id)??(s===rh?nh(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?hh(e.ext):void 0,operatorId:nh(e.from),deviceId:r,timestamp:oh(e.ts),raw:e.raw}},yh=(e,t)=>{const r=ch(e.resource,e.raw?.resource,e.raw?.clientResource);if(dh(r,t.clientResource))return So("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=nh(e.to);if(!s)return To("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=nh(e.lastMsgId),o=ih(e.msgIdList)??(n?[n]:void 0),i=oh(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?sh:rh,messageIds:o,beforeTimestamp:i,deviceId:r,raw:e.raw}},vh=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},bh=2147483647,Ih=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>bh?void 0:r},wh=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>bh?Math.floor(e/1e3):Math.floor(e);return Ih(t)};var Ch=4096,Sh=65547,Th=15,_h=2113929216,Rh=65536,Ah=65536,Mh=10485760,Eh={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Uh={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function kh(e){if(!(e>0))return Ah;if(e<=Ah)return Ah;if(e>1073741823)return e;for(var t=Ah;t<e;)t*=2;return t}var Nh={byU16:0,byU32:1},Oh=0,xh=1,Lh=2,Ph=0,Dh=1;function $h(e,t){return e[t]|e[t+1]<<8}function qh(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Bh(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var Gh="fast";function Fh(e){return 2654435761*(e>>>0)>>>20&4095}function jh(e){return 2654435761*(e>>>0)>>>19&8191}function zh(e,t,r){if("fast"===Gh){var s=qh(e,t);return r===Nh.byU16?jh(s):Fh(s)}throw new Error("Unsupported hash strategy: "+Gh)}function Kh(e,t,r,s,n){r[t]=e-n}function Hh(e,t,r,s,n){Kh(t,zh(e,t,s),r,0,n)}function Vh(e,t,r,s){return t[e]+s}function Wh(e,t,r,s,n){return Vh(zh(e,t,s),r,0,n)}function Jh(e,t,r,s){for(var n=t;t<s-3;){if(qh(e,t)!==qh(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 Zh(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>_h)return 0;switch(c){case Oh:default:u=s,l=s;break;case xh:u=s-e.currentOffset,l=s-e.dictSize;break;case Lh:u=s-e.currentOffset,l=s}if(a===Nh.byU16&&n>=Sh)return 0;if(n<13)return Xh(t,r,I,w,T,_,i);Hh(t,m,p,a,u),h=zh(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 Xh(t,r,I,w,T,_,i);A=Vh(N,p,0,u),c===Lh&&(A<s?(R=b,l=y):(R=0,l=s)),h=zh(t,E,a),Kh(m,N,p,0,u)}while(d===Dh&&A<f||a!==Nh.byU16&&A+65535<m||!Qh(t,g,m,A,R,c,s));for(;m>I&&A+R>l;){var O=A+R-1;if(t[m-1]!==(c===Lh&&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>=Th){var L=x-Th;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(Bh(r,T,m-A),T+=2,c===Lh&&A<s){var $=m+(v-(A+R));if($>S&&($=S),(m+=4+(D=Yh(t,g,m+4,A+R+4-y+e.dictionaryStart,$,v-y)))===$&&$<S){var q=Jh(t,m,s,S);D+=q,m+=q}}else m+=4+(D=Jh(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(Hh(t,m-2,p,a,u),A=Wh(t,m,p,a,u),c===Lh&&(A<s?(R=b,l=y):(R=0,l=s)),Hh(t,m,p,a,u),!((d!==Dh||A>=f)&&A+65535>=m&&Qh(t,g,m,A,R,c,s)))break t;r[M=T++]=0}h=zh(t,++m,a)}return Xh(t,r,I,w,T,_,i)}function Qh(e,t,r,s,n,o,i){var a,c=qh(e,r);o===Lh&&s+n<i?a=qh(t,s+n):a=qh(e,s+n);return c===a}function Yh(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 Xh(e,t,r,s,n,o,i){var a=s-r;if(i&&n+a+1+Math.floor((a+255-Th)/255)>o)return 0;if(a>=Th){for(t[n++]=240,a-=Th;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 ep(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 tp(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)===Th){var T=ep(e,A={ip:p},m-Th,!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=$h(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=ep(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===Lh&&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 rp(){return{hashTable:new Uint32Array(Ch),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function sp(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function np(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?Dh:Ph;return e.dictionary&&c===s?(u=Zh(e,t,r,s,n,i||0,a||!1,Nh.byU32,xh,h),e.dictSize+=n,e.currentOffset+=n,u):(u=Zh(e,t,r,s,n,i||0,a||!1,Nh.byU32,Lh,h),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function op(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 ip(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function ap(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function cp(e,t,r,s,n,o,i){var a;if(e.prefixEnd===o){if((a=tp(t,r,s,n,o,i,!0,0,0,Lh,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=tp(t,r,s,n,o,i,!0,0,0,Lh,o,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=o+a}return a}function dp(e){var t=(e=e||{}).minWorkArea||Ah,r=e.maxWorkArea||Mh,s=e.shrinkThreshold||t;t<Ah&&(t=Ah),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Rh+t,this.maxBufferSize=Rh+r,this.shrinkThreshold=Rh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Eh.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=rp()}function up(e){var t=(e=e||{}).minWorkArea||Ah,r=e.maxWorkArea||Mh,s=e.shrinkThreshold||t;t<Ah&&(t=Ah),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Rh+t,this.maxBufferSize=Rh+r,this.shrinkThreshold=Rh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Eh.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}dp.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Rh?this.offset:Rh,n=this.offset>Rh?this.offset-Rh:0;t.set(this.ringBuffer.subarray(n,n+s),0),op(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},dp.prototype.compress=function(e,t){var r=e.length;if(r<=0)return Uh.PARAM_ERROR;if(r>this.maxBufferSize-Rh)return Uh.PARAM_ERROR;if(r>this.ringBufferSize-Rh){var s=kh(r),n=Rh+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Uh.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(op(this.stream,this.ringBuffer,0,Rh),this.offset=Rh);var o=this.offset;this.ringBuffer.set(e,o);var i=np(this.stream,this.ringBuffer,t,o,r,0,t.length,!0);return i<=0?Uh.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),i)},dp.prototype.reset=function(){this.offset=0,sp(this.stream)},dp.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},dp.prototype._tryAutoShrink=function(){this.shrinkMode!==Eh.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Eh.AUTO_IMMEDIATE||this.shrinkMode===Eh.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},dp.prototype.getWorkArea=function(){return this.ringBufferSize-Rh},dp.prototype.getRingBufferSize=function(){return this.ringBufferSize},dp.prototype.getBaseBufferSize=function(){return this.minBufferSize},dp.prototype.getMaxBufferSize=function(){return this.maxBufferSize},dp.prototype.getCurrentOffset=function(){return this.offset},dp.prototype.getShrinkMode=function(){return this.shrinkMode},dp.prototype.setShrinkMode=function(e){this.shrinkMode=e},dp.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},dp.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Rh,r=this.maxBufferSize-Rh;if(e<t||e>r)return Uh.PARAM_ERROR;this.shrinkThreshold=Rh+e},up.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Rh?this.offset:Rh,n=this.offset>Rh?this.offset-Rh:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,ap(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},up.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return Uh.PARAM_ERROR;if(r>this.maxBufferSize-Rh)return Uh.PARAM_ERROR;if(r>this.ringBufferSize-Rh){var n=kh(r),o=Rh+n;if(o>this.maxBufferSize&&(o=this.maxBufferSize),!this._resizeBuffer(o))return Uh.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var i=this.offset-Rh;i>0&&this.ringBuffer.set(this.ringBuffer.subarray(i,i+Rh),0),ap(this.streamDecode,this.ringBuffer,0,Rh),this.offset=Rh}var a=cp(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?Uh.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},up.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},up.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},up.prototype._tryAutoShrink=function(){this.shrinkMode!==Eh.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Eh.AUTO_IMMEDIATE||this.shrinkMode===Eh.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},up.prototype.getWorkArea=function(){return this.ringBufferSize-Rh},up.prototype.getRingBufferSize=function(){return this.ringBufferSize},up.prototype.getBaseBufferSize=function(){return this.minBufferSize},up.prototype.getMaxBufferSize=function(){return this.maxBufferSize},up.prototype.getCurrentOffset=function(){return this.offset},up.prototype.getShrinkMode=function(){return this.shrinkMode},up.prototype.setShrinkMode=function(e){this.shrinkMode=e},up.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},up.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Rh,r=this.maxBufferSize-Rh;if(e<t||e>r)return Uh.PARAM_ERROR;this.shrinkThreshold=Rh+e};const lp={LZ4_MAX_INPUT_SIZE:_h,BLOCK_MAX_SIZE:65536,DICT_SIZE:Rh,DEFAULT_WORK_AREA:Ah,DEFAULT_MAX_WORK:Mh,SHRINK_MODE:Eh,LZ4_ERROR:Uh,alignToPowerOf2:kh,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".');Gh=e},getHashStrategy:function(){return Gh},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>_h)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var o=s<Sh?Nh.byU16:Nh.byU32;return Zh({hashTable:new Uint32Array(o===Nh.byU16?8192:Ch),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,o,Oh,Ph)},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>_h)return 0;if(o<1)return 0;if(0===s)return t[n]=0,1;var i=s<Sh?Nh.byU16:Nh.byU32;return Zh({hashTable:new Uint32Array(i===Nh.byU16?8192:Ch),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,o,!0,i,Oh,Ph)},compressBound:function(e){return e<0||e>_h?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:tp(e,t,r,s,n,o,!0,0,0,Oh,n,null,0))},decompressFast:function(e,t,r,s,n){return tp(e,t,r=r||0,0,s=s||0,n,!1,0,0,xh,s-65536,0,65536)},createStream:rp,resetStream:sp,loadDict:function(e,t,r,s){if(e.initCheck&&sp(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;)Hh(t,o,e.hashTable,Nh.byU32,n),o+=3;return s},compressContinue:np,saveDict:op,createStreamDecode:ip,setStreamDecode:ap,decompressSafeContinue:cp,RingBufferEncoder:dp,RingBufferDecoder:up,_hashU16:jh,_hashU32:Fh,_TABLE_TYPE:Nh},hp=268435455,pp=new Uint32Array(256);let mp=!1;function fp(e){!function(){if(!mp){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;pp[e]=t>>>0}mp=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(pp[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var gp=(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))(gp||{});const yp=268435455;class vp{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:lp.DEFAULT_WORK_AREA,maxWorkArea:lp.DEFAULT_MAX_WORK,shrinkMode:lp.SHRINK_MODE.MANUAL};this.encoder=new lp.RingBufferEncoder(e),this.decoder=new lp.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>yp)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=lp.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>hp)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=fp(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>yp)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=fp(i);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return i}reset(){this.encoder.reset(),this.decoder.reset()}}const bp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ip=(e,t)=>Zc(e,t).finish();class wp{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Zu({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:[Bs],compressType:[Gs],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=Hu(),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:[Gs],encryptType:[Bs],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=Ip(t,s),o={version:0,guid:Qu({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:[Bs],payload:n,traceId:tl()};return Ip(r,o)}encodeHeartbeat(){const e=Hu(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Ip(t,{}),n={version:0,encryptType:[Bs],command:ns,payload:s,traceId:tl()};return Ip(r,n)}encodeStatisticRebuild(){const e=Hu(),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=Ip(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=Ip(s,a);return Ip(n,{version:0,encryptType:[Bs],command:ss,payload:c,traceId:tl()})}decodeProvision(e){const t=Hu().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=Hu().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=Hu().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=Hu().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=Hu(),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=Yu(n.metaId),c=Yu(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(Yu(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=>Yu(e)).filter(e=>Boolean(e)),t=Yu(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=el(Array.isArray(s.ext)?s.ext.filter(bp):void 0),n=bp(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=Yu(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=Yu(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const h=Yu(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:el(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=Hu(),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(!bp(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(!bp(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=Hu(),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=Hu(),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=ph({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=Hu(),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=fh({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=mh({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?hl({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}):Hl({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&&Ql.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:bp(s.data)?s.data:s}}]}if("conv"===n){const e=bp(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=gh({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=bp(s.data)?s.data:s,t=yh({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(!ah(s))continue;const e=ch(s.operator_resource,s.resource,s.clientResource);if(dh(e,t.clientResource))continue;const n=nh(s.group)??nh(s.user);if(!n||!ah(s.data))continue;const o=nh(s.group)?sh:rh,i=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:o,remindType:nh(i.type),silentMode:i,deviceId:e,raw:s})}return r})(bp(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(Yu(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:vh(e.category),data:e}}decodeNotice(e){const t=Hu().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Hu().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=Hu(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=Ip(r,{queue:e}),o={version:0,encryptType:[Bs],command:ss,payload:n,traceId:tl()};return Ip(s,o)}encodeLastSession(e,t){const r=Hu(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),o=Ip(s,{queue:e,key:t}),i={version:0,encryptType:[Bs],command:ss,payload:o,traceId:tl()};return Ip(n,i)}encodeChatMessage(e,t){const r=Hu(),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:Xu(e.ext??{}),...c?{meta:c}:{},...a,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=Ip(s,u),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e),f={id:t,to:Qu({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=Ip(n,{meta:f}),y={version:0,encryptType:[Bs],command:ss,payload:g,traceId:tl()};return Ip(o,y)}encodeActionMessage(e,t){const r=Hu(),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:Xu(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=Ip(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:Qu({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=Ip(n,{meta:l}),p={version:0,encryptType:[Bs],command:ss,payload:h,traceId:tl()};return Ip(o,p)}encodeChatRoomOperation(e,t){const r=Hu(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i={mucId:Qu({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=Ip(s,i),c={id:t,from:Qu({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=Ip(n,{meta:c}),u={version:0,encryptType:[Bs],command:ss,payload:d,traceId:tl()};return Ip(o,u)}decodeServerMessageMeta(e){const t=Hu(),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=ci.fromString("1099511628211",!0);let r=ci.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(ci.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()})(e)}decodeChatRoomJoinInfo(e){const t=Hu().lookupType("easemob.pb.MUCBody");for(const s of e){if(!bp(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(!bp(e)||!bp(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!bp(s))continue;const o=s[this.context.userId];if(!bp(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=Yu(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:Yu(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=el(t.ext),h=el(e.ext),p=Number(Yu(e.timestamp))||Date.now(),m=Yu(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)};Wl(_,{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=Jl(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 Ih(Yu(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(Yu(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:Xu(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:eh(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=el(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?Xu({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(!bp(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(!bp(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(!bp(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(!bp(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=bp(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:bp(n?.ext)?n.ext:{},timestamp:s,body:l,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(bp(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:bp(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 bp(e)?e:null}catch{return null}}if(bp(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return bp(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(bp).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 vp);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===gp.UPLINK_ONLY||r===gp.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===gp.DOWNLINK_ONLY||r===gp.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?gp.UPLINK_ONLY:1===e?gp.DOWNLINK_ONLY:2===e?gp.BIDIRECTIONAL:gp.NONE}disableCompression(){this.compressor&&(this.compressor.mode=gp.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Cp=1e3,Sp="direct";class Tp{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 _p{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 Rp={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},Ap=()=>{const e=globalThis.crypto?.randomUUID?.();return e??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class Mp{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??Ap;const t=new _p({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 Tp({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:Rp[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??Sp,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??Sp,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 Ep;const Up=e=>{Ep?.applyDnsSwitch(e)},kp=e=>{Ep?.updateNetworkType(e)},Np=e=>{if("disabled"!==Ep?.state)return Ep?.startOperation(e)},Op=()=>{Ep?.reset(),Ep=void 0};class xp{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 wp({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 Gu({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new zu({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=Ed({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=Np({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 Lp=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()}},Pp=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},Dp=()=>{const e=Vo().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},$p=new Uint8Array([99,109]),qp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Bp=e=>Array.isArray(e)&&e.every(qp),Gp=e=>"string"==typeof e?e:void 0,Fp=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jp=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},zp=(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},Kp=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},Hp=(e,t)=>{const r=Hu().lookupType(e).decode(t);if(!qp(r))throw new Error(`${e} decoded result is invalid`);return r},Vp=e=>qp(e)&&"string"==typeof e.name?e.name:"",Wp=(e,t,r)=>{const s=(Bp(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=Fp(e.type)??ys,r=Boolean(Gp(e.remotePath))||Boolean(Gp(e.title))||Boolean(Gp(e.summary))||(Fp(e.combineLevel)??0)>0,s=t===ys&&0===e.subType&&r;if(t===_s||s){const t=Fp(e.combineLevel)??0;return{type:"combine",body:{title:Gp(e.title)??"",summary:Gp(e.summary)??"",filename:Gp(e.displayName)??"combine",filetype:"application/octet-stream",url:Gp(e.remotePath),secret:Gp(e.secretKey),fileLength:Fp(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ys)return{type:"text",body:{content:Gp(e.text)??""}};if(t===Ss)return{type:"cmd",body:{action:Gp(e.action)??""}};if(t===Ts){const t=el(Bp(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:Gp(e.customEvent)??"",params:t}}}if(t===Is)return{type:"location",body:{latitude:Fp(e.latitude)??0,longitude:Fp(e.longitude)??0,address:Gp(e.address),buildingName:Gp(e.buildingName)}};if(t===vs){const t=qp(e.size)?e.size:{},r=Gp(e.remotePath)??"",s=no(r),n=Gp(e.thumbnailRemotePath),o=io(e.imageType)===Wn;return{type:"image",body:{localUrl:"",filename:Gp(e.displayName)??"image",filetype:"application/octet-stream",width:Fp(t.width)??0,height:Fp(t.height)??0,isGif:1===e.subType,isOriginalImage:o,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:Gp(e.secretKey),fileLength:Fp(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===bs){const t=qp(e.size)?e.size:{};return{type:"video",body:{url:Gp(e.remotePath)??"",filename:Gp(e.displayName)??"video",filetype:"application/octet-stream",duration:Fp(e.duration)??0,width:Fp(t.width),height:Fp(t.height),secret:Gp(e.secretKey),fileLength:Fp(e.fileLength),thumbnailUrl:Gp(e.thumbnailRemotePath)}}}if(t===ws)return{type:"voice",body:{url:Gp(e.remotePath)??"",filename:Gp(e.displayName)??"voice",filetype:"application/octet-stream",duration:Fp(e.duration)??0,secret:Gp(e.secretKey),fileLength:Fp(e.fileLength)}};if(t===Cs)return{type:"file",body:{url:Gp(e.remotePath)??"",filename:Gp(e.displayName)??"file",filetype:"application/octet-stream",secret:Gp(e.secretKey),fileLength:Fp(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const o=Vp(e.from)||Vp(r?.from)||`unknown-${t}`,i=Vp(e.to)||Vp(r?.to)||`unknown-${t}`,a=(c=e.type)===us?"groupChat":c===ls?"chatRoom":"singleChat";var c;const d=i||o,u=Number(Yu(r?.timestamp))||Date.now(),l=el(Bp(e.ext)?e.ext:void 0),h={msgServerId:Yu(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},Jp=(e,t)=>{const r=[];try{const n=Hp("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=Hp("easemob.pb.MessageBody",o);return Wp(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=Hp("easemob.pb.MessageBody",e);return Wp(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=Hp("easemob.pb.MessageBody.Content",e);return Wp({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("; "))},Zp=(e,t)=>{const r=Ao(e);try{const e=JSON.parse(r);if(!qp(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 Jp(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)}})}}},Qp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Yp=(e,t,r)=>{throw new Zr(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},Xp=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:Qp(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},em=(e,t)=>{if(e.sender.userId||Yp(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,ir),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||Yp(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,ir),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&Yp(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,ir),Qp(e.body)||Yp(`messageList[${t}] body must be object`,`messageList[${t}].body`,ir),"combine"===e.type){const r=Xp(e);(!Number.isInteger(r)||r<0)&&Yp(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,ir),r>10&&Yp(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ar)}},tm=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&Yp("messageList must not be empty","messageList",ir),(!Number.isInteger(t)||t<=0||t>300)&&Yp("max items is invalid","maxItems",ir),e>t&&Yp(`messageList max length is ${t}`,"messageList",cr)},rm=e=>{tm(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?em(r,t):Yp(`messageList[${t}] is required`,`messageList[${t}]`,ir)}},sm=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=Xp(r);e>t&&(t=e)}return t+1},nm=e=>{(!Number.isInteger(e)||e<=0)&&Yp("combineLevel must be positive integer","combineLevel",ir),e>10&&Yp("combineLevel must be <= 10","combineLevel",ar)},om=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class im{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"};Zl(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"};Zl(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 Zl(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:om(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:om(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??[];rm(r);const s=sm(r);nm(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=$p.length+t.reduce((e,t)=>e+4+t.length,0)+1,s=new Uint8Array(r);let n=0;s.set($p,n),n+=$p.length;for(const e of t){const t=jp(e.length);s.set(t,n),n+=t.length,s.set(e,n),n+=e.length}const o=Kp(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=Pp(i);if(!a&&!this.attachmentUploader)throw new Qr("Combine payload local url generation failed",{code:dr});Lp.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 Zl(e,c),th(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};Zl(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||Lp.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"};Zl(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)>=Cp){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=Np({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<Cp&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<Cp&&(this.chatRoomReportSaturated=!1)))}}class am{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 cm{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new am}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 dm{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 um=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class lm{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new cm(r),this.messageContexts=new Map,this.recentMessageIds=new dm(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(!um(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(!um(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(!um(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(!um(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(!um(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(!um(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(!um(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(!um(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!um(t.message)||"string"!=typeof t.message.type||!um(t.message.body)||!um(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...um(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)um(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)!um(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 hm=e=>e instanceof Error?e.message:String(e);class pm{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Cd({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;tm(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:{[rl]:tl()}});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<$p.length+1)throw new Yr("Combine payload is too short",{code:lr});const t=e.subarray(0,$p.length);if(t[0]!==$p[0]||t[1]!==$p[1])throw new Yr("Combine payload header is invalid",{code:lr});const r=e.subarray(0,e.length-1),s=Kp(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=$p.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=zp(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=Zp(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 tm(o.length,r),rm(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:hm(o),url:n}})}}}const mm=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?Cd({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:{[rl]:tl()}});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",Gr);if(n.status>=400)throw new Hr("attachment download failed",er,{details:{status:n.status,url:r}});return{filename:mm(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 ym=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[rl]:tl(),...r??{}}),vm=async e=>{const t=ym(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)}},bm=(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:Br,success:!1,description:"Upload aborted"}),To("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload aborted",{code:Br,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(ym(t,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{c.setRequestHeader(e,t)}),c.send(l)}),Im=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 vm({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=bm(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 vm({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},wm=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:Br,success:!1,description:"Upload canceled"}),To("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.(),r(new rs("Upload canceled",{code:Br,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(rl,tl());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)}),Cm=Zd(),Sm=e=>Object.prototype.toString.call(e),Tm=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:Sm(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}},_m=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}),Rm=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Am=e=>"object"==typeof e&&null!==e,Mm=(e,t)=>{const r=Am(t)?t:void 0,s=r?.code===Do&&r.stage===Lo;return"miniapp-path"===e&&(e=>{if(!Am(e))return!1;const t=Am(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 Em{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(!Rm(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=Lp.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:Tm(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=Np({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===Br&&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:_m(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:_m(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:_m(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:_m(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:_m(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(!Rm(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(Mm(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:_m(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:_m(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"}),Cm;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(!Rm(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(!Rm(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:_m(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:_m(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Im(i)}catch(d){const e=d instanceof rs?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return wm(i);throw d}return wm(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(!Rm(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}`,[rl]:tl()},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:_m(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 Zl(e,n),th(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 Zl(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 Zl(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 Zl(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 Zl(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(!Mm(t.md5FileInfo.source.sourceType,n))throw n;To("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:_m(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 Um{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 km="__internal:core";class Nm{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 xp({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new Em({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 im(r,null,this.eventHub,s),this.messageReceiver=new lm(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new pm(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(km,{[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 Um(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(km),Lp.clear()}}const Om=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)},xm=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 Lm{getCrypto(){return Vo().crypto}constructor(e,t){if(this.enabled=(()=>{const e=Vo();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=si(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:Om(s),ct:Om(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=xm(t.iv),s=xm(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 Pm="conversationMap",Dm="userInfoMap",$m="groupNamecardMap",qm="contactRelationMap",Bm="contactVersion",Gm="contactMeta",Fm="sessionListMap",jm="sessionListCheckpoint",zm="joinedGroupPreview",Km="metadata",Hm=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Vm{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 Wm=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=Vo().localStorage;return t&&"function"==typeof t.getItem?t:null};class Jm{constructor(e){this.available=Jm.checkAvailable(),this.cryptoAdapter=e??null}static checkAvailable(){const e=Wm();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.available)return t;const r=Wm();if(!r)return t;try{const s=r.getItem(e);if(!s)return t;let n=s;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(s);if(null===e)return t;n=e}return ml(n,t)}catch(s){return To("CacheStore read failed",s),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.available)return;const s=(e=>{try{return JSON.stringify(e)}catch{return null}})(t);if(null===s){if(r)throw new TypeError("CacheStore value cannot be serialized");return}const n=Wm();if(n)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(s):s;n.setItem(e,t)}catch(o){if(fl(o))throw o;if(r)throw o;To("CacheStore write failed",o)}}remove(e){if(!this.available)return;const t=Wm();if(t)try{t.removeItem(e)}catch(r){To("CacheStore remove failed",r)}}}const Zm={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Qm={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Ym{constructor(){this.items=new Map,this.versionState=Zm,this.meta=Qm}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(!pl(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 pl(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"}:Zm}normalizeMeta(e){return pl(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"}:Qm}}const Xm=(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}},ef=(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}},tf=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 rf{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=Xm(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=ef(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:tf(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(!pl(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=pl(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 sf=(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(sf(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=sf(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(sf(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=sf(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(sf(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=Xm(n,e,t),i=new Set(o.removed.map(e=>sf(e.groupId,e.userId)));this.items.clear();for(const a of s)i.has(sf(a.groupId,a.userId))||this.items.set(sf(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=ef(s,Math.min(e,s.length)),o=new Set(n.removed.map(e=>sf(e.groupId,e.userId)));this.items.clear();for(const i of r)o.has(sf(i.groupId,i.userId))||this.items.set(sf(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||!pl(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 of=100,af=3e3,cf=e=>({...e}),df=e=>"object"==typeof e&&null!==e,uf=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 lf{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:of,serverLimit:af,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:of,serverLimit:af,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return df(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:uf(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,of),this.meta=(e=>{const t=df(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:of,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:af,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=>cf(e)).slice(0,of),this.meta={...e.meta,source:"localPreview",storageLimit:of,serverLimit:af,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>cf(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>cf(e)),meta:{...this.meta,source:"localPreview"}}}}const hf=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,pf=e=>{const t={...e};return delete t.type,t},mf=e=>{if(!pl(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!pl(e.body))return null;const r=((e,t)=>{if(pl(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=hf(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(pl(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:pf(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}:{}}},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 o=s;t.has(o)||(t.add(o),r.push(o))}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,o=t.lastMessageAt??t.updatedAt;return n!==o?o-n:e.conversationId.localeCompare(t.conversationId)};class yf{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(!pl(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=hf(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:mf(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:o,conversationAvatar:i,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class vf{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=Xm(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=ef(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(!pl(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 bf=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,If=e=>e.lastMessageAt??e.updatedAt,wf=e=>[...e].sort((e,t)=>{const r=bf(t)-bf(e);if(0!==r)return r;const s=If(t)-If(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),Cf=e=>`${e.conversationType}:${e.conversationId}`,Sf=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Tf=(e,t)=>((e,t)=>If(t)>If(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Sf(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,_f=e=>{const t=new Map,r=new Set;for(const o of e.snapshot)r.add(Cf(o));for(const o of e.existing)t.set(Cf(o),o);const s=e.snapshot.map(e=>{const r=t.get(Cf(e));return r?Tf(e,r):e}),n=e.existing.filter(t=>!r.has(Cf(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return wf([...s,...n])},Rf=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Af=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Mf=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 Ef{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,Rf.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 Uf=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class kf{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 Lm(e.appKey,e.userId);this.store=new Jm(t??void 0);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Hm(r,Pm),this.userInfoKey=Hm(r,Dm),this.groupNamecardKey=Hm(r,$m),this.sessionListKey=Hm(r,Fm),this.sessionListCheckpointKey=Hm(r,jm),this.joinedGroupPreviewKey=Hm(r,zm),this.contactRelationKey=Hm(r,qm),this.contactVersionKey=Hm(r,Bm),this.contactMetaKey=Hm(r,Gm),this.metadataKey=Hm(r,Km),this.metadataStore=new Vm(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new rf,this.userInfoCache=new vf,this.groupNamecardCache=new nf,this.sessionListCache=new yf,this.joinedGroupPreviewCache=new lf,this.contactCache=new Ym,this.userInfoRuntimeStore=new Ef,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 lf;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=_f({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?Af(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([Mf(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=Cf(e.nextRecord),r=e.existing.filter(e=>Cf(e)!==t);return wf([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&&pl(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(o,e);const i=(n&&pl(n)&&pl(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&&pl(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&pl(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 r=6;for(let s=0;s<=r;s+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!fl(t))return this.restoreDirtyBatch(e),void To("Cache flush failed",t);const r=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,r),"none"===r)return this.restoreDirtyBatch(e),void To("Cache flush failed: no cache entry can be evicted",t)}To("Cache flush failed after quota cleanup attempts"),this.restoreDirtyBatch(e)}finally{}}async writeDirtyDomains(e){for(const t of Uf)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),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=>bf(e)>0),r=new Map;for(const n of e.incoming)r.set(Cf(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(Cf(e))&&0===bf(e)):e.existing.filter(e=>!r.has(Cf(e)));return wf([...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(_f({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=Jl(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?Af(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 Nf{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 Of={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function xf(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 Lf(e){return new Promise(t=>setTimeout(t,e))}const Pf=e=>{const t={...e};return delete t.type,t},Df=(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:Pf(r.body),modifiedInfo:r.modifiedInfo,userInfoUpdateTime:r.userInfoUpdateTime,namecardUpdateTime:r.namecardUpdateTime}},$f=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},qf=async(e,t)=>{const r=await $f(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:Df(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 Bf{constructor(e=`session-list-${Dp()}`){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 Gf=0,Ff=5,jf=10,zf=11,Kf=1,Hf=2,Vf=1,Wf=2,Jf=3,Zf=e=>e===Kf?"groupChat":e===Hf?"chatRoom":"singleChat",Qf=()=>Hu().lookupType("easemob.pb.MessageBody"),Yf=e=>{const t=Qf().toObject(Qf().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:""}:{}},Xf=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}},eg=e=>{const t={...e};return delete t.type,t},tg=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,rg=(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:tg({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:eg(t)};var o},sg=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},ng=(e,t)=>e.sessions.map(e=>{const r=(e=>{if(!e||0===e.byteLength)return{};try{return Yf(e)}catch{return{}}})(e.last_message?.payload),s=e.session_id??"",n=Zf(e.session_type),o=(e=>{const t=e.session_id??"",r=Zf(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:Xf(e)})(e);return{conversationId:s,conversationType:n,unreadCount:e.unread_count??0,lastMessage:rg(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:sg(e.marks),readAt:e.read_receipt,remindType:(i=e.remind_type,i===Vf?"ALL":i===Wf?"AT":i===Jf?"NONE":"DEFAULT"),conversationName:o.conversationName,conversationAvatar:o.conversationAvatar};var i}),og={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 ig=null,ag=!1;const cg=()=>ig||(ag||(kc.util.Long=ci,kc.configure(),ag=!0),id(),ig=kc.Root.fromJSON(og),od(ig),ig),dg=e=>cg().lookupType(e),ug=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}},lg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:ug(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:ug(t.protocol_version)??ug(t.protocolVersion)??0}},hg=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}},pg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==ug(t.id)?String(ug(t.id)):void 0,from:hg(t.from),timestamp:ug(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 mg{constructor(){this.requestType=dg("easemob.sessionlist.GetSessionListRequest"),this.responseType=dg("easemob.sessionlist.GetSessionListResponse"),this.errorType=dg("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:Gf}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=ug(t.type);return r!==jf?null:{type:r,header:lg(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:ug(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=ug(t.type);return r!==zf?null:{type:r,header:lg(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:ug(t.session_type),last_message:pg(t.last_message),updated_at:ug(t.updated_at),pinned_time:ug(t.pinned_time),unread_count:ug(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:ug(t.read_receipt),remind_type:ug(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:ug(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=ug(t.type);return r!==Ff?null:{type:r,header:lg(t.header),code:ug(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,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 mg;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=ng(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}}}})},gg=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"}]}}),yg=(e,t,r)=>{const s=e+t;return s<r?String(s):""},vg=e=>({...e}),bg=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}},Ig=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,wg=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 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=Ig(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:yg(t,e.pageSize,r.length)}},Cg=()=>Date.now(),Sg={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Tg=(e,t)=>({status:e,determinedAt:Cg(),reason:t}),_g=e=>e instanceof Hr&&(e.code===kt||1103===e.code),Rg=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:_g(e)});class Ag{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 Bf,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={...Of,...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=xf(i,s);await Lf(e)}throw n}(async()=>{o+=1;const r=1===o?e:this.createRetrySession();r.start();try{return await fg({client:this.client,session:r,params:t})}catch(s){throw r.fail(),s}},_g,Sg),a={result:i,syncStartedAt:e.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:Cg()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:Cg()};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:Rg(t)}),r.loadSessionList()}const u=r.loadSessionList();return r.updateConversationsFromServer(u.map(bg),{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:Tg("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:Rg(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=Tg("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new Bf}async buildFallbackSessionList(e){return await(async(e,t)=>await qf(e,t))(e.loadConversationSummaries(),this.client)}}const Mg=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Eg=async e=>{if("string"==typeof e||Mg(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Mg(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}})},Ug=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},kg=async e=>{await new Promise(t=>{setTimeout(t,e)})},Ng=e=>e instanceof Error?e:new Error(String(e));class Og{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,Ng(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=Ng(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=Ug(this.attempt);To("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await kg(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=Vo(),s=this.socketAdapter??Ed({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 Eg(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Ng(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(Ng(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(Ng(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(Ng(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 xg=(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 Lg(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 Pg={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"}},Dg=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),$g=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 qg{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:Gr,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:Gr}}):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=Pg[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_${Dg(e)}`,operationType:r}})(t.operation):void 0,a=i?Np(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[rl]=tl());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=$g(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=$g(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(xg(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 Lg({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 Lg({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 Bg=async(e,t,r)=>{const{orgName:s,appName:n}=Qn(e.appKey),o=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,i=new qg(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(pl(e))return pl(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 Gg,Fg,jg;(Fg=Gg||(Gg={})).assertEqual=e=>{},Fg.assertIs=function(e){},Fg.assertNever=function(e){throw new Error},Fg.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},Fg.getValidEnumValues=e=>{const t=Fg.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return Fg.objectValues(r)},Fg.objectValues=e=>Fg.objectKeys(e).map(function(t){return e[t]}),Fg.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},Fg.find=(e,t)=>{for(const r of e)if(t(r))return r},Fg.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Fg.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},Fg.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(jg||(jg={})).mergeShapes=(e,t)=>({...e,...t});const zg=Gg.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Kg=e=>{switch(typeof e){case"undefined":return zg.undefined;case"string":return zg.string;case"number":return Number.isNaN(e)?zg.nan:zg.number;case"boolean":return zg.boolean;case"function":return zg.function;case"bigint":return zg.bigint;case"symbol":return zg.symbol;case"object":return Array.isArray(e)?zg.array:null===e?zg.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?zg.promise:"undefined"!=typeof Map&&e instanceof Map?zg.map:"undefined"!=typeof Set&&e instanceof Set?zg.set:"undefined"!=typeof Date&&e instanceof Date?zg.date:zg.object;default:return zg.unknown}},Hg=Gg.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 Vg 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 Vg))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Gg.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()}}Vg.create=e=>new Vg(e);const Wg=(e,t)=>{let r;switch(e.code){case Hg.invalid_type:r=e.received===zg.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Hg.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Gg.jsonStringifyReplacer)}`;break;case Hg.unrecognized_keys:r=`Unrecognized key(s) in object: ${Gg.joinValues(e.keys,", ")}`;break;case Hg.invalid_union:r="Invalid input";break;case Hg.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Gg.joinValues(e.options)}`;break;case Hg.invalid_enum_value:r=`Invalid enum value. Expected ${Gg.joinValues(e.options)}, received '${e.received}'`;break;case Hg.invalid_arguments:r="Invalid function arguments";break;case Hg.invalid_return_type:r="Invalid function return type";break;case Hg.invalid_date:r="Invalid date";break;case Hg.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}"`:Gg.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Hg.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 Hg.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 Hg.custom:r="Invalid input";break;case Hg.invalid_intersection_types:r="Intersection results could not be merged";break;case Hg.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Hg.not_finite:r="Number must be finite";break;default:r=t.defaultError,Gg.assertNever(e)}return{message:r}};let Jg=Wg;function Zg(e,t){const r=Jg,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===Wg?void 0:Wg].filter(e=>!!e)});e.common.issues.push(s)}class Qg{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 Yg;"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 Qg.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 Yg;if("aborted"===n.status)return Yg;"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 Yg=Object.freeze({status:"aborted"}),Xg=e=>({status:"dirty",value:e}),ey=e=>({status:"valid",value:e}),ty=e=>"aborted"===e.status,ry=e=>"dirty"===e.status,sy=e=>"valid"===e.status,ny=e=>"undefined"!=typeof Promise&&e instanceof Promise;var oy,iy;(iy=oy||(oy={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},iy.toString=e=>"string"==typeof e?e:e?.message;class ay{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 cy=(e,t)=>{if(sy(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 Vg(e.common.issues);return this._error=t,this._error}}};function dy(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 uy{get description(){return this._def.description}_getType(e){return Kg(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Kg(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Qg,ctx:{common:e.parent.common,data:e.data,parsedType:Kg(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:Kg(e)},s=this._parseSync({data:e,path:r.path,parent:r});return cy(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Kg(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return sy(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=>sy(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:Kg(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(ny(s)?s:Promise.resolve(s));return cy(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:Hg.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 uv({schema:this,typeName:wv.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 lv.create(this,this._def)}nullable(){return hv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wy.create(this)}promise(){return dv.create(this,this._def)}or(e){return Qy.create([this,e],this._def)}and(e){return Xy.create(this,e,this._def)}transform(e){return new uv({...dy(this._def),schema:this,typeName:wv.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new pv({...dy(this._def),innerType:this,defaultValue:t,typeName:wv.ZodDefault})}brand(){return new gv({typeName:wv.ZodBranded,type:this,...dy(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new mv({...dy(this._def),innerType:this,catchValue:t,typeName:wv.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return yv.create(this,e)}readonly(){return vv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ly=/^c[^\s-]{8,}$/i,hy=/^[0-9a-z]+$/,py=/^[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,yy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vy=/^[-+]?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)?)??$/,by=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Iy;const 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])$/,Cy=/^(?:(?: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])$/,Sy=/^(([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]))$/,Ty=/^(([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])$/,_y=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ry=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ay="((\\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])))",My=new RegExp(`^${Ay}$`);function Ey(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 Uy(e){return new RegExp(`^${Ey(e)}$`)}function ky(e){let t=`${Ay}T${Ey(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 Ny(e,t){return!("v4"!==t&&t||!wy.test(e))||!("v6"!==t&&t||!Sy.test(e))}function Oy(e,t){if(!yy.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 xy(e,t){return!("v4"!==t&&t||!Cy.test(e))||!("v6"!==t&&t||!Ty.test(e))}class Ly extends uy{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==zg.string){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.string,received:t.parsedType}),Yg}const t=new Qg;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.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),Zg(r,{code:Hg.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?Zg(r,{code:Hg.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&Zg(r,{code:Hg.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)by.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"email",code:Hg.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)Iy||(Iy=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Iy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"emoji",code:Hg.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)fy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"uuid",code:Hg.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)gy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"nanoid",code:Hg.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)ly.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"cuid",code:Hg.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)hy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"cuid2",code:Hg.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)py.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"ulid",code:Hg.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Zg(r,{validation:"url",code:Hg.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),Zg(r,{validation:"regex",code:Hg.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),Zg(r,{code:Hg.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),Zg(r,{code:Hg.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),Zg(r,{code:Hg.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){ky(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){My.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){Uy(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?vy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"duration",code:Hg.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?Ny(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"ip",code:Hg.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?Oy(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"jwt",code:Hg.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?xy(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"cidr",code:Hg.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?_y.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"base64",code:Hg.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Ry.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"base64url",code:Hg.invalid_string,message:s.message}),t.dirty()):Gg.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Hg.invalid_string,...oy.errToObj(r)})}_addCheck(e){return new Ly({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...oy.errToObj(e)})}url(e){return this._addCheck({kind:"url",...oy.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...oy.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...oy.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...oy.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...oy.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...oy.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...oy.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...oy.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...oy.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...oy.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...oy.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...oy.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,...oy.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,...oy.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...oy.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...oy.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...oy.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...oy.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...oy.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...oy.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...oy.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...oy.errToObj(t)})}nonempty(e){return this.min(1,oy.errToObj(e))}trim(){return new Ly({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ly({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ly({...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 Py(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}Ly.create=e=>new Ly({checks:[],typeName:wv.ZodString,coerce:e?.coerce??!1,...dy(e)});class Dy extends uy{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)!==zg.number){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.number,received:t.parsedType}),Yg}let t;const r=new Qg;for(const s of this._def.checks)if("int"===s.kind)Gg.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Zg(t,{code:Hg.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),Zg(t,{code:Hg.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),Zg(t,{code:Hg.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Py(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),Zg(t,{code:Hg.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Zg(t,{code:Hg.not_finite,message:s.message}),r.dirty()):Gg.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,oy.toString(t))}gt(e,t){return this.setLimit("min",e,!1,oy.toString(t))}lte(e,t){return this.setLimit("max",e,!0,oy.toString(t))}lt(e,t){return this.setLimit("max",e,!1,oy.toString(t))}setLimit(e,t,r,s){return new Dy({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:oy.toString(s)}]})}_addCheck(e){return new Dy({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:oy.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:oy.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:oy.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:oy.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:oy.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:oy.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:oy.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:oy.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:oy.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&&Gg.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)}}Dy.create=e=>new Dy({checks:[],typeName:wv.ZodNumber,coerce:e?.coerce||!1,...dy(e)});class $y extends uy{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)!==zg.bigint)return this._getInvalidInput(e);let t;const r=new Qg;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),Zg(t,{code:Hg.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),Zg(t,{code:Hg.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),Zg(t,{code:Hg.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Gg.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.bigint,received:t.parsedType}),Yg}gte(e,t){return this.setLimit("min",e,!0,oy.toString(t))}gt(e,t){return this.setLimit("min",e,!1,oy.toString(t))}lte(e,t){return this.setLimit("max",e,!0,oy.toString(t))}lt(e,t){return this.setLimit("max",e,!1,oy.toString(t))}setLimit(e,t,r,s){return new $y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:oy.toString(s)}]})}_addCheck(e){return new $y({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:oy.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:oy.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:oy.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:oy.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:oy.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}}$y.create=e=>new $y({checks:[],typeName:wv.ZodBigInt,coerce:e?.coerce??!1,...dy(e)});class qy extends uy{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==zg.boolean){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.boolean,received:t.parsedType}),Yg}return ey(e.data)}}qy.create=e=>new qy({typeName:wv.ZodBoolean,coerce:e?.coerce||!1,...dy(e)});class By extends uy{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==zg.date){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.date,received:t.parsedType}),Yg}if(Number.isNaN(e.data.getTime())){return Zg(this._getOrReturnCtx(e),{code:Hg.invalid_date}),Yg}const t=new Qg;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.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),Zg(r,{code:Hg.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):Gg.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new By({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:oy.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:oy.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}}By.create=e=>new By({checks:[],coerce:e?.coerce||!1,typeName:wv.ZodDate,...dy(e)});class Gy extends uy{_parse(e){if(this._getType(e)!==zg.symbol){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.symbol,received:t.parsedType}),Yg}return ey(e.data)}}Gy.create=e=>new Gy({typeName:wv.ZodSymbol,...dy(e)});class Fy extends uy{_parse(e){if(this._getType(e)!==zg.undefined){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.undefined,received:t.parsedType}),Yg}return ey(e.data)}}Fy.create=e=>new Fy({typeName:wv.ZodUndefined,...dy(e)});class jy extends uy{_parse(e){if(this._getType(e)!==zg.null){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.null,received:t.parsedType}),Yg}return ey(e.data)}}jy.create=e=>new jy({typeName:wv.ZodNull,...dy(e)});class zy extends uy{constructor(){super(...arguments),this._any=!0}_parse(e){return ey(e.data)}}zy.create=e=>new zy({typeName:wv.ZodAny,...dy(e)});class Ky extends uy{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ey(e.data)}}Ky.create=e=>new Ky({typeName:wv.ZodUnknown,...dy(e)});class Hy extends uy{_parse(e){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.never,received:t.parsedType}),Yg}}Hy.create=e=>new Hy({typeName:wv.ZodNever,...dy(e)});class Vy extends uy{_parse(e){if(this._getType(e)!==zg.undefined){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.void,received:t.parsedType}),Yg}return ey(e.data)}}Vy.create=e=>new Vy({typeName:wv.ZodVoid,...dy(e)});class Wy extends uy{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==zg.array)return Zg(t,{code:Hg.invalid_type,expected:zg.array,received:t.parsedType}),Yg;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(Zg(t,{code:e?Hg.too_big:Hg.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&&(Zg(t,{code:Hg.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&&(Zg(t,{code:Hg.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 ay(t,e,t.path,r)))).then(e=>Qg.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new ay(t,e,t.path,r)));return Qg.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Wy({...this._def,minLength:{value:e,message:oy.toString(t)}})}max(e,t){return new Wy({...this._def,maxLength:{value:e,message:oy.toString(t)}})}length(e,t){return new Wy({...this._def,exactLength:{value:e,message:oy.toString(t)}})}nonempty(e){return this.min(1,e)}}function Jy(e){if(e instanceof Zy){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=lv.create(Jy(s))}return new Zy({...e._def,shape:()=>t})}return e instanceof Wy?new Wy({...e._def,type:Jy(e.element)}):e instanceof lv?lv.create(Jy(e.unwrap())):e instanceof hv?hv.create(Jy(e.unwrap())):e instanceof ev?ev.create(e.items.map(e=>Jy(e))):e}Wy.create=(e,t)=>new Wy({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wv.ZodArray,...dy(t)});class Zy extends uy{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=Gg.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==zg.object){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.object,received:t.parsedType}),Yg}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),o=[];if(!(this._def.catchall instanceof Hy&&"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 ay(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof Hy){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&&(Zg(r,{code:Hg.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 ay(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=>Qg.mergeObjectSync(t,e)):Qg.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return oy.errToObj,new Zy({...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:oy.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Zy({...this._def,unknownKeys:"strip"})}passthrough(){return new Zy({...this._def,unknownKeys:"passthrough"})}extend(e){return new Zy({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Zy({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:wv.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Zy({...this._def,catchall:e})}pick(e){const t={};for(const r of Gg.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Zy({...this._def,shape:()=>t})}omit(e){const t={};for(const r of Gg.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Zy({...this._def,shape:()=>t})}deepPartial(){return Jy(this)}partial(e){const t={};for(const r of Gg.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new Zy({...this._def,shape:()=>t})}required(e){const t={};for(const r of Gg.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof lv;)e=e._def.innerType;t[r]=e}return new Zy({...this._def,shape:()=>t})}keyof(){return iv(Gg.objectKeys(this.shape))}}Zy.create=(e,t)=>new Zy({shape:()=>e,unknownKeys:"strip",catchall:Hy.create(),typeName:wv.ZodObject,...dy(t)}),Zy.strictCreate=(e,t)=>new Zy({shape:()=>e,unknownKeys:"strict",catchall:Hy.create(),typeName:wv.ZodObject,...dy(t)}),Zy.lazycreate=(e,t)=>new Zy({shape:e,unknownKeys:"strip",catchall:Hy.create(),typeName:wv.ZodObject,...dy(t)});class Qy extends uy{_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 Vg(e.ctx.common.issues));return Zg(t,{code:Hg.invalid_union,unionErrors:r}),Yg});{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 Vg(e));return Zg(t,{code:Hg.invalid_union,unionErrors:n}),Yg}}get options(){return this._def.options}}function Yy(e,t){const r=Kg(e),s=Kg(t);if(e===t)return{valid:!0,data:e};if(r===zg.object&&s===zg.object){const r=Gg.objectKeys(t),s=Gg.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const o of s){const r=Yy(e[o],t[o]);if(!r.valid)return{valid:!1};n[o]=r.data}return{valid:!0,data:n}}if(r===zg.array&&s===zg.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=Yy(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===zg.date&&s===zg.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Qy.create=(e,t)=>new Qy({options:e,typeName:wv.ZodUnion,...dy(t)});class Xy extends uy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(ty(e)||ty(s))return Yg;const n=Yy(e.value,s.value);return n.valid?((ry(e)||ry(s))&&t.dirty(),{status:t.value,value:n.data}):(Zg(r,{code:Hg.invalid_intersection_types}),Yg)};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}))}}Xy.create=(e,t,r)=>new Xy({left:e,right:t,typeName:wv.ZodIntersection,...dy(r)});class ev extends uy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==zg.array)return Zg(r,{code:Hg.invalid_type,expected:zg.array,received:r.parsedType}),Yg;if(r.data.length<this._def.items.length)return Zg(r,{code:Hg.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Yg;!this._def.rest&&r.data.length>this._def.items.length&&(Zg(r,{code:Hg.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 ay(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>Qg.mergeArray(t,e)):Qg.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ev({...this._def,rest:e})}}ev.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ev({items:e,typeName:wv.ZodTuple,rest:null,...dy(t)})};class tv extends uy{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!==zg.object)return Zg(r,{code:Hg.invalid_type,expected:zg.object,received:r.parsedType}),Yg;const s=[],n=this._def.keyType,o=this._def.valueType;for(const i in r.data)s.push({key:n._parse(new ay(r,i,r.path,i)),value:o._parse(new ay(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?Qg.mergeObjectAsync(t,s):Qg.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new tv(t instanceof uy?{keyType:e,valueType:t,typeName:wv.ZodRecord,...dy(r)}:{keyType:Ly.create(),valueType:e,typeName:wv.ZodRecord,...dy(t)})}}class rv extends uy{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!==zg.map)return Zg(r,{code:Hg.invalid_type,expected:zg.map,received:r.parsedType}),Yg;const s=this._def.keyType,n=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:s._parse(new ay(r,e,r.path,[o,"key"])),value:n._parse(new ay(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 Yg;"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 Yg;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}rv.create=(e,t,r)=>new rv({valueType:t,keyType:e,typeName:wv.ZodMap,...dy(r)});class sv extends uy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==zg.set)return Zg(r,{code:Hg.invalid_type,expected:zg.set,received:r.parsedType}),Yg;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(Zg(r,{code:Hg.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&&(Zg(r,{code:Hg.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 Yg;"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 ay(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>o(e)):o(i)}min(e,t){return new sv({...this._def,minSize:{value:e,message:oy.toString(t)}})}max(e,t){return new sv({...this._def,maxSize:{value:e,message:oy.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}sv.create=(e,t)=>new sv({valueType:e,minSize:null,maxSize:null,typeName:wv.ZodSet,...dy(t)});class nv extends uy{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})}}nv.create=(e,t)=>new nv({getter:e,typeName:wv.ZodLazy,...dy(t)});class ov extends uy{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Zg(t,{received:t.data,code:Hg.invalid_literal,expected:this._def.value}),Yg}return{status:"valid",value:e.data}}get value(){return this._def.value}}function iv(e,t){return new av({values:e,typeName:wv.ZodEnum,...dy(t)})}ov.create=(e,t)=>new ov({value:e,typeName:wv.ZodLiteral,...dy(t)});class av extends uy{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return Zg(t,{expected:Gg.joinValues(r),received:t.parsedType,code:Hg.invalid_type}),Yg}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 Zg(t,{received:t.data,code:Hg.invalid_enum_value,options:r}),Yg}return ey(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 av.create(e,{...this._def,...t})}exclude(e,t=this._def){return av.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}av.create=iv;class cv extends uy{_parse(e){const t=Gg.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==zg.string&&r.parsedType!==zg.number){const e=Gg.objectValues(t);return Zg(r,{expected:Gg.joinValues(e),received:r.parsedType,code:Hg.invalid_type}),Yg}if(this._cache||(this._cache=new Set(Gg.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Gg.objectValues(t);return Zg(r,{received:r.data,code:Hg.invalid_enum_value,options:e}),Yg}return ey(e.data)}get enum(){return this._def.values}}cv.create=(e,t)=>new cv({values:e,typeName:wv.ZodNativeEnum,...dy(t)});class dv extends uy{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==zg.promise&&!1===t.common.async)return Zg(t,{code:Hg.invalid_type,expected:zg.promise,received:t.parsedType}),Yg;const r=t.parsedType===zg.promise?t.data:Promise.resolve(t.data);return ey(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}dv.create=(e,t)=>new dv({type:e,typeName:wv.ZodPromise,...dy(t)});class uv extends uy{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wv.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=>{Zg(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 Yg;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?Yg:"dirty"===s.status||"dirty"===t.value?Xg(s.value):s});{if("aborted"===t.value)return Yg;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?Yg:"dirty"===s.status||"dirty"===t.value?Xg(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?Yg:("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?Yg:("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(!sy(e))return Yg;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=>sy(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):Yg)}Gg.assertNever(s)}}uv.create=(e,t,r)=>new uv({schema:e,typeName:wv.ZodEffects,effect:t,...dy(r)}),uv.createWithPreprocess=(e,t,r)=>new uv({schema:t,effect:{type:"preprocess",transform:e},typeName:wv.ZodEffects,...dy(r)});class lv extends uy{_parse(e){return this._getType(e)===zg.undefined?ey(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}lv.create=(e,t)=>new lv({innerType:e,typeName:wv.ZodOptional,...dy(t)});class hv extends uy{_parse(e){return this._getType(e)===zg.null?ey(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}hv.create=(e,t)=>new hv({innerType:e,typeName:wv.ZodNullable,...dy(t)});class pv extends uy{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===zg.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}pv.create=(e,t)=>new pv({innerType:e,typeName:wv.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...dy(t)});class mv extends uy{_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 Vg(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Vg(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}mv.create=(e,t)=>new mv({innerType:e,typeName:wv.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...dy(t)});class fv extends uy{_parse(e){if(this._getType(e)!==zg.nan){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.nan,received:t.parsedType}),Yg}return{status:"valid",value:e.data}}}fv.create=e=>new fv({typeName:wv.ZodNaN,...dy(e)});class gv extends uy{_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 yv extends uy{_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?Yg:"dirty"===e.status?(t.dirty(),Xg(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?Yg:"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 yv({in:e,out:t,typeName:wv.ZodPipeline})}}class vv extends uy{_parse(e){const t=this._def.innerType._parse(e),r=e=>(sy(e)&&(e.value=Object.freeze(e.value)),e);return ny(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function bv(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Iv(e,t={},r){return e?zy.create().superRefine((s,n)=>{const o=e(s);if(o instanceof Promise)return o.then(e=>{if(!e){const e=bv(t,s),o=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:o})}});if(!o){const e=bv(t,s),o=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:o})}}):zy.create()}var wv,Cv;vv.create=(e,t)=>new vv({innerType:e,typeName:wv.ZodReadonly,...dy(t)}),(Cv=wv||(wv={})).ZodString="ZodString",Cv.ZodNumber="ZodNumber",Cv.ZodNaN="ZodNaN",Cv.ZodBigInt="ZodBigInt",Cv.ZodBoolean="ZodBoolean",Cv.ZodDate="ZodDate",Cv.ZodSymbol="ZodSymbol",Cv.ZodUndefined="ZodUndefined",Cv.ZodNull="ZodNull",Cv.ZodAny="ZodAny",Cv.ZodUnknown="ZodUnknown",Cv.ZodNever="ZodNever",Cv.ZodVoid="ZodVoid",Cv.ZodArray="ZodArray",Cv.ZodObject="ZodObject",Cv.ZodUnion="ZodUnion",Cv.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Cv.ZodIntersection="ZodIntersection",Cv.ZodTuple="ZodTuple",Cv.ZodRecord="ZodRecord",Cv.ZodMap="ZodMap",Cv.ZodSet="ZodSet",Cv.ZodFunction="ZodFunction",Cv.ZodLazy="ZodLazy",Cv.ZodLiteral="ZodLiteral",Cv.ZodEnum="ZodEnum",Cv.ZodEffects="ZodEffects",Cv.ZodNativeEnum="ZodNativeEnum",Cv.ZodOptional="ZodOptional",Cv.ZodNullable="ZodNullable",Cv.ZodDefault="ZodDefault",Cv.ZodCatch="ZodCatch",Cv.ZodPromise="ZodPromise",Cv.ZodBranded="ZodBranded",Cv.ZodPipeline="ZodPipeline",Cv.ZodReadonly="ZodReadonly";const Sv=Ly.create,Tv=Dy.create,_v=qy.create;zy.create;const Rv=Ky.create,Av=Hy.create,Mv=Wy.create,Ev=Zy.create,Uv=Qy.create;Xy.create,ev.create;const kv=tv.create,Nv=av.create;dv.create,lv.create,hv.create;class Ov{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof Vg){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 xv=e=>Sv().regex(/^https?:\/\/\S+$/i,e),Lv=e=>Sv().regex(/^wss?:\/\/\S+$/i,e),Pv=Ev({appKey:Sv().min(1,"appKey is required"),enableUserInfoSync:_v().optional(),enableSyncData:Mv(Nv(["conversation","contact","group"])).optional(),enableDeliveryReceipt:_v().optional(),deleteConversationOnGroupDestroyed:_v().optional(),syncConversationListConfig:Ev({includeEmpty:_v().optional()}).strict().optional(),useCustomAttachmentUpload:_v().optional(),useFixedDeviceId:_v().optional(),deviceId:Sv().min(1,"deviceId is required").optional(),serviceConfig:Ev({dnsConfigUrls:Mv(xv("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:Ev({restApiUrl:xv("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:Lv("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:xv("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:Lv("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:_v().optional(),customDeviceName:Sv().min(1,"customDeviceName is required").optional(),customOSPlatform:Tv().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:Sv().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Sv().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:Mv(Rv()).optional(),platformAdapterOptions:Ev({prefer:Nv(["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:Iv(e=>"object"==typeof e&&null!==e).optional(),overrides:Iv(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{"enableMd5Check"in e&&t.addIssue({code:Hg.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:Hg.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:Hg.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:Hg.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:Hg.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:Hg.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:Hg.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:Hg.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),s&&(s?.restApiUrl||t.addIssue({code:Hg.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),s?.wsUrl||t.addIssue({code:Hg.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),Dv=Ev({userId:Sv().min(1,"userId is required"),token:Sv().min(1,"token is required")}),$v=Sv().trim().min(1,"token is required"),qv=Ev({channelName:Sv().trim().min(1,"channelName is required").optional()}).optional(),Bv=Mv(Tv({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))),Gv=Ev({protocol:Sv(),domain:Sv().optional(),ip:Sv().optional(),port:Uv([Sv(),Tv()]).optional()}).passthrough(),Fv=Ev({rest:Ev({hosts:Mv(Gv).nonempty()}),"msync-wx":Ev({hosts:Mv(Gv).nonempty()}),"sync-ws":Ev({hosts:Mv(Gv).nonempty()}).optional(),enableReportLogs:Nv(["true","false"]).optional(),reportInterval:Tv().positive().finite().optional(),enableDataReport:Nv(["true","false"]).optional(),enableMd5Check:Nv(["true","false"]).optional(),uploadinparts_enable:Nv(["true","false"]).optional()}).passthrough(),jv=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],zv=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],Kv=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function Hv(e){return"object"==typeof e&&null!==e}function Vv(e){return Array.isArray(e)?{hosts:e}:function(e){return Hv(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Wv(e,t,r){for(const s of t){const t=Vv(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=Vv(n);if(e)return{key:s,section:e}}}function Jv(e){if(!Hv(e))return Ov.validateOrThrow(Fv,e);const t=Vv(e.rest),r=Wv(e,zv,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s=Wv(e,Kv,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&&!Vv(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}),Ov.validateOrThrow(Fv,n)}function Zv(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 Qv(e,t){return"https"===e?"https":"http"===e?"http":t}function Yv(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 Xv(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 tb(e,t,r){const s=new qg(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}?${new URLSearchParams({app_key:t,_v:String(Date.now())}).toString()}`}return Jv(await s.get(n))}function rb(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,Qv(e.protocol,t))).filter(e=>"string"==typeof e&&e.length>0):[]}async function sb(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:jv;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 tb(i,e.appKey,e.requestAdapter),s=eb(Xv(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=Xv(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=>Zv(e,Qv(e.protocol,r))),d=Zv(n,Qv(n.protocol,r)),u=rb(t,r);return{websocketUrl:d,websocketUrls:c,syncWebsocketUrls:u,baseUrl:i,restBaseUrl:Yv(a,Qv(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 nb=e=>new Zr(e,{code:ot,details:{reason:"invalid_rest_response"}}),ob=e=>{if(!pl(e))throw nb("Invalid REST response");return pl(e.data)?e.data:e},ib=(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}}},ab=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},cb=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},db=async(e,t)=>{const r=await e.get((e=>`${cb(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=ob(e),r=ib(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw nb("Invalid token expires response");return r})(r)},ub=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=new URLSearchParams({channelName:t?.channelName??"*"});return`${cb(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=ob(e);return{appId:ab(t,["app_id","appId"])??"",rtcToken:ab(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:ab(t,["channel_name","channelName"])??"",rtcUid:ib(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:ib(t,["expires_in","expire","expireAt"])??0}})(s)},lb=async(e,t,r)=>{const s=await e.post((e=>`${cb(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=ob(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)},hb=async(e,t)=>{const r=await e.get((e=>`${cb(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=pl(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!pl(n))continue;const e=ab(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},pb=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},mb={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:{}},fb=e=>({userId:e}),gb=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),yb=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 i of n)s.set(i.userId,gb(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,yb(t))}for(const i of r)s.has(i)||s.set(i,fb(i));return s};class bb{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 Ib{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 wb=0,Cb=1,Sb=2,Tb=3,_b=4,Rb=5,Ab=0,Mb=0,Eb=1,Ub=1001,kb=1002,Nb=1003,Ob=1004,xb=1005,Lb=1101,Pb=pb(mb,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Db=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=$u(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new Nf,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 Ib({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new bb({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)},[B]:e=>{this.handleMultiDeviceContactEvent(e)},[G]: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=Ov.validateOrThrow(Pv,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=Ov.validateOrThrow(Dv,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??$u(this.config.platformAdapterOptions);var c;this.platformAdapter=a,c={requestAdapter:a.request,onDiagnostic:(e,t)=>{To(e,t)}},Ep?.reset(),Ep=new Mp(c);const d=(e=>Ep?.startSession(e))({appKey:this.config.appKey,uid:o.userId,sdkVersion:"5.0.0-beta.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=>{kp(e)}).catch(()=>{kp("unknown")});const l=Np({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 sb({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}),Up(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}),Up(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}),Up(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,Up(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),Op(),e}this.core=new Nm({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=>{Ep?.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),Op(),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 Op();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(),Op()}}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=Ov.validateOrThrow($v,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 qg(n.restBaseUrl,{errorMap:Pb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});o.setAuthToken(t),To("Renew token started",{userId:r.userId});const i=await db(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=Ov.validateOrThrow(qv,e),r=this.getRestContext(),s=new qg(r.restBaseUrl,{errorMap:Pb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),To("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),ub(s,r,t)}async getUserIdsWithRTCUids(e){const t=Ov.validateOrThrow(Bv,e),r=this.getRestContext(),s=new qg(r.restBaseUrl,{errorMap:Pb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),To("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),lb(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new qg(e.restBaseUrl,{errorMap:Pb,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}),hb(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 Og({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:Yl(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 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=Jl(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=>{Vl.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};Wl(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 kf({appKey:this.config.appKey,userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode}),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(vg),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 Ag(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 Bg(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 sb({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=new URL(e);return""!==r.pathname&&"/"!==r.pathname||(r.pathname="/ws"),r.searchParams.set("token",t),r.toString()}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:Tb,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??jv,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)}};Db.instance=null;let $b=Db;const qb=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Bb=(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()},Gb=e=>`mark_${String(e)}`,Fb=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw qb(t,`${t} must be one of singleChat, groupChat, chatRoom`)},jb=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",zb=e=>"string"==typeof e&&e.length>0?e:void 0,Kb=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}},Hb=e=>pl(e)?e:void 0,Vb=(e,t)=>{const r=Hb(e);if(!r)return;const s=(e=>"string"==typeof e?ml(e,{}):Hb(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],o=Hb(n[0])??Hb(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:zb(t.msg)??zb(t.content)??""};if("custom"===e){const e=Hb(t.customExts)??Hb(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:zb(t.customEvent)??zb(t.event)??"",params:r}}if("cmd"===e)return{action:zb(t.action)??""};if("image"===e){const e=zb(t.url)??zb(t.remotePath)??"";return{localUrl:"",filename:zb(t.filename)??zb(t.displayName),filetype:zb(t.filetype)??"application/octet-stream",width:Kb(t.width),height:Kb(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:zb(t.bigImageUrl),thumbnailUrl:zb(t.thumbnailUrl)??zb(t.thumbnailRemotePath),secret:zb(t.secret)??zb(t.secretKey),fileLength:Kb(t.fileLength)}}return"file"===e?{url:zb(t.url)??zb(t.remotePath),filename:zb(t.filename)??zb(t.displayName),filetype:zb(t.filetype)??"application/octet-stream",fileSize:Kb(t.fileSize),fileLength:Kb(t.fileLength),secret:zb(t.secret)??zb(t.secretKey)}:"voice"===e?{url:zb(t.url)??zb(t.remotePath),filename:zb(t.filename)??zb(t.displayName),filetype:zb(t.filetype)??"application/octet-stream",duration:Kb(t.duration)??0,fileLength:Kb(t.fileLength),secret:zb(t.secret)??zb(t.secretKey)}:"video"===e?{url:zb(t.url)??zb(t.remotePath),filename:zb(t.filename)??zb(t.displayName),filetype:zb(t.filetype)??"application/octet-stream",duration:Kb(t.duration)??0,width:Kb(t.width),height:Kb(t.height),fileLength:Kb(t.fileLength),secret:zb(t.secret)??zb(t.secretKey),thumbnailUrl:zb(t.thumbnailUrl)??zb(t.thumbnailRemotePath)}:"location"===e?{latitude:Kb(t.latitude)??0,longitude:Kb(t.longitude)??0,address:zb(t.address),buildingName:zb(t.buildingName)}:null})(i,o);if(!a)return;const c=zb(s.from)??zb(r.from)??"",d=zb(s.to)??t.conversationId,u=Hb(s.sender),l={userId:zb(u?.userId)??c,nickname:zb(u?.nickname),avatarUrl:zb(u?.avatarUrl)},h=Hb(s.ext)??{},p=(e=>{const t=Hb(e);if(!t)return;const r=zb(t.operatorId)??zb(t.operator),s=Kb(t.operationCount)??Kb(t.count),n=Kb(t.operationTime)??Kb(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??Hb(s.meta)?.edit_msg);return{msgServerId:zb(r.id)??t.messageId,msgLocalId:zb(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:i,sendStatus:"sent",ext:h,timestamp:Kb(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},Wb=e=>`${e.conversationType}:${e.conversationId}`,Jb=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},Zb=async(e,t,r,s)=>{const n=Jb(t),o=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw qb("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!pl(e))throw qb(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:Bb(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:Fb(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:Bb(t.conversationId,"params.conversationId"),conversationType:Fb(t.conversationType,"params.conversationType")}]})(r),i=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw qb(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:Gb(i),targets:o.map(e=>({to:e.conversationId,type:jb(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!pl(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(Wb({conversationId:r,conversationType:s}))}),t})((pl(a)&&pl(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of o){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(Wb(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:i,operation:s?"addMark":"removeMark"}},Qb=async(e,t,r,s)=>{const n=Jb(t),o=Bb(r.conversationId,"params.conversationId"),i=Fb(r.conversationType,"params.conversationType"),a=Bb(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:jb(i),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:o,conversationType:i,messageId:a,operation:s?"pin":"unpin"}},Yb=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Xb=(e,t)=>`${e}\0${t}`,eI=(e,t,r)=>{const s={userId:e};for(const n of Yb){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},tI=e=>eI(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),rI=(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(Xb(n.groupId,n.user.userId),t.namecard)}return s},sI=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}),[]}},nI=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})}}))},oI=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=Xb(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,tI(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),o=new Set(n),i=rI(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=Xb(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([sI(n,e.fetchUserInfos),nI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=rI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=Xb(h.groupId,e),r=eI(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))}},iI=async e=>{const t=await oI({...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(Xb(e.groupId.trim(),n));o&&r.set(n,o)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},aI=Nv(["singleChat","groupChat","chatRoom"]),cI=kv(Rv()).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"),dI=Ev({path:Sv().min(1,"data.path is required"),size:Tv().optional(),name:Sv().optional(),type:Sv().optional()}),uI=Ev({uri:Sv().min(1,"data.uri is required"),size:Tv().optional(),name:Sv().optional(),type:Sv().optional()}),lI=Uv(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>Iv(t=>t instanceof e,t))(File):Av(),dI,uI]),hI=Ev({conversationId:Sv().min(1,"conversationId is required"),conversationType:aI,ext:cI.optional(),timestamp:Tv().int().positive("timestamp must be a positive integer").optional(),receiverList:Mv(Sv().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:_v().optional(),webhookEnv:Sv().optional(),priority:Nv(["high","normal","low"]).optional(),needReadReceipt:_v().optional(),isChatThread:_v().optional()}),pI=Ev({type:Sv().min(1,"messageList.type is required"),sender:Ev({userId:Sv().min(1,"messageList.sender.userId is required"),nickname:Sv().optional(),avatarUrl:Sv().optional()}),conversationId:Sv().min(1,"messageList.conversationId is required"),conversationType:aI,timestamp:Tv().int().positive("messageList.timestamp must be positive"),body:kv(Rv()),combineLevel:Tv().int().min(0).max(10).optional()}).passthrough(),mI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:Hg.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:Hg.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:Hg.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),fI=mI(hI.extend({content:Sv().min(1,"content is required"),targetLanguages:Mv(Sv().min(1)).optional()})),gI=mI(hI.extend({originalUrl:Sv().min(1,"originalUrl is required").optional(),filename:Sv().min(1,"filename is required").optional(),filetype:Sv().min(1,"filetype is required").optional(),width:Tv().positive("width must be positive").optional(),height:Tv().positive("height must be positive").optional(),isGif:_v().optional(),isOriginalImage:_v().optional(),fileLength:Tv().positive("fileLength must be positive").optional(),data:lI.optional(),thumbnailUrl:Sv().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),yI=mI(hI.extend({originalUrl:Sv().min(1,"originalUrl is required").optional(),filename:Sv().min(1,"filename is required").optional(),filetype:Sv().min(1,"filetype is required").optional(),fileSize:Tv().positive("fileSize must be positive").optional(),fileLength:Tv().positive("fileLength must be positive").optional(),data:lI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),vI=mI(hI.extend({originalUrl:Sv().min(1,"originalUrl is required").optional(),filename:Sv().min(1,"filename is required").optional(),filetype:Sv().min(1,"filetype is required").optional(),duration:Tv().positive("duration must be positive"),fileLength:Tv().positive("fileLength must be positive").optional(),data:lI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),bI=mI(hI.extend({originalUrl:Sv().min(1,"originalUrl is required").optional(),filename:Sv().min(1,"filename is required").optional(),filetype:Sv().min(1,"filetype is required").optional(),duration:Tv().positive("duration must be positive"),width:Tv().positive("width must be positive").optional(),height:Tv().positive("height must be positive").optional(),fileLength:Tv().positive("fileLength must be positive").optional(),thumbnailUrl:Sv().min(1).optional(),data:lI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),II=mI(hI.extend({latitude:Tv(),longitude:Tv(),address:Sv().min(1).optional(),buildingName:Sv().min(1).optional()})),wI=mI(hI.extend({action:Sv().min(1,"action is required")})),CI=mI(hI.extend({event:Sv().min(1,"event is required"),params:kv(Sv()).optional()})),SI=mI(hI.extend({title:Sv().min(1,"title is required"),summary:Sv().min(1,"summary is required"),compatibleText:Sv().min(1).optional(),messageList:Mv(pI).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),TI=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=()=>Dp(),RI=(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=Pp(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},AI=e=>!!e.isGif||(e.isOriginalImage??!1),MI=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??Dp(),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}),EI=(e,t)=>{const r=Ov.validateOrThrow(SI,e),s=r.messageList,n=TI(t);rm(s);const o=sm(s);nm(o);const i={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:o},a=MI(r,n,"combine",i);return((e,t)=>{t&&Xl.set(e,t)})(a,r.compatibleText),a},UI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},kI=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},NI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),OI=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})}},xI=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",LI=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},PI=e=>({userId:e}),DI=(e,t)=>{if(!NI(e)||!NI(e.data))throw Lg({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},$I=(e,t)=>{if(!NI(e)||!Array.isArray(e.data))throw Lg({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},qI=(e,t)=>Array.isArray(e)?e:$I(e,t),BI={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},GI={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},FI={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},jI=(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)},zI=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},KI=(e,t,r)=>{const s=xI(r.contentType??r.type),n=GI[s];if(!n)return null;const o=NI(r.content)?r.content:{},i=((e,t)=>{const r=xI(t.conversationType);if("groupchat"===r||"chatroom"===r)return xI(t.receiverId);const s=xI(t.senderId);return s===e?xI(t.receiverId):s})(t,r),a=FI[xI(r.conversationType)]??"singleChat",c={msgServerId:xI(r.messageId),msgLocalId:xI(r.messageId),from:xI(r.senderId),to:xI(r.receiverId),conversationId:i,conversationType:a,type:n,ext:NI(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(xI(r.sentTime)).getTime(),sender:{userId:xI(r.senderId)},highlight:zI(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=xI(o.remotePath??o.url),l=xI(o.secret??o.secretKey);switch(n){case"txt":d={type:"txt",content:xI(o.message??r.text)};break;case"img":{const t=jI(e,u,l);d={type:"img",url:t,thumb:o.thumb?jI(e,xI(o.thumb),xI(o.thumb_secret??o.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(o.width??(NI(o.size)?o.size.width:0))||0,height:Number(o.height??(NI(o.size)?o.size.height:0))||0,fileLength:Number(o.file_length??o.fileLength??0)};break}case"video":d={type:"video",url:jI(e,u,l),thumb:o.thumb||o.thumbnailRemotePath?jI(e,xI(o.thumb??o.thumbnailRemotePath),xI(o.thumb_secret??o.thumbnailSecretKey)):"",secret:l,filename:xI(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:jI(e,u,l),secret:l,filename:xI(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:xI(o.addr??o.address),buildingName:xI(o.buildingName)};break;case"custom":d={type:"custom",customEvent:xI(o.customEvent),customExts:NI(o.customExts)?o.customExts:{}};break;default:return null}return{...c,body:d}},HI=async(e,t,r)=>{const s=`${UI(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=>BI[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=NI(o)?o:{},a=NI(i.data)?i.data:i,c=NI(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=NI(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(!NI(g))continue;const e=KI(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:h,totalPages:p,isLast:m}},VI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/api/sdk/v1/${t}/${r}`},WI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),JI=e=>WI(e)&&"string"==typeof e.path&&e.path.trim().length>0,ZI=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||JI(e),QI=e=>{if(!WI(e))return;return{data:WI(e.data)?e.data:void 0,error:WI(e.error)?e.error:void 0}},YI=(e,t)=>{const r=QI(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},XI=(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||WI(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))),tw=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},rw=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof Hr&&WI(e.details)?e.details:void 0,r=QI(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 XI("File upload failed",$r,{cause:e.details});if(e instanceof Hr&&!t)return e;if(t)switch(t){case"4041001":return XI("File not found",Or,{serviceCode:t,serviceMessage:r});case"4001002":return XI("Invalid file",Ur,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return XI("File upload failed",$r,{serviceCode:t,serviceMessage:r});case"4001003":return XI("Voice duration exceeds 60 seconds",kr,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return XI("Voice-to-text service is not enabled",$t,{serviceCode:t,serviceMessage:r});case"4031002":return XI("Beta service usage limit exceeded",Gr,{serviceCode:t,serviceMessage:r});case"4001001":return"string"==typeof(s=r)&&s.toLowerCase().includes("uploaded file exceeds")?XI("File too large",xr,{serviceCode:t,serviceMessage:r}):XI(r||"Missing or invalid request parameter",nt,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return XI("Voice-to-text failed",Nr,{serviceCode:t,serviceMessage:r});case"4011001":return XI(r||"Unauthorized or invalid token",dt,{serviceCode:t,serviceMessage:r},"auth");default:return XI(r||(e instanceof Error?e.message:"Voice-to-text failed"),Nr,{serviceCode:t,serviceMessage:r})}var s;return e instanceof Hr?XI(e.message,e.code,e.details):XI(e instanceof Error?e.message:"Voice-to-text failed",Nr)},sw=(e,t)=>{if(!WI(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 XI("Invalid file",Ur,{path:"voiceMessageBody"},"validation");var r;if(ew(t))throw XI("Invalid file",Ur,{path:"voiceParams"},"validation");if(!e.url)throw XI("File not found",Or,{path:"voiceMessageBody.url"});if(!tw(e.url))throw XI("Invalid file",Ur,{path:"voiceMessageBody.url"},"validation");return e},nw=(e,t)=>{if(ew(t))throw XI("Invalid file",Ur,{path:"voiceParams"},"validation");if(!ZI(e))throw XI("Invalid file",Ur,{path:"file"},"validation");return e},ow=async(e,t,r,s)=>{const n=sw(r,s),o=tw(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(`${VI(t)}/speech/transcriptions`,{data:{fileId:o,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:YI(r,"voiceMessageToText")}}catch(i){throw rw(i)}},iw=Ev({keywordList:Mv(Sv()).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:Nv(["or","and"]).optional(),conversationId:Sv().min(1).optional(),conversationType:Nv(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:Mv(Nv(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Tv().optional(),endTime:Tv().optional(),searchScope:Nv(["none","with","only"]).optional(),direction:Nv(["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"}),aw=Ev({option:iw,pageNum:Tv().int().min(1).default(1),pageSize:Tv().int().min(1).max(100).default(20)}),cw=pb(mb,{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"]}}}}}),dw=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=Ov.validateOrThrow(fI,e),s=TI(t),n=_I(),o={content:r.content};return r.targetLanguages&&(o.targetLanguages=r.targetLanguages),MI(r,s,"text",o,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=Ov.validateOrThrow(gI,e),n=TI(t),o=_I(),i=s.data?RI(void 0,s.data):"",a=s.originalUrl?no(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&Lp.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:AI({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),MI(s,n,"image",d,o)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(yI,e),s=TI(t),n=_I(),o=RI(r.originalUrl,r.data);r.data&&Lp.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),MI(r,s,"file",i,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(vI,e),s=TI(t),n=_I(),o=RI(r.originalUrl,r.data);r.data&&Lp.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),MI(r,s,"voice",i,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(bI,e),s=TI(t),n=_I(),o=RI(r.originalUrl,r.data);r.data&&Lp.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),MI(r,s,"video",i,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(II,e),s=TI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),MI(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(wI,e),s=TI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),MI(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(CI,e),s=TI(t),n={event:r.event};return r.params&&(n.params=r.params),MI(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return EI(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(vg);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=Jb(t),n=Bb(r.conversationId,"params.conversationId"),o=Fb(r.conversationType,"params.conversationType"),i=r.deleteRoamingMessages??!1;if("boolean"!=typeof i)throw qb("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":jb(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=Jb(t),n=Bb(r.conversationId,"params.conversationId"),o=Fb(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw qb("params.pinned","params.pinned must be a boolean");const i="groupChat"===o?"groupChat":jb(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=pl(a)&&pl(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)=>Zb(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)=>Zb(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=Jb(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)=>Qb(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>Qb(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=Jb(t),n=Bb(r.conversationId,"params.conversationId"),o=Fb(r.conversationType,"params.conversationType"),i=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(jb(o))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=pl(i)&&pl(i.data)?i.data:{};return{items:(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!pl(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:pl(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=Vb(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=`${UI(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=DI(o,"getHistoryMessages"),a=Array.isArray(i.msgs)?i.msgs:[],c=[];for(const d of a){if(!NI(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(kI(d.msg));e&&c.push(e)}return{items:c,cursor:LI(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=Ov.validateOrThrow(aw,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>HI(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?`${UI(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${o}`:`${UI(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=new URLSearchParams;s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${UI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,o=await e.get(n,{operation:"getGroupMessageReadUsers"}),i=DI(o,"getGroupMessageReadUsers"),a=NI(i.group_ack)?i.group_ack:i,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>NI(e)&&"string"==typeof e.username?{userId:e.username,user:PI(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:LI(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=`${UI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return $I(n,"getGroupMessageReadReceipts").map(e=>NI(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(`${UI(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=`${UI(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=new URLSearchParams,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(`${UI(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return $I(o,"getReactionList").map(e=>{if(!NI(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>NI(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=new URLSearchParams;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(`${UI(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),o=DI(n,"getReactionDetail"),i=Array.isArray(o.reactionUserList)?o.reactionUserList.map(e=>NI(e)&&"string"==typeof e.userId?{userId:e.userId,user:PI(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:PI(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:LI(o.cursor),hasMore:LI(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 OI(()=>e.get(`${UI(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return qI(r,"getSupportedTranslationLanguages").map(e=>NI(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 OI(()=>e.post(`${UI(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=qI(s,"translateMessage"),o=NI(n[0])?n[0]:null;if(!o)throw Lg({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const i=Array.isArray(o.translations)?o.translations:[],a=NI(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=>NI(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){sw(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>ow(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){nw(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=nw(r,s),o=Fn({file:n,fallbackName:JI(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${VI(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[rl]:tl()},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:YI(n,"voiceFileToText")}}catch(i){if(i instanceof Hr)throw rw(i);throw rw(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 qg(e.restBaseUrl,{errorMap:cw,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 iI({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)}};dw.key="chatManager";let uw=dw;class lw{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 hw=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),pw=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),mw=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw hw(t);return e.trim()},fw=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw pw(t,`${t} must be a string`);return e},gw=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw pw(t,`${t} must be an integer between 1 and 50`);return e},yw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},vw=e=>pl(e)?e:null,bw=e=>{const t=vw(e);return t?.data??e},Iw=e=>{const t=vw(e);if(Array.isArray(t?.entities))return t.entities;const r=bw(e);if(Array.isArray(r))return r;const s=vw(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},ww=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)??""},Cw=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,o="string"==typeof n?ml(n,{}):vw(n)??{},i=Array.isArray(o.bodies)?o.bodies:[],a=vw(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}},Sw=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:Cw(t.lastMessage??t.last_message)}:null},Tw=e=>({items:Iw(e).map(e=>Sw(e)).filter(e=>null!==e),cursor:ww(e)}),_w=async(e,t,r)=>{const s=yw(t),n=mw(r,"chatThreadId");return(e=>{const t=bw(e),r=Array.isArray(t)?t[0]:t,s=Sw(r);if(!s)throw pw("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},Rw=async(e,t,r)=>{const s=yw(t),n=mw(r.chatThreadId,"params.chatThreadId"),o=gw(r.pageSize,"params.pageSize"),i=fw(r.cursor,"params.cursor"),a=new URLSearchParams({limit:String(o),cursor:i}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:Iw(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:ww(d)};var d},Aw=async(e,t,r)=>{const s=yw(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw hw("params.chatThreadIds");if(r.chatThreadIds.length>20)throw pw("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>mw(e,`params.chatThreadIds[${t}]`)),o=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:Iw(o).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:Cw(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},Mw=pb(mb,{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"]}}}}}),Ew=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 lw(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=yw(t),n=mw(r.parentId,"params.parentId"),o=mw(r.name,"params.name"),i=mw(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=vw(bw(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw pw("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=yw(t),n=mw(r.parentId,"params.parentId"),o=gw(r.pageSize,"params.pageSize"),i=fw(r.cursor,"params.cursor"),a=new URLSearchParams({limit:String(o),cursor:i}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return Tw(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=yw(t),n=gw(r.pageSize,"params.pageSize"),o=fw(r.cursor,"params.cursor"),i=new URLSearchParams({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 Tw(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=yw(t),n=mw(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=yw(t),n=mw(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=yw(t),n=mw(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=yw(t),n=mw(r.chatThreadId,"params.chatThreadId"),o=mw(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 Rw(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=yw(t),n=mw(r.chatThreadId,"params.chatThreadId"),o=mw(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 Aw(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 qg(e.restBaseUrl,{errorMap:Mw,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}}};Ew.key="chatThreadManager";let Uw=Ew;class kw{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 Nw=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Ow=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},xw=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Lw=e=>({userId:e}),Pw=(e,t,r)=>{const s={userId:r};for(const n of Nw){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Dw=async(e,t)=>{const r=Ow(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,xw(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,Lw(i));return s},$w=e=>pl(e)?e:null,qw=e=>"string"==typeof e?e:void 0,Bw=e=>{const t=qw(e)?.trim();return t||void 0},Gw=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}},Fw=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},jw=e=>{const t=$w(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},zw=e=>{const t=$w(e);return t?$w(t.data)?t.data:t:null},Kw=(e,t)=>{const r=$w(e),s=r&&$w(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Gw(n[0])},Hw=e=>Bw(e.chatRoomId)??Bw(e.chatroomid)??Bw(e.id)??"",Vw=e=>qw(e.name)??qw(e.title)??qw(e.groupname)??"",Ww=e=>Lw(e),Jw=(e,t)=>{const r=$w(e);if(!r)return null;const s=Hw(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)})(Bw(r.owner)):Bw(r.owner);return{chatRoomId:s,name:Vw(r),owner:n?Ww(n):void 0,memberCount:Gw(r.memberCount)??Gw(r.affiliations_count),disabled:Fw(r.disabled)}},Zw=(e,t)=>{const r=(e=>{const t=$w(e);return t?Gw(t.count):void 0})(e),s=jw(e).map(e=>Jw(e,t)).filter(e=>null!==e),n=Kw(e,"pagenum"),o=Kw(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}},Qw=(e,t)=>{const r=jw(e),s=$w(r[0])??zw(e)??{},n=Jw(s)??{chatRoomId:Hw(s),name:Vw(s)},o=((e,t)=>{if(!t)return;if(Bw(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const s of r){const e=$w(s);if(e){if(Bw(e.owner)===t)return"owner";if(Bw(e.admin)===t)return"admin";if(Bw(e.member)===t)return"member"}}})(s,t),i=Gw(s.muteExpireAt)??Gw(s.mute_expire)??Gw(s.expire),a=Fw(s.inAllowlist)??Fw(s.white)??Fw(s.in_whitelist),c=Fw(s.muted);return{...n,description:qw(s.description),maxMembers:Gw(s.maxMembers)??Gw(s.maxusers)??Gw(s.max_users),createdAt:Gw(s.createdAt)??Gw(s.created),ext:qw(s.ext)??qw(s.custom),announcement:qw(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}},Yw=e=>jw(e).map(e=>Bw(e)).filter(e=>Boolean(e)).map(e=>Ww(e)),Xw=(e,t)=>{const r=zw(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=$w(r.errorKeys)??{},o={};for(const[i,a]of Object.entries(n))"string"==typeof a&&(o[i]={code:tC(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:o}},eC=e=>{const t=$w(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],o=[];return s.forEach(e=>{const t=$w(e),r=(e=>{const t=$w(e);if(!t)return null;const r=Bw(t.user),s=Bw(t.chatRoomId)??Bw(t.chatroomid)??Bw(t.id),n=qw(t.action),o=Fw(t.result);return r&&s&&void 0!==n&&void 0!==o?{chatRoomId:s,user:Ww(r),action:n,reason:qw(t.reason),...o?{}:{reason:qw(t.reason)??"failed"}}:null})(e);if(!r||!t)return;Fw(t.result)?n.push(r):o.push(r)}),{succeeded:n,failed:o}},tC=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?Gr:e.includes("is not part of you")?Ir:e.includes("is not Legal")||e.includes("is not exist")?nt:fr,rC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},sC=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),nC=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),oC=(e,t)=>`/${e.orgName}/${e.appName}${t}`,iC=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw nC(t,`${t} must be a string`);return e}},aC=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw nC(t,`${t} must be a number`);return e}},cC=(e,t)=>{const r=new URLSearchParams;"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}`:""},dC=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw sC(t);return e.trim()},uC=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw sC(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw nC(`${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 sC(t);return r},lC=(e,t)=>uC(e,t),hC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o={},i=iC(r.name,"params.name"),a=iC(r.description,"params.description"),c=aC(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 sC("params");const d=oC(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=zw(e)??{};return{nameUpdated:Fw(t.groupname),descriptionUpdated:Fw(t.description),maxMembersUpdated:Fw(t.maxusers)}})(await e.put(d,o,{operation:"updateChatRoomInfo"}))},pC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=new URLSearchParams;"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 jw(e)){const e=$w(n);if(!e)continue;const r=Bw(e.owner),s=Bw(e.admin),o=Bw(e.member),i=r??s??o;i&&t.push({user:Ww(i),role:r?"owner":s?"admin":"member",joinedAt:Gw(e.joinedAt)??Gw(e.joined_time)})}const r=$w(e),s=r?Bw(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(o,{operation:"getChatRoomMemberList"}))},mC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/admin`),i=await e.get(o,{operation:"getChatRoomAdminList"});return Yw(i)},fC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=new URLSearchParams;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=oC(s,`/chatrooms/${encodeURIComponent(n)}/mute?${o.toString()}`);return(e=>{const t=jw(e);if(t.every(e=>"string"==typeof e))return Yw(e).map(e=>({user:e}));const r=[];for(const s of t){const e=$w(s);if(!e)continue;const t=Bw(e.user)??Bw(e.member)??Bw(e.owner)??Bw(e.admin);t&&r.push({user:Ww(t),muteExpire:Gw(e.muteExpire)??Gw(e.expire)??Gw(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(i,{operation:"getChatRoomMuteList"}))},gC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=zw(e)??{};return{muted:Fw(t.muted)??Fw(t.value)??Boolean(t.data),muteExpireAt:Gw(t.muteExpireAt)??Gw(t.expire)??Gw(t.mute_expire)}})(await e.get(o,{operation:"isCurrentUserMutedInChatRoom"}))},yC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=cC(r),i=o?"&":"",a=oC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${i}${o.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return Yw(c).map(e=>({user:e}))},vC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),i=await e.get(o,{operation:"getChatRoomAllowlist"});return Yw(i).map(e=>({user:e}))},bC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=zw(e)??{};return Fw(t.value)??Fw(t.white)??!1})(await e.get(o,{operation:"checkIfInChatRoomAllowList"}))},IC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=zw(e)??{};return{announcement:qw(t.announcement)??""}})(await e.get(o,{operation:"getChatRoomAnnouncement"}))},wC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=zw(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(o,{keys:r.keys?lC(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},CC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw nC(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw sC(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw nC(t,`${t} contains invalid key`);if("string"!=typeof r)throw nC(`${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=oC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:o,autoDelete:i?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return Xw(u,n)},SC={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},TC=(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 TC(`${t} must be a string`,t,"invalid_format");return e},RC=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw TC(`${t} must be a string, number, or boolean`,t,"invalid_format")},AC=(e,t="attribute")=>{const r=SC[e];if(!r)throw TC(`${t} is invalid`,t,"invalid_format");return r},MC=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw TC(`${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 TC(`${t} is required`,t,"required");return r},EC=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw TC(`${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 SC))throw TC(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw TC(`${t} is required`,t,"required");return r},UC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/get`},kC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},NC=e=>({targets:MC(e)}),OC=e=>!!pl(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),xC=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!pl(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},LC=(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},PC=(e,t)=>{const r=(e=>{const t=new Map,r=pl(e)?e:null;if(r?.data&&pl(r.data))for(const[s,n]of Object.entries(r.data))OC(n)&&t.set(s,n);return xC(r?.entities,t),xC(r?.data&&pl(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=pl(e)?e:null;if(!r?.lastModified||!pl(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:LC(o,e),lastModified:s.get(o)})}return n},DC=(e,t)=>PC(e,t).map(e=>e.profile),$C=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,_C(r,s)]):e.push([t,String(RC(r,s))]))},qC=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),BC={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},GC=pb(mb,{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}}}}}),FC=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=BC[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=BC[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=rC(t),n=oC(s,`/chatrooms${cC(r)}`),o=await e.get(n,{operation:"getChatRoomList"});return Zw(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 kw(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true`),i=await e.get(o,{operation:"getChatRoomInfo"});return Qw(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 hC(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=dC(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=dC(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 pC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(s,`/chatrooms/${encodeURIComponent(n)}/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{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 mC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=dC(r.userId,"params.userId"),i=oC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=dC(r.userId,"params.userId"),i=oC(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 fC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=aC(r.duration,"params.duration"),a=oC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(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 gC(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await yC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=1===o.length,a=oC(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 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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(i,{usernames:o},{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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{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 bC(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return IC(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=iC(r.announcement,"params.announcement");if(void 0===o)throw sC("params.announcement");const i=oC(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 wC(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await CC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=lC(r.keys,"params.keys"),{isForced:i=!1}=r,a=i?"/forced":"",c=oC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:o},operation:"removeChatRoomAttributes"});return Xw(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 qg(e.restBaseUrl,{errorMap:GC,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 Dw(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=Ow(e),s=await Dw(r,t);return r.map(e=>Pw(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=NC(e),s=await this.getRestClient(t).request(UC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return DC(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 Pw(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>Pw(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:Pw(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:Pw(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:Pw(e.owner,t.get(e.owner.userId),e.owner.userId)}}};FC.key="chatRoomManager";let jC=FC;const zC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},KC=e=>pl(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):[],HC=(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&&pl(e),s},VC=async(e,t)=>{const r=zC(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return KC(n).map(e=>({userId:e}))},WC=async(e,t,r)=>{const s=zC(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:KC(o).map(e=>({userId:e})),failed:[]}},JC={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 ZC=!1,QC=null;const YC=()=>QC||(ZC||(kc.util.Long=ci,kc.configure(),ZC=!0),id(),QC=kc.Root.fromJSON(JC),od(QC),QC),XC=e=>"number"==typeof e?e:ci.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:XC(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:XC(t.protocolVersion)}};class tS{encodeRequest(e){const t=YC().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=Ab){const t=YC().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Sb,status:e})).finish()}decode(e){const t=YC(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case Cb:return{type:Cb};case Sb:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Sb,status:XC(r.status)}}case _b:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:_b,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:XC(t.createdAt),updatedAt:XC(t.updatedAt),metadataUpdatedAt:XC(t.metadataUpdatedAt)}})(e)):[],cursor:XC(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:XC(r.responseType)||Mb}}case Rb:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:Rb,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:wb}}}}class rS{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===Eb?"incremental":"full",version:this.version,pages:this.pages}}}const sS=e=>e.type===_b,nS=e=>"message"in e&&"code"in e;class oS{constructor(e){this.codec=new tS,this.sharedSession=e}async sync(e){const t=new rS(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:sS(t)||nS(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===Cb)return void(await r.send(this.codec.encodePong()));if(sS(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(nS(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 kb:return new Jr(e.message,{code:dt,details:r(!1)});case Nb:return new Hr(e.message,Gr,{details:r(!0)});case Ub:return new Hr(e.message,nt,{details:r(!1)});case Ob:return new Hr(e.message,ot,{details:r(!1)});case xb:return new Hr(e.message,fr,{details:r(!0)});case Lb: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 iS=e=>e.versionState.version?"incremental":"full",aS=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?iS(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}},cS=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{}}},dS=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},uS=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),lS=e=>{To("Contact sync duration",e)};class hS{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=aS({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void lS({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(dS(s)){const r=aS({metadataFailed:!0,state:e}),n=s instanceof Hr?s:new Hr("Contact metadata request failed",wr,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:uS("metadata",n.code,n.message,!1)}),void lS({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=aS({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:uS("metadata",wr,s instanceof Error?s.message:String(s),!0)}),void lS({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 oS(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=cS(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(),lS({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:uS(i,n.code,n.message,!0)}),lS({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 pS={items:[],loaded:!1,source:"server"},mS=pb(mb,{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:{}}}}),fS=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=pS,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=pS,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=zC(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=zC(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=zC(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=zC(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=zC(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 VC(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=HC(e,"params.userIds"),s=this.getRestClient(t);So("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await WC(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=HC(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=zC(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 qg(e.restBaseUrl,{errorMap:mS,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=pS)}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 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 To("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=NC(e),s=await this.getRestClient(t).request(UC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return DC(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 hS(e)}};fS.key="contactManager";let gS=fS;class yS{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)}},bS=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),IS=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),wS=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw bS(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw IS(`${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 bS(t);return r},CS=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw bS(t);return e.trim()},SS=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw IS(t,`${t} must be a string`);return e}},TS=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw IS(t,`${t} must be a boolean`);return e}},_S=(e,t)=>`/${e.orgName}/${e.appName}${t}`,RS=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),AS=e=>{const t=new URLSearchParams;"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}`:""},MS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Rl(e),r=wl(t[0]),s=Al(e)??r;return{groupId:s&&Ul(s)||r&&Ul(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?wS(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"}))},ES=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o=_S(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),i=await e.get(o,{operation:"getGroupInfo"});return Nl(i)},US=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o={},i=SS(r.name,"params.name"),a=SS(r.description,"params.description"),c=SS(r.avatar,"params.avatar"),d=SS(r.ext,"params.ext"),u=TS(r.public,"params.public"),l=TS(r.joinApprovalRequired,"params.joinApprovalRequired"),h=TS(r.allowInvites,"params.allowInvites"),p=TS(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw IS(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 bS("params");const f=_S(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,o,{operation:"updateGroupInfo"})},kS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/users${(e=>{const t=new URLSearchParams;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 Rl(e)){const e=wl(o);if(!e)continue;const r=Sl(e.owner),s=Sl(e.admin),n=Sl(e.member),i=r??s??n;if(!i)continue;const a=Tl(e.joinedAt)??Tl(e.joined_time);t.push({user:Ol(i),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=Ml(e,"pagenum"),s=Ml(e,"pagesize"),n=El(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},NS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/admin`),o=await e.get(n,{operation:"getGroupAdminList"});return xl(o)},OS=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o=AS(r),i=o?"&":"",a=_S(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${i}${o.replace("?","")}`);return(e=>{const t=[];for(const r of Rl(e)){const e=Sl(r);if(e){t.push({user:Ol(e)});continue}const s=wl(r);if(!s)continue;const n=Sl(s.user);if(!n)continue;const o=Tl(s.expire);t.push({user:Ol(n),...void 0===o?{}:{muteExpire:o}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},xS=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o=AS(r),i=o?"&":"",a=_S(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${i}${o.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return xl(c).map(e=>({user:e}))},LS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/white/users`),o=await e.get(n,{operation:"getGroupAllowlist"});return xl(o).map(e=>({user:e}))},PS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=Al(e)??{};return{announcement:Cl(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},DS=async(e,t,r)=>{const s=vS(t),n=new URLSearchParams;n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const o=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=Ml(e,"pagenum"),r=Ml(e,"pagesize"),s=El(e,r);return{items:Rl(e).map(e=>Ll(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(o,{operation:"getGroupSharedFileList"}))},$S=(e,t)=>{const r=vS(e);return _S(r,`/chatgroups/${encodeURIComponent(CS(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(CS(t.fileId,"params.fileId"))}`)},qS=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o=CS(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(!RS.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"})},BS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/sdk/metadata/chatgroup/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/get`);return(e=>{const t=Al(e)??{},r=wl(t.data)??t,s={};for(const[n,o]of Object.entries(r)){const e=wl(o);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:wS(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},GS=e=>{const t=pl(e)?e:{},r=t.data,s=pl(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return FS(n);const o=pl(r)?r:t,i=pl(o.namecards)?o.namecards:o,a={};for(const[c,d]of Object.entries(i)){if("string"==typeof d){a[c]={namecard:d};continue}if(!pl(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:jS(d)})}return a},FS=e=>{const t={};return e.forEach(e=>{if(!pl(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:jS(e)})}),t},jS=e=>wh("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),zS=e=>{if(pl(e))return wh("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 KS{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 HS=e=>({...e}),VS=e=>({...e,owner:e.owner?{...e.owner}:void 0});class WS{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=HS({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=VS({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=HS(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?HS(this.summarySnapshot):this.detailSnapshot?HS(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?VS(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 JS{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 ZS{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new JS,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 WS(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 QS=0,YS=5,XS=12,eT=13,tT=0,rT=1,sT=2,nT=0,oT=1,iT=2,aT=3,cT=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===tT?"owner":s===rT?"admin":s===sT?"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===nT?"DEFAULT":r===oT?"ALL":r===iT?"AT":r===aT?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},dT=e=>e.updatedAt??0,uT=(e,t)=>{if(!e)return!0;return dT(t)>=dT(e)},lT={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 hT=null,pT=!1;const mT=()=>hT||(pT||(kc.util.Long=ci,kc.configure(),pT=!0),id(),hT=kc.Root.fromJSON(lT),od(hT),hT),fT=e=>mT().lookupType(e),gT=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(ci.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}},yT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:gT(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:gT(t.protocol_version)??gT(t.protocolVersion)??0}};class vT{constructor(){this.requestType=fT("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=fT("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=fT("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:QS}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=gT(t.type);return r!==XS?null:{type:r,header:yT(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:gT(t.last_sync_time)??gT(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=gT(t.type);return r!==eT?null:{type:r,header:yT(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:gT(t.members_count)??gT(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:gT(t.role),mute_expiration:gT(t.mute_expiration)??gT(t.muteExpiration),remind_type:gT(t.remind_type)??gT(t.remindType),create_at:gT(t.create_at)??gT(t.createAt),update_at:gT(t.update_at)??gT(t.updateAt),joined_timestamp:gT(t.joined_timestamp)??gT(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:gT(t.last_sync_finished_ts)??gT(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=gT(t.type);return r!==YS?null:{type:r,header:yT(t.header),code:gT(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class bT{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 IT=e=>e.type===eT,wT=e=>e.type===YS;class CT{constructor(e){this.codec=new vT,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new bT(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:IT(t)||wT(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(IT(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(wT(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,Gr,{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 ST{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 CT(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),o=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=cT(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);uT(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=af;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:of,serverLimit:af,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:XS,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const TT=pb(mb,{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:"",errors:{}},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 ZS,this.groupEventSync=new KS(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 MS(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 yS(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 ES(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=wS(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(pl(i)&&Array.isArray(i.data)?i.data:[]).map(e=>Nl({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 US(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:wS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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 kS(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=wS(r.userIds,"params.userIds"),o=_S(s,`/chatgroups/${encodeURIComponent(CS(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 NS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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 OS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:wS(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=wS(r.userIds,"params.userIds"),o=_S(s,`/chatgroups/${encodeURIComponent(CS(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=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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 xS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:wS(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=wS(r.userIds,"params.userIds"),o=_S(s,`/chatgroups/${encodeURIComponent(CS(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 LS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:wS(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=wS(r.userIds,"params.userIds"),o=_S(s,`/chatgroups/${encodeURIComponent(CS(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=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),o=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof o?o:pl(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=vS(t),n=_S(s,`/sdk/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),o=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof o?o:pl(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 PS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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 DS(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=$S(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=Fn({file:e.file}),n=Np({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}`,[rl]:tl()},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===Br&&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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(CS(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}${$S(s,e)}`;t=Np({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}:{},[rl]:tl()},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 qS(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return BS(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=_S(s,`/sdk/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/nameCard/batch/get`),o=await e.post(n,{members:wS(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:GS(o),responseTimestamp:zS(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 qg(e.restBaseUrl,{errorMap:TT,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 ZS),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new KS(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 ES(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=wh("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!pl(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(pl(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];pl(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;pl(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 Il(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 bl(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>bl(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:bl(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 ES(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=NC(e),s=await this.getRestClient(t).request(UC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return DC(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(Xb(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await iI({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 oI({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 ST(e)}};_T.key="groupManager";let RT=_T;const AT=pb(mb,{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}}}}}),MT=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 qg(e.restBaseUrl,{errorMap:AT,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}})}};MT.key="presenceManager";let ET=MT;const UT=pb(mb,{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}}}}}),kT=["singleChat","groupChat"],NT=["ALL","AT","NONE","DEFAULT"],OT=["ALL","AT","NONE"],xT=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),LT=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=wg({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 qg(e.restBaseUrl,{errorMap:UT,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||!kT.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(!xT(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(!OT.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(!xT(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(!xT(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(xT(e.data)){const r=e.data[t];if(xT(r))return r}const r=e[t];return xT(r)?r:{}}resolveSilentModeRuleSource(e){if(!xT(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return xT(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":NT.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(xT(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}})}};LT.key="pushManager";let PT=LT;const DT=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},$T=(e,t="params.userIds")=>MC(e,t),qT=e=>{const t=$T(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",Gr);return{usernames:t}},BT=(e,t)=>{const r=(e=>$T(e))(t);return`${DT(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},GT=(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}},FT=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],jT=pb(mb,{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}}}}}),zT=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=GT(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=NC(MC(e.userIds,"params.userIds")),n=UC(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=MC(e.userIds,"params.userIds"),o=EC(e.attributes,"params.attributes"),{targets:MC(n),properties:EC(o).map(e=>AC(e,"params.attributes"))});var n,o;const i=UC(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=>DT(e))(t),n=qT(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=BT(t,e.userIds);So("UserInfoManager unsubscribeUsersInfo",{userIds:MC(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=>DT(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($C(t,"nickname",e.nickname,"params.nickname"),$C(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),$C(t,"mail",e.mail,"params.mail"),$C(t,"phone",e.phone,"params.phone"),$C(t,"gender",e.gender,"params.gender"),$C(t,"sign",e.sign,"params.sign"),$C(t,"birth",e.birth,"params.birth"),$C(t,"ext",e.ext,"params.ext"),0===t.length)throw TC("params must include at least one updatable field","params","required");return qC(t)})(e),n=kC(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=AC(e,"attribute"),s=RC(t,"value");if("gender"!==r&&"string"!=typeof s)throw TC("value must be a string","value","invalid_format");return qC([[r,String(s)]])})(e,t),o=kC(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 qg(e.restBaseUrl,{errorMap:jT,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 PC(e,t)}normalizeUpdateEnvelope(e,t,r){const s=pl(e)?e:null,n=(s&&pl(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!!pl(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 FT)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return FT.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=wh(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)}};zT.key="userInfoManager";let KT=zT;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=kf,e.ChatClient=$b,e.ChatManager=uw,e.ChatRoom=kw,e.ChatRoomManager=jC,e.ChatThread=lw,e.ChatThreadManager=Uw,e.ConnectionError=Wr,e.ContactManager=gS,e.Group=yS,e.GroupManager=RT,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.MessageReceiveError=Yr,e.MessageSendError=Qr,e.NetworkError=Vr,e.PresenceManager=ET,e.PushManager=PT,e.RUNTIME_PLATFORMS=Eo,e.RestBusinessError=ts,e.RestTransportError=es,e.SDKError=Hr,e.StorageError=Xr,e.StreamMessageStatus=rt,e.UploadError=rs,e.UserInfoManager=KT,e.ValidationError=Zr,e.createPlatformAdapter=$u,e.detectRuntimePlatform=(e,t)=>si(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",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",B="onMultiDeviceContact",G="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",Be="onMembersJoined",Ge="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,Bt=507,Gt=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,Br=1,Gr=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,Bs=0,Gs=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]:Gr,[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]:Gr,[In]:Gr,[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":Gr,"not in group or chatroom white list":Bt,nonroster:Yt,"group is disabled":br,"roaming is not open":$t,"Sorry, message does not exist":nt,"Sorry, edit limit reached":Gr,"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",Gr],["no permission to recall message",ut]],kn={[Tn]:Gr,[_n]:Gr,[Rn]:Gr,"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?Gt:e===nn?mt:void 0}})(e,t);return{code:r??(An[e]??Fr),retryable:!Mn.has(e)}},On={[Gr]:"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",[Bt]:"The user is not in the group or chat room allowlist",[Gt]:"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}},Bn=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=Gn({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}},Gn=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 Bn({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=Gn({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=Gn({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=Gn({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",Bo="PLATFORM_SOCKET_FAILED",Go="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=e=>{if(e)return e;const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,r={..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}};if(!t)return r;try{Object.assign(t,r)}catch{}return t},Wo={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},Jo=(e,t)=>{if("object"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Zo=e=>(e=>Jo(e,"canIUse")&&Jo(e,"getSystemInfo"))(e)||(e=>Jo(e,"request")&&Jo(e,"connectSocket"))(e),Qo=(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,Yo=e=>{const t=e?.miniGlobal;return Zo(t)?t:e},Xo=e=>void 0!==e.window&&void 0!==e.document,ei=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),ti=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;try{if(!Jo(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},ri=e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return Wo[r]??Eo.UNIAPP}catch{return Eo.UNIAPP}return Xo(e)?Eo.WEB:Eo.UNIAPP},si=(e,t)=>{const r=e??Vo();if(t){const e=t===Eo.UNIAPP||ti(r);return{platform:t,hostPlatform:e?ri(r):t,framework:e?"uniapp":Xo(r)?"web":"native",global:e&&r.uni?r.uni:Yo(Qo(r,t))??r}}return ti(r)?{platform:Eo.UNIAPP,hostPlatform:ri(r),framework:"uniapp",global:r.uni??r}:Zo(r.swan)?{platform:Eo.BAIDU_MINIAPP,hostPlatform:Eo.BAIDU_MINIAPP,framework:"native",global:Yo(r.swan)??r.swan}:Zo(r.tt)?{platform:Eo.TOUTIAO_MINIAPP,hostPlatform:Eo.TOUTIAO_MINIAPP,framework:"native",global:Yo(r.tt)??r.tt}:Zo(r.dd)?{platform:Eo.DINGTALK_MINIAPP,hostPlatform:Eo.DINGTALK_MINIAPP,framework:"native",global:Yo(r.dd)??r.dd}:Zo(r.my)?{platform:Eo.ALIPAY_MINIAPP,hostPlatform:Eo.ALIPAY_MINIAPP,framework:"native",global:Yo(r.my)??r.my}:Zo(r.wx)?{platform:Eo.WECHAT_MINIAPP,hostPlatform:Eo.WECHAT_MINIAPP,framework:"native",global:Yo(r.wx)??r.wx}:Zo(r.qq)?{platform:Eo.QQ_MINIAPP,hostPlatform:Eo.QQ_MINIAPP,framework:"native",global:Yo(r.qq)??r.qq}:Zo(r.jd)?{platform:Eo.JD_MINIAPP,hostPlatform:Eo.JD_MINIAPP,framework:"native",global:Yo(r.jd)??r.jd}:Zo(r.ks)?{platform:Eo.KUAISHOU_MINIAPP,hostPlatform:Eo.KUAISHOU_MINIAPP,framework:"native",global:Yo(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:Xo(r)?Eo.ELECTRON_RENDERER:Eo.ELECTRON_MAIN,hostPlatform:Xo(r)?Eo.ELECTRON_RENDERER:Eo.ELECTRON_MAIN,framework:"electron",global:r}:ei(r)||Xo(r)?{platform:Eo.WEB,hostPlatform:Eo.WEB,framework:ei(r)?"worker":"web",global:r}:{platform:Eo.UNKNOWN,hostPlatform:Eo.UNKNOWN,framework:"native",global:r}},ni=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,oi=["request","upload","socket","proto"],ii=(e,t=oi)=>{const r=((e,t=oi)=>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 ai=null;try{ai=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 ci(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function di(e){return!0===(e&&e.__isLong__)}function ui(e){var t=Math.clz32(e&-e);return e?31-t:t}ci.prototype.__isLong__,Object.defineProperty(ci.prototype,"__isLong__",{value:!0}),ci.isLong=di;var li={},hi={};function pi(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=hi[e])?s:(r=fi(e,0,!0),n&&(hi[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=li[e])?s:(r=fi(e,e<0?-1:0,!1),n&&(li[e]=r),r)}function mi(e,t){if(isNaN(e))return t?Ti:Si;if(t){if(e<0)return Ti;if(e>=Ii)return Ei}else{if(e<=-wi)return Ui;if(e+1>=wi)return Mi}return e<0?mi(-e,t).neg():fi(e%bi|0,e/bi|0,t)}function fi(e,t,r){return new ci(e,t,r)}ci.fromInt=pi,ci.fromNumber=mi,ci.fromBits=fi;var gi=Math.pow;function yi(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?Ti:Si;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 yi(e.substring(1),t,r).neg();for(var n=mi(gi(r,8)),o=Si,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=mi(gi(r,a));o=o.mul(d).add(mi(c))}else o=(o=o.mul(n)).add(mi(c))}return o.unsigned=t,o}function vi(e,t){return"number"==typeof e?mi(e,t):"string"==typeof e?yi(e,t):fi(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}ci.fromString=yi,ci.fromValue=vi;var bi=4294967296,Ii=bi*bi,wi=Ii/2,Ci=pi(1<<24),Si=pi(0);ci.ZERO=Si;var Ti=pi(0,!0);ci.UZERO=Ti;var _i=pi(1);ci.ONE=_i;var Ri=pi(1,!0);ci.UONE=Ri;var Ai=pi(-1);ci.NEG_ONE=Ai;var Mi=fi(-1,2147483647,!1);ci.MAX_VALUE=Mi;var Ei=fi(-1,-1,!0);ci.MAX_UNSIGNED_VALUE=Ei;var Ui=fi(0,-2147483648,!1);ci.MIN_VALUE=Ui;var ki=ci.prototype;ki.toInt=function(){return this.unsigned?this.low>>>0:this.low},ki.toNumber=function(){return this.unsigned?(this.high>>>0)*bi+(this.low>>>0):this.high*bi+(this.low>>>0)},ki.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Ui)){var t=mi(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=mi(gi(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}},ki.getHighBits=function(){return this.high},ki.getHighBitsUnsigned=function(){return this.high>>>0},ki.getLowBits=function(){return this.low},ki.getLowBitsUnsigned=function(){return this.low>>>0},ki.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ui)?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},ki.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},ki.isZero=function(){return 0===this.high&&0===this.low},ki.eqz=ki.isZero,ki.isNegative=function(){return!this.unsigned&&this.high<0},ki.isPositive=function(){return this.unsigned||this.high>=0},ki.isOdd=function(){return!(1&~this.low)},ki.isEven=function(){return!(1&this.low)},ki.equals=function(e){return di(e)||(e=vi(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},ki.eq=ki.equals,ki.notEquals=function(e){return!this.eq(e)},ki.neq=ki.notEquals,ki.ne=ki.notEquals,ki.lessThan=function(e){return this.comp(e)<0},ki.lt=ki.lessThan,ki.lessThanOrEqual=function(e){return this.comp(e)<=0},ki.lte=ki.lessThanOrEqual,ki.le=ki.lessThanOrEqual,ki.greaterThan=function(e){return this.comp(e)>0},ki.gt=ki.greaterThan,ki.greaterThanOrEqual=function(e){return this.comp(e)>=0},ki.gte=ki.greaterThanOrEqual,ki.ge=ki.greaterThanOrEqual,ki.compare=function(e){if(di(e)||(e=vi(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},ki.comp=ki.compare,ki.negate=function(){return!this.unsigned&&this.eq(Ui)?Ui:this.not().add(_i)},ki.neg=ki.negate,ki.add=function(e){di(e)||(e=vi(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,fi((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},ki.subtract=function(e){return di(e)||(e=vi(e)),this.add(e.neg())},ki.sub=ki.subtract,ki.multiply=function(e){if(this.isZero())return this;if(di(e)||(e=vi(e)),ai)return fi(ai.mul(this.low,this.high,e.low,e.high),ai.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Ti:Si;if(this.eq(Ui))return e.isOdd()?Ui:Si;if(e.eq(Ui))return this.isOdd()?Ui:Si;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(Ci)&&e.lt(Ci))return mi(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,fi((l&=65535)<<16|(h&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},ki.mul=ki.multiply,ki.divide=function(e){if(di(e)||(e=vi(e)),e.isZero())throw Error("division by zero");var t,r,s;if(ai)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?fi((this.unsigned?ai.div_u:ai.div_s)(this.low,this.high,e.low,e.high),ai.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Ti:Si;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Ti;if(e.gt(this.shru(1)))return Ri;s=Ti}else{if(this.eq(Ui))return e.eq(_i)||e.eq(Ai)?Ui:e.eq(Ui)?_i:(t=this.shr(1).div(e).shl(1)).eq(Si)?e.isNegative()?_i:Ai:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(Ui))return this.unsigned?Ti:Si;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=Si}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:gi(2,n-48),i=mi(t),a=i.mul(e);a.isNegative()||a.gt(r);)a=(i=mi(t-=o,this.unsigned)).mul(e);i.isZero()&&(i=_i),s=s.add(i),r=r.sub(a)}return s},ki.div=ki.divide,ki.modulo=function(e){return di(e)||(e=vi(e)),ai?fi((this.unsigned?ai.rem_u:ai.rem_s)(this.low,this.high,e.low,e.high),ai.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},ki.mod=ki.modulo,ki.rem=ki.modulo,ki.not=function(){return fi(~this.low,~this.high,this.unsigned)},ki.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},ki.clz=ki.countLeadingZeros,ki.countTrailingZeros=function(){return this.low?ui(this.low):ui(this.high)+32},ki.ctz=ki.countTrailingZeros,ki.and=function(e){return di(e)||(e=vi(e)),fi(this.low&e.low,this.high&e.high,this.unsigned)},ki.or=function(e){return di(e)||(e=vi(e)),fi(this.low|e.low,this.high|e.high,this.unsigned)},ki.xor=function(e){return di(e)||(e=vi(e)),fi(this.low^e.low,this.high^e.high,this.unsigned)},ki.shiftLeft=function(e){return di(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fi(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):fi(0,this.low<<e-32,this.unsigned)},ki.shl=ki.shiftLeft,ki.shiftRight=function(e){return di(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fi(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):fi(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},ki.shr=ki.shiftRight,ki.shiftRightUnsigned=function(e){return di(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fi(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):fi(32===e?this.high:this.high>>>e-32,0,this.unsigned)},ki.shru=ki.shiftRightUnsigned,ki.shr_u=ki.shiftRightUnsigned,ki.rotateLeft=function(e){var t;return di(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?fi(this.high,this.low,this.unsigned):e<32?(t=32-e,fi(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),fi(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},ki.rotl=ki.rotateLeft,ki.rotateRight=function(e){var t;return di(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?fi(this.high,this.low,this.unsigned):e<32?(t=32-e,fi(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),fi(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},ki.rotr=ki.rotateRight,ki.toSigned=function(){return this.unsigned?fi(this.low,this.high,!1):this},ki.toUnsigned=function(){return this.unsigned?this:fi(this.low,this.high,!0)},ki.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},ki.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]},ki.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]},ci.fromBytes=function(e,t,r){return r?ci.fromBytesLE(e,t):ci.fromBytesBE(e,t)},ci.fromBytesLE=function(e,t){return new ci(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},ci.fromBytesBE=function(e,t){return new ci(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&&(ci.fromBigInt=function(e,t){return fi(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},ci.fromValue=function(e,t){return"bigint"==typeof e?ci.fromBigInt(e,t):vi(e,t)},ki.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var Ni,Oi,xi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Li={exports:{}},Pi={},Di={};function $i(){if(Oi)return Ni;return Oi=1,Ni=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))}})},Ni}var qi,Bi,Gi,Fi,ji,zi,Ki,Hi={};function Vi(){return Ki?zi:(Ki=1,zi=function(){return null})}var Wi,Ji,Zi,Qi,Yi,Xi,ea,ta,ra,sa,na,oa,ia,aa,ca={};function da(){return Xi||(Xi=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=$i(),r.base64=(qi||(qi=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)}}(Hi)),Hi),r.EventEmitter=function(){if(Gi)return Bi;function e(){this._listeners={}}return Gi=1,Bi=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},Bi}(),r.float=function(){if(ji)return Fi;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,Fi=e(e)}(),r.inquire=Vi(),r.utf8=(Wi||(Wi=1,(t=ca).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}),ca),r.pool=Zi?Ji:(Zi=1,Ji=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(Yi)return Qi;Yi=1,Qi=t;var e=da();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},Qi}(),r.isNode=Boolean(void 0!==xi&&xi&&xi.process&&xi.process.versions&&xi.process.versions.node),r.global=r.isNode&&xi||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||Di,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}}(Di)),Di}function ua(){if(ta)return ea;ta=1,ea=c;var e,t=da(),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()},ea}function la(){if(oa)return na;oa=1,na=o;var e,t=da(),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)}})},na}var ha,pa,ma,fa,ga,ya,va={};function ba(){return ma||(ma=1,va.Service=function(){if(pa)return ha;pa=1,ha=t;var e=da();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},ha}()),va}function Ia(){return ga?fa:(ga=1,fa={})}function wa(){return ya||(ya=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=ua(),t.BufferWriter=function(){if(sa)return ra;sa=1,ra=r;var e=ua();(r.prototype=Object.create(e.prototype)).constructor=r;var t=da();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(),ra}(),t.Reader=la(),t.BufferReader=function(){if(aa)return ia;aa=1,ia=r;var e=la();(r.prototype=Object.create(e.prototype)).constructor=r;var t=da();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(),ia}(),t.util=da(),t.rpc=ba(),t.roots=Ia(),t.configure=r,r()}(Pi)),Pi}var Ca,Sa,Ta,_a,Ra={},Aa={exports:{}};var Ma,Ea,Ua,ka,Na,Oa,xa,La,Pa,Da,$a,qa,Ba,Ga,Fa,ja={};function za(){if(Ua)return Ea;Ua=1,Ea=c;var e=Mc();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=Rc(),o=Tc(),i=Ac();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},Ea}function Ka(){if(Na)return ka;Na=1,ka=s;var e=Rc();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=_c(),r=Tc();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))}},ka}function Ha(){if(xa)return Oa;xa=1,Oa=r;var e=Mc();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=Tc();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))},Oa}function Va(){if(Pa)return La;Pa=1,La=n;var e=za();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=Ha(),r=Tc(),s=ba();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},La}function Wa(){if($a)return Da;$a=1,Da=t;var e=da();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)},Da}function Ja(){if(Ba)return qa;Ba=1,qa=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=Ec(),t=_c(),r=Tc();function s(e){return"missing required '"+e.name+"'"}return qa}function Za(){if(Fa)return Ga;Fa=1,Ga=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=Ec(),t=Tc();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 Ga}var Qa,Ya={};function Xa(){return Qa||(Qa=1,function(e){var t=e,r=Ec(),s=Tc();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")}}(Ya)),Ya}var ec,tc,rc,sc,nc,oc,ic,ac,cc,dc,uc,lc,hc,pc,mc,fc,gc,yc,vc,bc,Ic={};function wc(){return ec||(ec=1,e=Ic,t=Wa(),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)}}),Ic;var e,t}function Cc(){if(rc)return tc;rc=1,tc=f;var e=za();((f.prototype=Object.create(e.prototype)).constructor=f).className="Type";var t=Ec(),r=Ac(),s=Rc(),n=Ka(),o=Va(),i=Wa(),a=la(),c=ua(),d=Tc(),u=Uc(),l=Ja(),h=Za(),p=Xa(),m=wc();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)}},tc}function Sc(){if(nc)return sc;nc=1,sc=c;var e=za();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=Rc(),o=Ec(),i=Ac(),a=Tc();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},sc}function Tc(){if(oc)return Aa.exports;oc=1;var e,t,r,s,n,o=Aa.exports=da(),i=Ia();o.codegen=function(){if(Sa)return Ca;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 Sa=1,Ca=e,e.verbose=!1,Ca}(),o.fetch=function(){if(_a)return Ta;_a=1,Ta=r;var e=$i(),t=Vi()("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()},Ta}(),o.path=(Ma||(Ma=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=Cc());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=Ec());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(Sc()))}}),Aa.exports}function _c(){return ic||(ic=1,function(e){var t=e,r=Tc(),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])}(Ra)),Ra}function Rc(){if(cc)return ac;cc=1,ac=i;var e=Mc();((i.prototype=Object.create(e.prototype)).constructor=i).className="Field";var t,r=Ec(),s=_c(),n=Tc(),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},ac}function Ac(){if(uc)return dc;uc=1,dc=s;var e=Mc();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=Rc(),r=Tc();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)})}},dc}function Mc(){if(hc)return lc;hc=1,lc=i,i.className="ReflectionObject";const e=Ac();var t,r=Tc(),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},lc}function Ec(){if(mc)return pc;mc=1,pc=s;var e=Mc();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=za(),r=Tc();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)},pc}function Uc(){if(gc)return fc;gc=1,fc=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=Ec(),t=_c(),r=Tc();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 fc}var kc=bc?vc:(bc=1,vc=function(){if(yc)return Li.exports;yc=1;var e=Li.exports=wa();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=Uc(),e.decoder=Ja(),e.verifier=Za(),e.converter=Xa(),e.ReflectionObject=Mc(),e.Namespace=za(),e.Root=Sc(),e.Enum=Ec(),e.Type=Cc(),e.Field=Rc(),e.OneOf=Ac(),e.MapField=Ka(),e.Service=Va(),e.Method=Ha(),e.Message=Wa(),e.wrappers=wc(),e.types=_c(),e.util=Tc(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),Li.exports}());const Nc={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}}}}}}}}}},Oc=e=>{if(!e||0===e.trim().length)throw Fo("Proto type name is required.",{code:Go,stage:xo,retryable:!1,details:{typeName:e}})};class xc{constructor(){this.codecMap=new Map}register(e,t){Oc(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:Go,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 Oc(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Fo("Proto codec not found.",{code:Go,stage:xo,retryable:!1,details:{typeName:e}})}}const Lc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Pc=e=>{class t extends kc.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},Dc=e=>ci.isLong(e),$c=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,qc=e=>Object.prototype.hasOwnProperty.call(kc.types.packed,e),Bc=e=>{const t=e.resolve();return t.resolvedType instanceof kc.Enum||qc(t.type)},Gc=(e,t)=>t in e?e[t]:void 0,Fc=e=>{const t=e.resolve();return t.resolvedType instanceof kc.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(kc.types.basic,r)?kc.types.basic[t.type]:2);var r},jc=(e,t)=>Dc(e)||"number"==typeof e||"string"==typeof e?e:Lc(e)&&"number"==typeof e.low&&"number"==typeof e.high?new ci(e.low,e.high,t):t?ci.UZERO:ci.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:$c(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}`)}},Kc=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},Hc=(e,t)=>{const r=e.uint32();return Kc(e,r,t),r},Vc=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return Kc(e,8,r),void e.skip(8);case 2:{const t=Hc(e,r);return void e.skip(t)}case 5:return Kc(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},Wc=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof kc.Type){const t=e.fork();return Zc(n,Lc(r)?r:{},t),t.ldelim(),e}return n instanceof kc.Enum?(e.int32("number"==typeof r?r:Number(r)),e):zc(e,s.type,r)},Jc=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(qc(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)Wc(e,t,s);return e.ldelim(),e}const n=Fc(t);for(const o of r)e.uint32(t.id<<3|n),Wc(e,t,o);return e},Zc=(e,t,r=kc.Writer.create())=>{const s=e.fieldsArray.slice().sort(kc.util.compareFieldsById);for(const n of s){const e=Gc(t,n.name);null!=e&&(n.repeated?Jc(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|Fc(n)),Wc(r,n,e)))}return r},Qc=(e,t,r,s)=>{const n=t.resolve(),o=n.resolvedType;return o instanceof kc.Type?2!==r?void Vc(e,r,s):Yc(o,e,Hc(e,s)):o instanceof kc.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)},Yc=(e,t,r)=>{const s=t instanceof kc.Reader?t:kc.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){Vc(s,d,n);continue}if(c.repeated){const e=Array.isArray(o[c.name])?o[c.name]:[];if(Bc(c)&&2===d){const t=Hc(s,n)+s.pos;for(;s.pos<t;)e.push(Qc(s,c,0,t))}else{const t=Qc(s,c,d,n);void 0!==t&&e.push(t)}o[c.name]=e;continue}const e=Qc(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},Xc=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,ed=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof kc.Type)return null;if(r.resolvedType instanceof kc.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&&Dc(r.typeDefault)?Xc(r.typeDefault,t):r.typeDefault},td=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof kc.Type?Lc(t)?rd(s.resolvedType,t,r):t:s.resolvedType instanceof kc.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&Dc(t)?Xc(t,r):"bytes"===s.type&&$c(t)?((e,t)=>t?.bytes===String?kc.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},rd=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(kc.util.compareFieldsById)){const e=Gc(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>td(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=ed(n,r)):s[n.name]=td(n,e,r)}return s},sd=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>Zc(e,Lc(t)?t:{},r),e.decode=(t,r)=>Yc(e,t,r),e.fromObject=e=>Lc(e)?e:{},e.toObject=(t,r)=>rd(e,Lc(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},nd=e=>{sd(e);for(const t of e.nestedArray)if(t instanceof kc.Type)nd(t);else if(t instanceof kc.Namespace)for(const e of t.nestedArray)e instanceof kc.Type&&nd(e)},od=e=>{for(const t of e.nestedArray)t instanceof kc.Type?nd(t):t instanceof kc.Namespace&&od(t)},id=()=>{const e=kc.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>Pc(e),kc.Type.prototype.setup=function(){return sd(this),this},kc.Type.prototype.create=function(e){return e?{...e}:{}},kc.Type.prototype.encode=function(e,t){return Zc(this,Lc(e)?e:{},t)},kc.Type.prototype.decode=function(e,t){return Yc(this,e,t)},kc.Type.prototype.fromObject=function(e){return Lc(e)?e:{}},kc.Type.prototype.toObject=function(e,t){return rd(this,Lc(e)?e:{},t)},kc.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let ad=!1,cd=null,ud=null,ld=null;const hd=e=>e.startsWith(".")?e.slice(1):e,pd=e=>e instanceof kc.Namespace,md=e=>e instanceof kc.Type,fd=e=>{for(const t of e.nestedArray)md(t)?nd(t):pd(t)&&fd(t)},gd=()=>{ad||(kc.util.Long=ci,kc.configure(),ad=!0),id();const e=kc.Root.fromJSON(Nc);return fd(e),e},yd=(e,t)=>{const r=e.nestedArray;for(const s of r){if(md(s)){const e=hd(s.fullName);nd(s),t.registerType(e,s);continue}pd(s)&&yd(s,t)}},vd=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return Fo(`Static proto ${r} failed.`,{code:Go,stage:xo,retryable:!1,details:{typeName:e,operation:r,cause:s}})},bd=()=>cd||(cd=gd(),cd),Id=()=>{if(ld)return ld;const e=(()=>{if(ud)return ud;const e=new xc,t=bd();return yd(t,e),ud=e,e})();return ld={encode(t,r){try{return e.getOrThrow(hd(t)).encode(r)}catch(s){throw vd(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(hd(t)).decode(r)}catch(s){throw vd(t,s,"decode")}}},ld},wd=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},Cd=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:wd(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)}}}},Sd=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Td=e=>"function"==typeof e.on&&"function"==typeof e.off,_d=(e,t,r)=>{if(Sd(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(Td(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw Fo("Socket event listener API is unsupported.",{code:Bo,stage:Oo,retryable:!1,details:{event:t}})},Rd=(e,t,r)=>{if(Sd(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(Td(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=_d(e,t,(...e)=>{n(),r(...e)}),n}throw Fo("Socket one-time listener API is unsupported.",{code:Bo,stage:Oo,retryable:!1,details:{event:t}})},Ad=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?Ad(e.data):null;var t},Md=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return _d(e,"open",()=>{t.forEach(e=>{e()})}),_d(e,"message",(...e)=>{const t=Ad(e[0]);null!==t&&r.forEach(e=>{e(t)})}),_d(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),_d(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:Bo,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)})}},Ed=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:Bo,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:Bo,stage:Oo,retryable:!0,details:{url:e.url,reason:"timeout"}})))};i=Rd(n,"open",()=>{c||(c=!0,i(),a(),d(),r(Md(n)))}),a=Rd(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:Bo,stage:Oo,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(o=setTimeout(u,e.timeoutMs))})}},Ud=(e,t)=>{throw Fo("Upload adapter execution failed.",{code:qo,stage:No,retryable:"abort"!==e,details:{reason:e,url:t.url}})},kd=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},Nd=(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{Ud("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),o.addEventListener("timeout",()=>{try{Ud("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),o.addEventListener("error",()=>{try{Ud("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=kd(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)}}))}}),Od=(e,t)=>e?"timeout":"abort",xd=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 Nd(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=kd(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?Od(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}})}}},Ld=(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},Pd=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=Ld(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)}}}},Dd=(e,t)=>e+t&4294967295,$d=(e,t,r,s,n,o)=>{return Dd((i=Dd(Dd(t,e),Dd(s,o)))<<(a=n)|i>>>32-a,r);var i,a},qd=(e,t,r,s,n,o,i)=>$d(t&r|~t&s,e,t,n,o,i),Bd=(e,t,r,s,n,o,i)=>$d(t&s|r&~s,e,t,n,o,i),Gd=(e,t,r,s,n,o,i)=>$d(t^r^s,e,t,n,o,i),Fd=(e,t,r,s,n,o,i)=>$d(r^(t|~s),e,t,n,o,i),zd=(e,t)=>{let[r,s,n,o]=e;r=qd(r,s,n,o,t[0]??0,7,-680876936),o=qd(o,r,s,n,t[1]??0,12,-389564586),n=qd(n,o,r,s,t[2]??0,17,606105819),s=qd(s,n,o,r,t[3]??0,22,-1044525330),r=qd(r,s,n,o,t[4]??0,7,-176418897),o=qd(o,r,s,n,t[5]??0,12,1200080426),n=qd(n,o,r,s,t[6]??0,17,-1473231341),s=qd(s,n,o,r,t[7]??0,22,-45705983),r=qd(r,s,n,o,t[8]??0,7,1770035416),o=qd(o,r,s,n,t[9]??0,12,-1958414417),n=qd(n,o,r,s,t[10]??0,17,-42063),s=qd(s,n,o,r,t[11]??0,22,-1990404162),r=qd(r,s,n,o,t[12]??0,7,1804603682),o=qd(o,r,s,n,t[13]??0,12,-40341101),n=qd(n,o,r,s,t[14]??0,17,-1502002290),s=qd(s,n,o,r,t[15]??0,22,1236535329),r=Bd(r,s,n,o,t[1]??0,5,-165796510),o=Bd(o,r,s,n,t[6]??0,9,-1069501632),n=Bd(n,o,r,s,t[11]??0,14,643717713),s=Bd(s,n,o,r,t[0]??0,20,-373897302),r=Bd(r,s,n,o,t[5]??0,5,-701558691),o=Bd(o,r,s,n,t[10]??0,9,38016083),n=Bd(n,o,r,s,t[15]??0,14,-660478335),s=Bd(s,n,o,r,t[4]??0,20,-405537848),r=Bd(r,s,n,o,t[9]??0,5,568446438),o=Bd(o,r,s,n,t[14]??0,9,-1019803690),n=Bd(n,o,r,s,t[3]??0,14,-187363961),s=Bd(s,n,o,r,t[8]??0,20,1163531501),r=Bd(r,s,n,o,t[13]??0,5,-1444681467),o=Bd(o,r,s,n,t[2]??0,9,-51403784),n=Bd(n,o,r,s,t[7]??0,14,1735328473),s=Bd(s,n,o,r,t[12]??0,20,-1926607734),r=Gd(r,s,n,o,t[5]??0,4,-378558),o=Gd(o,r,s,n,t[8]??0,11,-2022574463),n=Gd(n,o,r,s,t[11]??0,16,1839030562),s=Gd(s,n,o,r,t[14]??0,23,-35309556),r=Gd(r,s,n,o,t[1]??0,4,-1530992060),o=Gd(o,r,s,n,t[4]??0,11,1272893353),n=Gd(n,o,r,s,t[7]??0,16,-155497632),s=Gd(s,n,o,r,t[10]??0,23,-1094730640),r=Gd(r,s,n,o,t[13]??0,4,681279174),o=Gd(o,r,s,n,t[0]??0,11,-358537222),n=Gd(n,o,r,s,t[3]??0,16,-722521979),s=Gd(s,n,o,r,t[6]??0,23,76029189),r=Gd(r,s,n,o,t[9]??0,4,-640364487),o=Gd(o,r,s,n,t[12]??0,11,-421815835),n=Gd(n,o,r,s,t[15]??0,16,530742520),s=Gd(s,n,o,r,t[2]??0,23,-995338651),r=Fd(r,s,n,o,t[0]??0,6,-198630844),o=Fd(o,r,s,n,t[7]??0,10,1126891415),n=Fd(n,o,r,s,t[14]??0,15,-1416354905),s=Fd(s,n,o,r,t[5]??0,21,-57434055),r=Fd(r,s,n,o,t[12]??0,6,1700485571),o=Fd(o,r,s,n,t[3]??0,10,-1894986606),n=Fd(n,o,r,s,t[10]??0,15,-1051523),s=Fd(s,n,o,r,t[1]??0,21,-2054922799),r=Fd(r,s,n,o,t[8]??0,6,1873313359),o=Fd(o,r,s,n,t[15]??0,10,-30611744),n=Fd(n,o,r,s,t[6]??0,15,-1560198380),s=Fd(s,n,o,r,t[13]??0,21,1309151649),r=Fd(r,s,n,o,t[4]??0,6,-145523070),o=Fd(o,r,s,n,t[11]??0,10,-1120210379),n=Fd(n,o,r,s,t[2]??0,15,718787259),s=Fd(s,n,o,r,t[9]??0,21,-343485551),e[0]=Dd(r,e[0]),e[1]=Dd(s,e[1]),e[2]=Dd(n,e[2]),e[3]=Dd(o,e[3])},Kd=(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},Hd=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},Vd=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)zd(t,Kd(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(Hd).join("")},Wd=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})},Jd=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},Zd=()=>({async getImageInfo(e){const t=Jd(e),r=await Wd(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=Jd(e),s=await Wd(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=Jd(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 Vd(new Uint8Array(r))}}),Qd=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)},Yd=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},Xd=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"}})},eu=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},tu=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(Qd(e)))}})}).catch(e=>{throw Fo("Miniapp image info read failed",{code:qo,stage:Lo,retryable:!1,details:{src:t,cause:Qd(e)}})}),ru=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,su=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await tu(e,t);return ru(t,r)},nu=e=>({async getImageInfo(t){const r=Yd(t),s=await tu(e,r),n=eu(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=Yd(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 tu(e,s),o=ru(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(Qd(e)))}})}).catch(e=>{throw Fo("Miniapp image compress failed",{code:qo,stage:Lo,retryable:!1,details:{src:o,cause:Qd(e)}})}),c=await su(e,a),d=await tu(e,c),u=eu(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=Xd(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(Qd(e)))}})}).catch(e=>{throw Fo("Miniapp file info read failed",{code:qo,stage:Lo,retryable:!1,details:{filePath:t,cause:Qd(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=Yd(t),s=await su(e,r),n=await(async(e,t)=>{const r=Xd(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(Qd(e)))}})}).catch(e=>{throw Fo("Miniapp file read failed",{code:qo,stage:Lo,retryable:!1,details:{filePath:t,cause:Qd(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 Vd(n)}}),ou="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",iu=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),au=e=>e===Eo.ALIPAY_MINIAPP||e===Eo.DINGTALK_MINIAPP,cu=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=ou.indexOf(t[i]??""),r=ou.indexOf(t[i+1]??""),a=t[i+2]??"=",c=t[i+3]??"=",d="="===a?0:ou.indexOf(a),u="="===c?0:ou.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},du=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),uu=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},lu=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(du(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?lu(r.data,t+1):e},hu=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return uu(e);if(du(e))try{return uu(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return uu(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=hu(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=hu(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)}},pu=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(au(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+=ou[i>>18&63],t+=ou[i>>12&63],t+=void 0===n?"=":ou[i>>6&63],t+=void 0===o?"=":ou[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:iu(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},mu=(e,t)=>{const r=lu(e.data);if("string"==typeof r){if(!au(t))return r;const s=cu(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:iu(n.subarray(0,8)),decodedSuffixHex:iu(n.subarray(Math.max(0,n.length-8)))}),s}const s=hu(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(!au(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:iu(s.subarray(0,8))}),s.buffer;const o=cu(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:iu(i.subarray(0,8)),decodedSuffixHex:iu(i.subarray(Math.max(0,i.length-8)))}),o},fu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),gu=(e,t)=>fu(e)&&"function"==typeof e[t],yu=e=>e instanceof Error?e.message:fu(e)&&"string"==typeof e.errMsg?e.errMsg:fu(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),vu=e=>e?{...e}:{},bu=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},Iu=e=>{try{e.close()}catch{}},wu=(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:yu(r)}})))},a=e.downloadFile?.({url:t.url,header:vu(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=hu(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=bu(t.signal,()=>{a?.abort(),i("Mini program file download aborted.","abort",!1)})}),Cu=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:vu(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:yu(e)}}))}});n=bu(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"}}))})}):wu(e,t)}),Su=(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&&Iu(o),n(Fo(t,{code:Bo,stage:Oo,retryable:s,details:{url:r.url,cause:yu(e)}})))},u=e=>{if(!(gu(r=e,"send")&&gu(r,"close")&&gu(r,"onOpen")&&gu(r,"onMessage")&&gu(r,"onError")&&gu(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 Iu(n);o=n;const i=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?Iu(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=mu(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:Bo,stage:Oo,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:pu(r,t),success:s,fail:e=>{n(Fo("Mini program socket send failed.",{code:Bo,stage:Oo,retryable:!0,details:{cause:yu(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))})}),Tu=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:vu(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:yu(e)}}))}});i.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),o=bu(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"}}))})})}),_u=e=>({async getItem(t){if(gu(e,"getStorageSync"))try{const r=e.getStorageSync(t);return"string"==typeof r&&r.length>0?r:null}catch{return null}return gu(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,r){if(gu(e,"setStorageSync"))e.setStorageSync(t,r);else if(gu(e,"setStorage"))return new Promise((s,n)=>{e.setStorage({key:t,data:r,success:s,fail:e=>{n(e instanceof Error?e:new Error(yu(e)))}})})},async removeItem(t){if(gu(e,"removeStorageSync"))e.removeStorageSync(t);else if(gu(e,"removeStorage"))return new Promise((r,s)=>{e.removeStorage({key:t,success:r,fail:e=>{s(e instanceof Error?e:new Error(yu(e)))}})})}}),Ru=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>gu(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 gu(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),gu(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{gu(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return gu(e,"onAppShow")&&e.onAppShow(r),gu(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{gu(e,"offAppShow")&&e.offAppShow(r),gu(e,"offAppHide")&&e.offAppHide(s)}}}),Au=(e,t=Eo.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(gu(e,"request")&&gu(e,"connectSocket")&&gu(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?nu(s):void 0;return{request:Cu(s),socket:Su(s,r),upload:Tu(s),runtime:Ru(s,t),storage:_u(s),imageProcessor:n}},Mu=[Eo.WEB,Eo.ELECTRON_RENDERER,Eo.REACT_NATIVE],Eu=(e,t)=>{if("object"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Uu=e=>Mu.includes(e),ku=(e,t)=>(e!==Eo.UNIAPP||!Ou(t))&&(Uu(e)||e===Eo.UNIAPP&&Xo(t)),Nu=e=>Eu(e,"getImageInfo")&&Eu(e,"getFileSystemManager"),Ou=e=>"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),xu=(e,t)=>{if(Uu(e)&&e!==Eo.REACT_NATIVE)return Zd();if(ni(e)&&Nu(t))return nu(t);if(e===Eo.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Xo(e))return Zd();if(Nu(e.uni))return nu(e.uni);if(Nu(e.wx))return nu(e.wx)}},Lu=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())}},Pu=(e,t,r,s)=>{if(e===Eo.UNIAPP&&Ou(r)&&void 0!==r.uni&&Zo(r.uni))return{...Au(r.uni,e,t),proto:Id()};if(((e,t)=>!ku(e,t)&&ni(e))(e,r)&&Zo(s))return{...Au(s,e,t),proto:Id()};const n=r.XMLHttpRequest,o=ku(e,r),i=o?Cd({fetchImpl:r.fetch}):void 0,a=o?Ed({webSocketCtor:r.WebSocket}):void 0,c=e===Eo.REACT_NATIVE?Pd({fetchImpl:r.fetch,formDataCtor:r.FormData}):o?xd({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:Id(),storage:Lu(r),imageProcessor:o&&e!==Eo.REACT_NATIVE?Zd():xu(e,s)}},Du=(e,t)=>{if(void 0!==e)return e;throw Fo("Platform adapter initialization failed.",{code:Po,stage:Uo,retryable:!1,details:{capability:t}})},$u=e=>{const t=Vo(e?.runtimeInput),r=si(t,e?.prefer),s=r.platform,n=Pu(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);ii(a);return{platform:s,platformId:s,capability:a,request:Du(i.request,"request"),upload:Du(i.upload,"upload"),socket:Du(i.socket,"socket"),runtime:Du(i.runtime,"runtime"),proto:Du(i.proto,"proto"),storage:Du(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:Br,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}})},Bu={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Gu{constructor(e={}){this.attemptCount=0,this.config={...Bu,...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 Fu={interval:3e4,timeout:6e4},ju="function"==typeof TextDecoder?new TextDecoder:null;class zu{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(!zu.isRecord(r))return;"pong"===zu.readString(r.type)&&(this.markAlive(),So("Pong received"))},this.config={...Fu,...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)?ju?.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 Ku=null;function Hu(){return Ku||(Ku=bd()),Ku}const Vu="websdk2:device-info",Wu="webim",Ju="web",Zu=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,o=Vo().localStorage,i=()=>{if(!o)return null;try{const t=o.getItem(Vu);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(Vu,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===Wu){const e=`${Ju}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${Ju}_${r}`,deviceName:r,deviceUuid:`${Ju}_${t}`});return a(e),e}const n={deviceId:`webim_${Ju}_${r}`,deviceName:`webim_${Ju}_${r}`,deviceUuid:`webim_${Ju}_${r}`};return a(n),n}if(r===Wu){const e=`random_${Ju}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${Ju}_${r}`,deviceName:r,deviceUuid:`random_${Ju}_${t}`})}return{deviceId:`webim_${Ju}_${r}`,deviceName:`webim_${Ju}_${r}`,deviceUuid:`webim_${Ju}_${r}`}},Qu=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Yu=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 ci(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Xu=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},el=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},tl=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,rl="X-Request-Id",sl=new Set(["mute"]),nl={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},ol=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},il=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},al=(e,t)=>{const r=e?.map(e=>ol(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},cl=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=il(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},dl=e=>{const t=il(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=nl[s];if(!e)continue;let t=n;if(sl.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},ul=e=>{const t=il(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:ol(t.operator)??ol(t.username)}},ll=(e,t)=>({eventName:e,payload:t}),hl=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=ol(e.from?.name),s=(n=e.to,ol(n?.[0]?.name));var n;switch(e.operation){case 1:return ll(qe,t);case 10:return ll(Fe,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return ll(Be,{...t,memberIds:al(e.members,r),ext:e.ext??e.eventExt});case 18:return ll(Ge,{...t,memberIds:al(e.members,r)});case 20:return ll(Ze,{...t,oldOwnerId:r,newOwnerId:s});case 21:return ll(We,{...t,adminId:s??r});case 22:return ll(Je,{...t,adminId:s??r});case 23:{const r=(e=>{const t=il(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):al(e.members,s),o=46388736e5;return ll(je,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,o])),muteExpire:cl(e.reason,e.eventExt)??o})}case 24:return ll(ze,{...t,userIds:al(e.members,s)});case 25:return ll(Qe,{...t,announcement:e.reason??""});case 26:return ll(Qe,{...t,announcement:""});case 29:return ll(Ke,{...t,userIds:al(e.members,s)});case 30:return ll(He,{...t,userIds:al(e.members,s)});case 31:return ll(Ve,{...t,isMuted:!0});case 32:return ll(Ve,{...t,isMuted:!1});case 14:return ll(Ye,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:dl(e.eventExt)});case 43:{const s=ul(e.eventExt);return ll(Xe,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=ul(e.eventExt);return ll(et,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},pl=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ml=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},fl=e=>!!e&&("undefined"!=typeof DOMException&&e instanceof DOMException?"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name:e instanceof Error&&("QuotaExceededError"===e.name||e.message.includes("quota"))),gl=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],yl=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),vl=e=>({userId:e}),bl=(e,t,r)=>{const s={userId:r};for(const n of gl){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Il=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,yl(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,vl(i));return s},wl=e=>pl(e)?e:null,Cl=e=>{if("string"==typeof e)return e},Sl=e=>{const t=Cl(e)?.trim();return t||void 0},Tl=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}},_l=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Rl=e=>{const t=wl(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Al=e=>{const t=wl(e);return t?wl(t.data)?t.data:t:null},Ml=(e,t)=>{const r=wl(e),s=r&&wl(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Tl(n[0])},El=(e,t)=>{const r=(e=>{const t=wl(e);return t?Tl(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},Ul=e=>Sl(e.groupId)??Sl(e.groupid)??Sl(e.id)??"",kl=e=>Cl(e.name)??Cl(e.groupname)??Cl(e.groupName)??"",Nl=e=>{const t=Rl(e),r=wl(t[0])??Al(e)??{},s=(e=>{const t=wl(e);if(!t)return null;const r=Ul(t);return r?{groupId:r,name:kl(t),description:Cl(t.description),memberCount:Tl(t.memberCount)??Tl(t.affiliations_count),public:_l(t.public),joinApprovalRequired:_l(t.joinApprovalRequired)??_l(t.approval)??_l(t.membersonly)??_l(t.members_only),allowInvites:_l(t.allowInvites)??_l(t.allowinvites)??_l(t.allow_user_invites),maxMembers:Tl(t.maxMembers)??Tl(t.maxusers),role:Sl(t.role)??Sl(t.permission),disabled:_l(t.disabled)}:null})(r)??{groupId:Ul(r),name:kl(r)},n=Sl(r.owner)??Sl(r.admin)??Sl(r.member),o=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>wl(e)).filter(e=>null!==e).map(e=>Tl(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?vl(n):void 0,inviteNeedConfirm:_l(r.inviteNeedConfirm)??_l(r.invite_need_confirm),muteAllMembers:_l(r.mute),ext:Cl(r.ext)??Cl(r.custom),createdAt:Tl(r.createdAt)??Tl(r.created),joinedAt:o,avatarUrl:Cl(r.avatar),messageBlocked:_l(r.messageBlocked)??_l(r.isMessageBlocked)??_l(r.shieldgroup)}},Ol=e=>vl(e),xl=e=>Rl(e).map(e=>Sl(e)).filter(e=>Boolean(e)).map(e=>Ol(e)),Ll=e=>{const t=wl(e);if(!t)return null;const r=Sl(t.fileId)??Sl(t.file_id);if(!r)return null;const s=Cl(t.fileName)??Cl(t.file_name)??r,n=Sl(t.fileOwner)??Sl(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?Ol(n):void 0,fileSize:Tl(t.fileSize)??Tl(t.file_size),createdAt:Tl(t.createdAt)??Tl(t.created)}},Pl=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Dl={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},$l=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},ql=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=>$l(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Gl=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=ql(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},Fl=e=>{const t=ql(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Dl[s];if(!e)continue;let t=n;if(Pl.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},jl=(e,t)=>{const r=ql(t)??ql(e);return Ll(r??void 0)??void 0},zl=(e,t)=>{const r=ql(t)??ql(e);return $l(r?.fileId)??$l(r?.file_id)??$l(e)??""},Kl=(e,t)=>({eventName:e,payload:t}),Hl=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=$l(e.from?.name),s=(n=e.to,$l(n?.[0]?.name));var n;switch(e.operation){case 4:return Kl(Y,{...t,applicantId:r,reason:e.reason});case 5:return Kl(X,{...t,accepterId:r});case 6:return Kl(ee,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return Kl(Q,{...t,inviterId:r,reason:e.reason});case 8:return Kl(te,{...t,inviteeId:r,reason:e.reason});case 9:return Kl(re,{...t,inviteeId:r,reason:e.reason});case 10:return Kl(se,t);case 1:return Kl(ne,t);case 19:return Kl(oe,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=ql(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=$l(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):Bl(e.members,s);return Kl(ie,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??Gl(e.reason,e.eventExt)})}case 24:return Kl(ae,{...t,userIds:Bl(e.members,s)});case 29:return Kl(ce,{...t,userIds:Bl(e.members,s)});case 30:return Kl(de,{...t,userIds:Bl(e.members,s)});case 31:return Kl(ue,{...t,isMuted:!0});case 32:return Kl(ue,{...t,isMuted:!1});case 21:return Kl(le,{...t,administratorId:s??r});case 22:return Kl(he,{...t,administratorId:s??r});case 20:return Kl(pe,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=Bl(e.members,r);return Kl(me,{...t,memberIds:s})}case 18:{const s=Bl(e.members,r);return Kl(fe,{...t,memberIds:s})}case 25:return Kl(ge,{...t,announcement:e.reason??""});case 26:return Kl(ge,{...t,announcement:""});case 27:return Kl(ye,{...t,sharedFile:jl(e.reason,e.eventExt)});case 28:return Kl(ve,{...t,fileId:zl(e.reason,e.eventExt)});case 14:return Kl(be,{...t,shouldFetchGroupDetail:!0,groupPatch:Fl(e.eventExt)});case 41:return Kl(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Kl(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=ql(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:$l(t.username),attribute:s}})(e.eventExt);return Kl(we,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},Vl=new WeakMap,Wl=(e,t)=>{Vl.set(e,t)},Jl=e=>Vl.get(e)??null,Zl=(e,t)=>{const r=Jl(e);r&&Wl(t,r)},Ql=new WeakMap,Yl=e=>Ql.get(e),Xl=new WeakMap,eh=e=>Xl.get(e),th=(e,t)=>{const r=Xl.get(e);r&&Xl.set(t,r)},rh="singleChat",sh="groupChat",nh=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},oh=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}},ih=e=>{if(!Array.isArray(e))return;const t=e.map(e=>nh(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},ah=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ch=(...e)=>{for(const t of e){const e=nh(t);if(e)return e}},dh=(e,t)=>Boolean(e&&t&&e===t),uh=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),lh=(e,t,r)=>{const s=ih(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>nh(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const o=nh(r?.name);return o?[o]:[]},hh=e=>{const t=oh(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}}},ph=(e,t)=>{const r=ch(e.to?.[0]?.clientResource);if(1!==e.to?.length||nh(e.to[0]?.name)!==t.userId||!uh(t.userId,r,t))return null;const s=(n=e.from,nh(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}},mh=(e,t)=>{if(!e.groupId)return To("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=ch(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!uh(nh(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=lh(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:nh(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},fh=(e,t)=>{if(!e.threadId)return To("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=ch(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!uh(nh(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=lh(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:nh(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},gh=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=ch(e.res,e.raw?.resource,e.raw?.clientResource);if(dh(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?rh:sh;var n;const o=nh(e.id)??(s===rh?nh(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?hh(e.ext):void 0,operatorId:nh(e.from),deviceId:r,timestamp:oh(e.ts),raw:e.raw}},yh=(e,t)=>{const r=ch(e.resource,e.raw?.resource,e.raw?.clientResource);if(dh(r,t.clientResource))return So("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=nh(e.to);if(!s)return To("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=nh(e.lastMsgId),o=ih(e.msgIdList)??(n?[n]:void 0),i=oh(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?sh:rh,messageIds:o,beforeTimestamp:i,deviceId:r,raw:e.raw}},vh=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},bh=2147483647,Ih=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>bh?void 0:r},wh=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>bh?Math.floor(e/1e3):Math.floor(e);return Ih(t)};var Ch=4096,Sh=65547,Th=15,_h=2113929216,Rh=65536,Ah=65536,Mh=10485760,Eh={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Uh={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function kh(e){if(!(e>0))return Ah;if(e<=Ah)return Ah;if(e>1073741823)return e;for(var t=Ah;t<e;)t*=2;return t}var Nh={byU16:0,byU32:1},Oh=0,xh=1,Lh=2,Ph=0,Dh=1;function $h(e,t){return e[t]|e[t+1]<<8}function qh(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Bh(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var Gh="fast";function Fh(e){return 2654435761*(e>>>0)>>>20&4095}function jh(e){return 2654435761*(e>>>0)>>>19&8191}function zh(e,t,r){if("fast"===Gh){var s=qh(e,t);return r===Nh.byU16?jh(s):Fh(s)}throw new Error("Unsupported hash strategy: "+Gh)}function Kh(e,t,r,s,n){r[t]=e-n}function Hh(e,t,r,s,n){Kh(t,zh(e,t,s),r,0,n)}function Vh(e,t,r,s){return t[e]+s}function Wh(e,t,r,s,n){return Vh(zh(e,t,s),r,0,n)}function Jh(e,t,r,s){for(var n=t;t<s-3;){if(qh(e,t)!==qh(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 Zh(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>_h)return 0;switch(c){case Oh:default:u=s,l=s;break;case xh:u=s-e.currentOffset,l=s-e.dictSize;break;case Lh:u=s-e.currentOffset,l=s}if(a===Nh.byU16&&n>=Sh)return 0;if(n<13)return Xh(t,r,I,w,T,_,i);Hh(t,m,p,a,u),h=zh(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 Xh(t,r,I,w,T,_,i);A=Vh(N,p,0,u),c===Lh&&(A<s?(R=b,l=y):(R=0,l=s)),h=zh(t,E,a),Kh(m,N,p,0,u)}while(d===Dh&&A<f||a!==Nh.byU16&&A+65535<m||!Qh(t,g,m,A,R,c,s));for(;m>I&&A+R>l;){var O=A+R-1;if(t[m-1]!==(c===Lh&&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>=Th){var L=x-Th;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(Bh(r,T,m-A),T+=2,c===Lh&&A<s){var $=m+(v-(A+R));if($>S&&($=S),(m+=4+(D=Yh(t,g,m+4,A+R+4-y+e.dictionaryStart,$,v-y)))===$&&$<S){var q=Jh(t,m,s,S);D+=q,m+=q}}else m+=4+(D=Jh(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(Hh(t,m-2,p,a,u),A=Wh(t,m,p,a,u),c===Lh&&(A<s?(R=b,l=y):(R=0,l=s)),Hh(t,m,p,a,u),!((d!==Dh||A>=f)&&A+65535>=m&&Qh(t,g,m,A,R,c,s)))break t;r[M=T++]=0}h=zh(t,++m,a)}return Xh(t,r,I,w,T,_,i)}function Qh(e,t,r,s,n,o,i){var a,c=qh(e,r);o===Lh&&s+n<i?a=qh(t,s+n):a=qh(e,s+n);return c===a}function Yh(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 Xh(e,t,r,s,n,o,i){var a=s-r;if(i&&n+a+1+Math.floor((a+255-Th)/255)>o)return 0;if(a>=Th){for(t[n++]=240,a-=Th;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 ep(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 tp(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)===Th){var T=ep(e,A={ip:p},m-Th,!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=$h(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=ep(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===Lh&&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 rp(){return{hashTable:new Uint32Array(Ch),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function sp(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function np(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?Dh:Ph;return e.dictionary&&c===s?(u=Zh(e,t,r,s,n,i||0,a||!1,Nh.byU32,xh,h),e.dictSize+=n,e.currentOffset+=n,u):(u=Zh(e,t,r,s,n,i||0,a||!1,Nh.byU32,Lh,h),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function op(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 ip(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function ap(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function cp(e,t,r,s,n,o,i){var a;if(e.prefixEnd===o){if((a=tp(t,r,s,n,o,i,!0,0,0,Lh,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=tp(t,r,s,n,o,i,!0,0,0,Lh,o,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=o+a}return a}function dp(e){var t=(e=e||{}).minWorkArea||Ah,r=e.maxWorkArea||Mh,s=e.shrinkThreshold||t;t<Ah&&(t=Ah),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Rh+t,this.maxBufferSize=Rh+r,this.shrinkThreshold=Rh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Eh.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=rp()}function up(e){var t=(e=e||{}).minWorkArea||Ah,r=e.maxWorkArea||Mh,s=e.shrinkThreshold||t;t<Ah&&(t=Ah),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Rh+t,this.maxBufferSize=Rh+r,this.shrinkThreshold=Rh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Eh.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}dp.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Rh?this.offset:Rh,n=this.offset>Rh?this.offset-Rh:0;t.set(this.ringBuffer.subarray(n,n+s),0),op(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},dp.prototype.compress=function(e,t){var r=e.length;if(r<=0)return Uh.PARAM_ERROR;if(r>this.maxBufferSize-Rh)return Uh.PARAM_ERROR;if(r>this.ringBufferSize-Rh){var s=kh(r),n=Rh+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Uh.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(op(this.stream,this.ringBuffer,0,Rh),this.offset=Rh);var o=this.offset;this.ringBuffer.set(e,o);var i=np(this.stream,this.ringBuffer,t,o,r,0,t.length,!0);return i<=0?Uh.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),i)},dp.prototype.reset=function(){this.offset=0,sp(this.stream)},dp.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},dp.prototype._tryAutoShrink=function(){this.shrinkMode!==Eh.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Eh.AUTO_IMMEDIATE||this.shrinkMode===Eh.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},dp.prototype.getWorkArea=function(){return this.ringBufferSize-Rh},dp.prototype.getRingBufferSize=function(){return this.ringBufferSize},dp.prototype.getBaseBufferSize=function(){return this.minBufferSize},dp.prototype.getMaxBufferSize=function(){return this.maxBufferSize},dp.prototype.getCurrentOffset=function(){return this.offset},dp.prototype.getShrinkMode=function(){return this.shrinkMode},dp.prototype.setShrinkMode=function(e){this.shrinkMode=e},dp.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},dp.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Rh,r=this.maxBufferSize-Rh;if(e<t||e>r)return Uh.PARAM_ERROR;this.shrinkThreshold=Rh+e},up.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Rh?this.offset:Rh,n=this.offset>Rh?this.offset-Rh:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,ap(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},up.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return Uh.PARAM_ERROR;if(r>this.maxBufferSize-Rh)return Uh.PARAM_ERROR;if(r>this.ringBufferSize-Rh){var n=kh(r),o=Rh+n;if(o>this.maxBufferSize&&(o=this.maxBufferSize),!this._resizeBuffer(o))return Uh.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var i=this.offset-Rh;i>0&&this.ringBuffer.set(this.ringBuffer.subarray(i,i+Rh),0),ap(this.streamDecode,this.ringBuffer,0,Rh),this.offset=Rh}var a=cp(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?Uh.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},up.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},up.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},up.prototype._tryAutoShrink=function(){this.shrinkMode!==Eh.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Eh.AUTO_IMMEDIATE||this.shrinkMode===Eh.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},up.prototype.getWorkArea=function(){return this.ringBufferSize-Rh},up.prototype.getRingBufferSize=function(){return this.ringBufferSize},up.prototype.getBaseBufferSize=function(){return this.minBufferSize},up.prototype.getMaxBufferSize=function(){return this.maxBufferSize},up.prototype.getCurrentOffset=function(){return this.offset},up.prototype.getShrinkMode=function(){return this.shrinkMode},up.prototype.setShrinkMode=function(e){this.shrinkMode=e},up.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},up.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Rh,r=this.maxBufferSize-Rh;if(e<t||e>r)return Uh.PARAM_ERROR;this.shrinkThreshold=Rh+e};const lp={LZ4_MAX_INPUT_SIZE:_h,BLOCK_MAX_SIZE:65536,DICT_SIZE:Rh,DEFAULT_WORK_AREA:Ah,DEFAULT_MAX_WORK:Mh,SHRINK_MODE:Eh,LZ4_ERROR:Uh,alignToPowerOf2:kh,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".');Gh=e},getHashStrategy:function(){return Gh},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>_h)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var o=s<Sh?Nh.byU16:Nh.byU32;return Zh({hashTable:new Uint32Array(o===Nh.byU16?8192:Ch),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,o,Oh,Ph)},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>_h)return 0;if(o<1)return 0;if(0===s)return t[n]=0,1;var i=s<Sh?Nh.byU16:Nh.byU32;return Zh({hashTable:new Uint32Array(i===Nh.byU16?8192:Ch),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,o,!0,i,Oh,Ph)},compressBound:function(e){return e<0||e>_h?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:tp(e,t,r,s,n,o,!0,0,0,Oh,n,null,0))},decompressFast:function(e,t,r,s,n){return tp(e,t,r=r||0,0,s=s||0,n,!1,0,0,xh,s-65536,0,65536)},createStream:rp,resetStream:sp,loadDict:function(e,t,r,s){if(e.initCheck&&sp(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;)Hh(t,o,e.hashTable,Nh.byU32,n),o+=3;return s},compressContinue:np,saveDict:op,createStreamDecode:ip,setStreamDecode:ap,decompressSafeContinue:cp,RingBufferEncoder:dp,RingBufferDecoder:up,_hashU16:jh,_hashU32:Fh,_TABLE_TYPE:Nh},hp=268435455,pp=new Uint32Array(256);let mp=!1;function fp(e){!function(){if(!mp){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;pp[e]=t>>>0}mp=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(pp[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var gp=(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))(gp||{});const yp=268435455;class vp{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:lp.DEFAULT_WORK_AREA,maxWorkArea:lp.DEFAULT_MAX_WORK,shrinkMode:lp.SHRINK_MODE.MANUAL};this.encoder=new lp.RingBufferEncoder(e),this.decoder=new lp.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>yp)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=lp.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>hp)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=fp(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>yp)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=fp(i);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return i}reset(){this.encoder.reset(),this.decoder.reset()}}const bp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ip=(e,t)=>Zc(e,t).finish();class wp{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Zu({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:[Bs],compressType:[Gs],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=Hu(),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:[Gs],encryptType:[Bs],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=Ip(t,s),o={version:0,guid:Qu({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:[Bs],payload:n,traceId:tl()};return Ip(r,o)}encodeHeartbeat(){const e=Hu(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Ip(t,{}),n={version:0,encryptType:[Bs],command:ns,payload:s,traceId:tl()};return Ip(r,n)}encodeStatisticRebuild(){const e=Hu(),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=Ip(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=Ip(s,a);return Ip(n,{version:0,encryptType:[Bs],command:ss,payload:c,traceId:tl()})}decodeProvision(e){const t=Hu().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=Hu().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=Hu().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=Hu().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=Hu(),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=Yu(n.metaId),c=Yu(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(Yu(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=>Yu(e)).filter(e=>Boolean(e)),t=Yu(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=el(Array.isArray(s.ext)?s.ext.filter(bp):void 0),n=bp(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=Yu(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=Yu(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const h=Yu(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:el(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=Hu(),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(!bp(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(!bp(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=Hu(),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=Hu(),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=ph({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=Hu(),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=fh({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=mh({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?hl({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}):Hl({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&&Ql.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:bp(s.data)?s.data:s}}]}if("conv"===n){const e=bp(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=gh({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=bp(s.data)?s.data:s,t=yh({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(!ah(s))continue;const e=ch(s.operator_resource,s.resource,s.clientResource);if(dh(e,t.clientResource))continue;const n=nh(s.group)??nh(s.user);if(!n||!ah(s.data))continue;const o=nh(s.group)?sh:rh,i=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:o,remindType:nh(i.type),silentMode:i,deviceId:e,raw:s})}return r})(bp(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(Yu(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:vh(e.category),data:e}}decodeNotice(e){const t=Hu().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Hu().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=Hu(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=Ip(r,{queue:e}),o={version:0,encryptType:[Bs],command:ss,payload:n,traceId:tl()};return Ip(s,o)}encodeLastSession(e,t){const r=Hu(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),o=Ip(s,{queue:e,key:t}),i={version:0,encryptType:[Bs],command:ss,payload:o,traceId:tl()};return Ip(n,i)}encodeChatMessage(e,t){const r=Hu(),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:Xu(e.ext??{}),...c?{meta:c}:{},...a,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=Ip(s,u),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e),f={id:t,to:Qu({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=Ip(n,{meta:f}),y={version:0,encryptType:[Bs],command:ss,payload:g,traceId:tl()};return Ip(o,y)}encodeActionMessage(e,t){const r=Hu(),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:Xu(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=Ip(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:Qu({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=Ip(n,{meta:l}),p={version:0,encryptType:[Bs],command:ss,payload:h,traceId:tl()};return Ip(o,p)}encodeChatRoomOperation(e,t){const r=Hu(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),o=r.lookupType("easemob.pb.MSync"),i={mucId:Qu({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=Ip(s,i),c={id:t,from:Qu({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=Ip(n,{meta:c}),u={version:0,encryptType:[Bs],command:ss,payload:d,traceId:tl()};return Ip(o,u)}decodeServerMessageMeta(e){const t=Hu(),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=ci.fromString("1099511628211",!0);let r=ci.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(ci.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()})(e)}decodeChatRoomJoinInfo(e){const t=Hu().lookupType("easemob.pb.MUCBody");for(const s of e){if(!bp(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(!bp(e)||!bp(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!bp(s))continue;const o=s[this.context.userId];if(!bp(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=Yu(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:Yu(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=el(t.ext),h=el(e.ext),p=Number(Yu(e.timestamp))||Date.now(),m=Yu(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)};Wl(_,{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=Jl(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 Ih(Yu(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(Yu(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:Xu(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:eh(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=el(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?Xu({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(!bp(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(!bp(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(!bp(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(!bp(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=bp(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:bp(n?.ext)?n.ext:{},timestamp:s,body:l,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(bp(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:bp(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 bp(e)?e:null}catch{return null}}if(bp(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return bp(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(bp).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 vp);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===gp.UPLINK_ONLY||r===gp.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===gp.DOWNLINK_ONLY||r===gp.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?gp.UPLINK_ONLY:1===e?gp.DOWNLINK_ONLY:2===e?gp.BIDIRECTIONAL:gp.NONE}disableCompression(){this.compressor&&(this.compressor.mode=gp.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Cp=1e3,Sp="direct";class Tp{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 _p{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 Rp={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},Ap=()=>{const e=globalThis.crypto?.randomUUID?.();return e??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class Mp{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??Ap;const t=new _p({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 Tp({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:Rp[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??Sp,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??Sp,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 Ep;const Up=e=>{Ep?.applyDnsSwitch(e)},kp=e=>{Ep?.updateNetworkType(e)},Np=e=>{if("disabled"!==Ep?.state)return Ep?.startOperation(e)},Op=()=>{Ep?.reset(),Ep=void 0};class xp{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 wp({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 Gu({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new zu({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=Ed({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=Np({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 Lp=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()}},Pp=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},Dp=()=>{const e=Vo().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},$p=new Uint8Array([99,109]),qp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Bp=e=>Array.isArray(e)&&e.every(qp),Gp=e=>"string"==typeof e?e:void 0,Fp=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jp=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},zp=(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},Kp=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},Hp=(e,t)=>{const r=Hu().lookupType(e).decode(t);if(!qp(r))throw new Error(`${e} decoded result is invalid`);return r},Vp=e=>qp(e)&&"string"==typeof e.name?e.name:"",Wp=(e,t,r)=>{const s=(Bp(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=Fp(e.type)??ys,r=Boolean(Gp(e.remotePath))||Boolean(Gp(e.title))||Boolean(Gp(e.summary))||(Fp(e.combineLevel)??0)>0,s=t===ys&&0===e.subType&&r;if(t===_s||s){const t=Fp(e.combineLevel)??0;return{type:"combine",body:{title:Gp(e.title)??"",summary:Gp(e.summary)??"",filename:Gp(e.displayName)??"combine",filetype:"application/octet-stream",url:Gp(e.remotePath),secret:Gp(e.secretKey),fileLength:Fp(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ys)return{type:"text",body:{content:Gp(e.text)??""}};if(t===Ss)return{type:"cmd",body:{action:Gp(e.action)??""}};if(t===Ts){const t=el(Bp(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:Gp(e.customEvent)??"",params:t}}}if(t===Is)return{type:"location",body:{latitude:Fp(e.latitude)??0,longitude:Fp(e.longitude)??0,address:Gp(e.address),buildingName:Gp(e.buildingName)}};if(t===vs){const t=qp(e.size)?e.size:{},r=Gp(e.remotePath)??"",s=no(r),n=Gp(e.thumbnailRemotePath),o=io(e.imageType)===Wn;return{type:"image",body:{localUrl:"",filename:Gp(e.displayName)??"image",filetype:"application/octet-stream",width:Fp(t.width)??0,height:Fp(t.height)??0,isGif:1===e.subType,isOriginalImage:o,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:Gp(e.secretKey),fileLength:Fp(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===bs){const t=qp(e.size)?e.size:{};return{type:"video",body:{url:Gp(e.remotePath)??"",filename:Gp(e.displayName)??"video",filetype:"application/octet-stream",duration:Fp(e.duration)??0,width:Fp(t.width),height:Fp(t.height),secret:Gp(e.secretKey),fileLength:Fp(e.fileLength),thumbnailUrl:Gp(e.thumbnailRemotePath)}}}if(t===ws)return{type:"voice",body:{url:Gp(e.remotePath)??"",filename:Gp(e.displayName)??"voice",filetype:"application/octet-stream",duration:Fp(e.duration)??0,secret:Gp(e.secretKey),fileLength:Fp(e.fileLength)}};if(t===Cs)return{type:"file",body:{url:Gp(e.remotePath)??"",filename:Gp(e.displayName)??"file",filetype:"application/octet-stream",secret:Gp(e.secretKey),fileLength:Fp(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const o=Vp(e.from)||Vp(r?.from)||`unknown-${t}`,i=Vp(e.to)||Vp(r?.to)||`unknown-${t}`,a=(c=e.type)===us?"groupChat":c===ls?"chatRoom":"singleChat";var c;const d=i||o,u=Number(Yu(r?.timestamp))||Date.now(),l=el(Bp(e.ext)?e.ext:void 0),h={msgServerId:Yu(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},Jp=(e,t)=>{const r=[];try{const n=Hp("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=Hp("easemob.pb.MessageBody",o);return Wp(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=Hp("easemob.pb.MessageBody",e);return Wp(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=Hp("easemob.pb.MessageBody.Content",e);return Wp({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("; "))},Zp=(e,t)=>{const r=Ao(e);try{const e=JSON.parse(r);if(!qp(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 Jp(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)}})}}},Qp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Yp=(e,t,r)=>{throw new Zr(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},Xp=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:Qp(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},em=(e,t)=>{if(e.sender.userId||Yp(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,ir),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||Yp(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,ir),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&Yp(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,ir),Qp(e.body)||Yp(`messageList[${t}] body must be object`,`messageList[${t}].body`,ir),"combine"===e.type){const r=Xp(e);(!Number.isInteger(r)||r<0)&&Yp(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,ir),r>10&&Yp(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ar)}},tm=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&Yp("messageList must not be empty","messageList",ir),(!Number.isInteger(t)||t<=0||t>300)&&Yp("max items is invalid","maxItems",ir),e>t&&Yp(`messageList max length is ${t}`,"messageList",cr)},rm=e=>{tm(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?em(r,t):Yp(`messageList[${t}] is required`,`messageList[${t}]`,ir)}},sm=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=Xp(r);e>t&&(t=e)}return t+1},nm=e=>{(!Number.isInteger(e)||e<=0)&&Yp("combineLevel must be positive integer","combineLevel",ir),e>10&&Yp("combineLevel must be <= 10","combineLevel",ar)},om=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class im{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"};Zl(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"};Zl(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 Zl(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:om(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:om(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??[];rm(r);const s=sm(r);nm(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=$p.length+t.reduce((e,t)=>e+4+t.length,0)+1,s=new Uint8Array(r);let n=0;s.set($p,n),n+=$p.length;for(const e of t){const t=jp(e.length);s.set(t,n),n+=t.length,s.set(e,n),n+=e.length}const o=Kp(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=Pp(i);if(!a&&!this.attachmentUploader)throw new Qr("Combine payload local url generation failed",{code:dr});Lp.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 Zl(e,c),th(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};Zl(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||Lp.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"};Zl(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)>=Cp){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=Np({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<Cp&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<Cp&&(this.chatRoomReportSaturated=!1)))}}class am{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 cm{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new am}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 dm{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 um=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class lm{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new cm(r),this.messageContexts=new Map,this.recentMessageIds=new dm(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(!um(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(!um(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(!um(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(!um(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(!um(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(!um(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(!um(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(!um(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!um(t.message)||"string"!=typeof t.message.type||!um(t.message.body)||!um(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...um(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)um(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)!um(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 hm=e=>e instanceof Error?e.message:String(e);class pm{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Cd({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;tm(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:{[rl]:tl()}});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<$p.length+1)throw new Yr("Combine payload is too short",{code:lr});const t=e.subarray(0,$p.length);if(t[0]!==$p[0]||t[1]!==$p[1])throw new Yr("Combine payload header is invalid",{code:lr});const r=e.subarray(0,e.length-1),s=Kp(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=$p.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=zp(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=Zp(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 tm(o.length,r),rm(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:hm(o),url:n}})}}}const mm=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?Cd({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:{[rl]:tl()}});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",Gr);if(n.status>=400)throw new Hr("attachment download failed",er,{details:{status:n.status,url:r}});return{filename:mm(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 ym=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[rl]:tl(),...r??{}}),vm=async e=>{const t=ym(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)}},bm=(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:Br,success:!1,description:"Upload aborted"}),To("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload aborted",{code:Br,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(ym(t,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{c.setRequestHeader(e,t)}),c.send(l)}),Im=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 vm({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=bm(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 vm({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},wm=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:Br,success:!1,description:"Upload canceled"}),To("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.(),r(new rs("Upload canceled",{code:Br,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(rl,tl());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)}),Cm=Zd(),Sm=e=>Object.prototype.toString.call(e),Tm=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:Sm(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}},_m=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}),Rm=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Am=e=>"object"==typeof e&&null!==e,Mm=(e,t)=>{const r=Am(t)?t:void 0,s=r?.code===Do&&r.stage===Lo;return"miniapp-path"===e&&(e=>{if(!Am(e))return!1;const t=Am(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 Em{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(!Rm(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=Lp.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:Tm(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=Np({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===Br&&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:_m(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:_m(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:_m(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:_m(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:_m(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(!Rm(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(Mm(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:_m(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:_m(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"}),Cm;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(!Rm(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(!Rm(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:_m(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:_m(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Im(i)}catch(d){const e=d instanceof rs?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return wm(i);throw d}return wm(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(!Rm(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}`,[rl]:tl()},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:_m(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 Zl(e,n),th(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 Zl(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 Zl(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 Zl(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 Zl(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(!Mm(t.md5FileInfo.source.sourceType,n))throw n;To("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:_m(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 Um{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 km="__internal:core";class Nm{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 xp({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new Em({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 im(r,null,this.eventHub,s),this.messageReceiver=new lm(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new pm(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(km,{[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 Um(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(km),Lp.clear()}}const Om=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)},xm=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 Lm{getCrypto(){return Vo().crypto}constructor(e,t){if(this.enabled=(()=>{const e=Vo();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=si(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:Om(s),ct:Om(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=xm(t.iv),s=xm(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 Pm="conversationMap",Dm="userInfoMap",$m="groupNamecardMap",qm="contactRelationMap",Bm="contactVersion",Gm="contactMeta",Fm="sessionListMap",jm="sessionListCheckpoint",zm="joinedGroupPreview",Km="metadata",Hm=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Vm{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 Wm=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=Vo().localStorage;return t&&"function"==typeof t.getItem?t:null};class Jm{constructor(e){this.available=Jm.checkAvailable(),this.cryptoAdapter=e??null}static checkAvailable(){const e=Wm();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.available)return t;const r=Wm();if(!r)return t;try{const s=r.getItem(e);if(!s)return t;let n=s;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(s);if(null===e)return t;n=e}return ml(n,t)}catch(s){return To("CacheStore read failed",s),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.available)return;const s=(e=>{try{return JSON.stringify(e)}catch{return null}})(t);if(null===s){if(r)throw new TypeError("CacheStore value cannot be serialized");return}const n=Wm();if(n)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(s):s;n.setItem(e,t)}catch(o){if(fl(o))throw o;if(r)throw o;To("CacheStore write failed",o)}}remove(e){if(!this.available)return;const t=Wm();if(t)try{t.removeItem(e)}catch(r){To("CacheStore remove failed",r)}}}const Zm={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Qm={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Ym{constructor(){this.items=new Map,this.versionState=Zm,this.meta=Qm}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(!pl(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 pl(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"}:Zm}normalizeMeta(e){return pl(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"}:Qm}}const Xm=(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}},ef=(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}},tf=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 rf{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=Xm(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=ef(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:tf(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(!pl(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=pl(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 sf=(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(sf(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=sf(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(sf(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=sf(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(sf(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=Xm(n,e,t),i=new Set(o.removed.map(e=>sf(e.groupId,e.userId)));this.items.clear();for(const a of s)i.has(sf(a.groupId,a.userId))||this.items.set(sf(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=ef(s,Math.min(e,s.length)),o=new Set(n.removed.map(e=>sf(e.groupId,e.userId)));this.items.clear();for(const i of r)o.has(sf(i.groupId,i.userId))||this.items.set(sf(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||!pl(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 of=100,af=3e3,cf=e=>({...e}),df=e=>"object"==typeof e&&null!==e,uf=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 lf{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:of,serverLimit:af,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:of,serverLimit:af,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return df(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:uf(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,of),this.meta=(e=>{const t=df(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:of,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:af,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=>cf(e)).slice(0,of),this.meta={...e.meta,source:"localPreview",storageLimit:of,serverLimit:af,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>cf(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>cf(e)),meta:{...this.meta,source:"localPreview"}}}}const hf=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,pf=e=>{const t={...e};return delete t.type,t},mf=e=>{if(!pl(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!pl(e.body))return null;const r=((e,t)=>{if(pl(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=hf(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(pl(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:pf(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}:{}}},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 o=s;t.has(o)||(t.add(o),r.push(o))}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,o=t.lastMessageAt??t.updatedAt;return n!==o?o-n:e.conversationId.localeCompare(t.conversationId)};class yf{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(!pl(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=hf(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:mf(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:o,conversationAvatar:i,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class vf{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=Xm(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=ef(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(!pl(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 bf=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,If=e=>e.lastMessageAt??e.updatedAt,wf=e=>[...e].sort((e,t)=>{const r=bf(t)-bf(e);if(0!==r)return r;const s=If(t)-If(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),Cf=e=>`${e.conversationType}:${e.conversationId}`,Sf=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Tf=(e,t)=>((e,t)=>If(t)>If(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Sf(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,_f=e=>{const t=new Map,r=new Set;for(const o of e.snapshot)r.add(Cf(o));for(const o of e.existing)t.set(Cf(o),o);const s=e.snapshot.map(e=>{const r=t.get(Cf(e));return r?Tf(e,r):e}),n=e.existing.filter(t=>!r.has(Cf(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return wf([...s,...n])},Rf=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Af=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Mf=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 Ef{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,Rf.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 Uf=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class kf{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 Lm(e.appKey,e.userId);this.store=new Jm(t??void 0);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Hm(r,Pm),this.userInfoKey=Hm(r,Dm),this.groupNamecardKey=Hm(r,$m),this.sessionListKey=Hm(r,Fm),this.sessionListCheckpointKey=Hm(r,jm),this.joinedGroupPreviewKey=Hm(r,zm),this.contactRelationKey=Hm(r,qm),this.contactVersionKey=Hm(r,Bm),this.contactMetaKey=Hm(r,Gm),this.metadataKey=Hm(r,Km),this.metadataStore=new Vm(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new rf,this.userInfoCache=new vf,this.groupNamecardCache=new nf,this.sessionListCache=new yf,this.joinedGroupPreviewCache=new lf,this.contactCache=new Ym,this.userInfoRuntimeStore=new Ef,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 lf;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=_f({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?Af(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([Mf(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=Cf(e.nextRecord),r=e.existing.filter(e=>Cf(e)!==t);return wf([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&&pl(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(o,e);const i=(n&&pl(n)&&pl(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&&pl(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&pl(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 r=6;for(let s=0;s<=r;s+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!fl(t))return this.restoreDirtyBatch(e),void To("Cache flush failed",t);const r=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,r),"none"===r)return this.restoreDirtyBatch(e),void To("Cache flush failed: no cache entry can be evicted",t)}To("Cache flush failed after quota cleanup attempts"),this.restoreDirtyBatch(e)}finally{}}async writeDirtyDomains(e){for(const t of Uf)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),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=>bf(e)>0),r=new Map;for(const n of e.incoming)r.set(Cf(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(Cf(e))&&0===bf(e)):e.existing.filter(e=>!r.has(Cf(e)));return wf([...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(_f({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=Jl(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?Af(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 Nf{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 Of={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function xf(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 Lf(e){return new Promise(t=>setTimeout(t,e))}const Pf=e=>{const t={...e};return delete t.type,t},Df=(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:Pf(r.body),modifiedInfo:r.modifiedInfo,userInfoUpdateTime:r.userInfoUpdateTime,namecardUpdateTime:r.namecardUpdateTime}},$f=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},qf=async(e,t)=>{const r=await $f(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:Df(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 Bf{constructor(e=`session-list-${Dp()}`){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 Gf=0,Ff=5,jf=10,zf=11,Kf=1,Hf=2,Vf=1,Wf=2,Jf=3,Zf=e=>e===Kf?"groupChat":e===Hf?"chatRoom":"singleChat",Qf=()=>Hu().lookupType("easemob.pb.MessageBody"),Yf=e=>{const t=Qf().toObject(Qf().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:""}:{}},Xf=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}},eg=e=>{const t={...e};return delete t.type,t},tg=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,rg=(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:tg({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:eg(t)};var o},sg=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},ng=(e,t)=>e.sessions.map(e=>{const r=(e=>{if(!e||0===e.byteLength)return{};try{return Yf(e)}catch{return{}}})(e.last_message?.payload),s=e.session_id??"",n=Zf(e.session_type),o=(e=>{const t=e.session_id??"",r=Zf(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:Xf(e)})(e);return{conversationId:s,conversationType:n,unreadCount:e.unread_count??0,lastMessage:rg(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:sg(e.marks),readAt:e.read_receipt,remindType:(i=e.remind_type,i===Vf?"ALL":i===Wf?"AT":i===Jf?"NONE":"DEFAULT"),conversationName:o.conversationName,conversationAvatar:o.conversationAvatar};var i}),og={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 ig=null,ag=!1;const cg=()=>ig||(ag||(kc.util.Long=ci,kc.configure(),ag=!0),id(),ig=kc.Root.fromJSON(og),od(ig),ig),dg=e=>cg().lookupType(e),ug=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}},lg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:ug(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:ug(t.protocol_version)??ug(t.protocolVersion)??0}},hg=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}},pg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==ug(t.id)?String(ug(t.id)):void 0,from:hg(t.from),timestamp:ug(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 mg{constructor(){this.requestType=dg("easemob.sessionlist.GetSessionListRequest"),this.responseType=dg("easemob.sessionlist.GetSessionListResponse"),this.errorType=dg("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:Gf}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=ug(t.type);return r!==jf?null:{type:r,header:lg(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:ug(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=ug(t.type);return r!==zf?null:{type:r,header:lg(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:ug(t.session_type),last_message:pg(t.last_message),updated_at:ug(t.updated_at),pinned_time:ug(t.pinned_time),unread_count:ug(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:ug(t.read_receipt),remind_type:ug(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:ug(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=ug(t.type);return r!==Ff?null:{type:r,header:lg(t.header),code:ug(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,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 mg;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=ng(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}}}})},gg=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"}]}}),yg=(e,t,r)=>{const s=e+t;return s<r?String(s):""},vg=e=>({...e}),bg=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}},Ig=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,wg=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 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=Ig(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:yg(t,e.pageSize,r.length)}},Cg=()=>Date.now(),Sg={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Tg=(e,t)=>({status:e,determinedAt:Cg(),reason:t}),_g=e=>e instanceof Hr&&(e.code===kt||1103===e.code),Rg=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:_g(e)});class Ag{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 Bf,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={...Of,...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=xf(i,s);await Lf(e)}throw n}(async()=>{o+=1;const r=1===o?e:this.createRetrySession();r.start();try{return await fg({client:this.client,session:r,params:t})}catch(s){throw r.fail(),s}},_g,Sg),a={result:i,syncStartedAt:e.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:Cg()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:Cg()};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:Rg(t)}),r.loadSessionList()}const u=r.loadSessionList();return r.updateConversationsFromServer(u.map(bg),{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:Tg("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:Rg(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=Tg("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new Bf}async buildFallbackSessionList(e){return await(async(e,t)=>await qf(e,t))(e.loadConversationSummaries(),this.client)}}const Mg=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Eg=async e=>{if("string"==typeof e||Mg(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Mg(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}})},Ug=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},kg=async e=>{await new Promise(t=>{setTimeout(t,e)})},Ng=e=>e instanceof Error?e:new Error(String(e));class Og{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,Ng(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=Ng(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=Ug(this.attempt);To("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await kg(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=Vo(),s=this.socketAdapter??Ed({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 Eg(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Ng(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(Ng(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(Ng(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(Ng(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 xg=(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 Lg(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 Pg={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"}},Dg=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),$g=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 qg{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:Gr,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:Gr}}):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=Pg[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_${Dg(e)}`,operationType:r}})(t.operation):void 0,a=i?Np(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[rl]=tl());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=$g(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=$g(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(xg(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 Lg({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 Lg({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 Bg=async(e,t,r)=>{const{orgName:s,appName:n}=Qn(e.appKey),o=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,i=new qg(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(pl(e))return pl(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 Gg,Fg,jg;(Fg=Gg||(Gg={})).assertEqual=e=>{},Fg.assertIs=function(e){},Fg.assertNever=function(e){throw new Error},Fg.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},Fg.getValidEnumValues=e=>{const t=Fg.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return Fg.objectValues(r)},Fg.objectValues=e=>Fg.objectKeys(e).map(function(t){return e[t]}),Fg.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},Fg.find=(e,t)=>{for(const r of e)if(t(r))return r},Fg.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Fg.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},Fg.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(jg||(jg={})).mergeShapes=(e,t)=>({...e,...t});const zg=Gg.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Kg=e=>{switch(typeof e){case"undefined":return zg.undefined;case"string":return zg.string;case"number":return Number.isNaN(e)?zg.nan:zg.number;case"boolean":return zg.boolean;case"function":return zg.function;case"bigint":return zg.bigint;case"symbol":return zg.symbol;case"object":return Array.isArray(e)?zg.array:null===e?zg.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?zg.promise:"undefined"!=typeof Map&&e instanceof Map?zg.map:"undefined"!=typeof Set&&e instanceof Set?zg.set:"undefined"!=typeof Date&&e instanceof Date?zg.date:zg.object;default:return zg.unknown}},Hg=Gg.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 Vg 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 Vg))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Gg.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()}}Vg.create=e=>new Vg(e);const Wg=(e,t)=>{let r;switch(e.code){case Hg.invalid_type:r=e.received===zg.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Hg.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Gg.jsonStringifyReplacer)}`;break;case Hg.unrecognized_keys:r=`Unrecognized key(s) in object: ${Gg.joinValues(e.keys,", ")}`;break;case Hg.invalid_union:r="Invalid input";break;case Hg.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Gg.joinValues(e.options)}`;break;case Hg.invalid_enum_value:r=`Invalid enum value. Expected ${Gg.joinValues(e.options)}, received '${e.received}'`;break;case Hg.invalid_arguments:r="Invalid function arguments";break;case Hg.invalid_return_type:r="Invalid function return type";break;case Hg.invalid_date:r="Invalid date";break;case Hg.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}"`:Gg.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Hg.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 Hg.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 Hg.custom:r="Invalid input";break;case Hg.invalid_intersection_types:r="Intersection results could not be merged";break;case Hg.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Hg.not_finite:r="Number must be finite";break;default:r=t.defaultError,Gg.assertNever(e)}return{message:r}};let Jg=Wg;function Zg(e,t){const r=Jg,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===Wg?void 0:Wg].filter(e=>!!e)});e.common.issues.push(s)}class Qg{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 Yg;"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 Qg.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 Yg;if("aborted"===n.status)return Yg;"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 Yg=Object.freeze({status:"aborted"}),Xg=e=>({status:"dirty",value:e}),ey=e=>({status:"valid",value:e}),ty=e=>"aborted"===e.status,ry=e=>"dirty"===e.status,sy=e=>"valid"===e.status,ny=e=>"undefined"!=typeof Promise&&e instanceof Promise;var oy,iy;(iy=oy||(oy={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},iy.toString=e=>"string"==typeof e?e:e?.message;class ay{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 cy=(e,t)=>{if(sy(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 Vg(e.common.issues);return this._error=t,this._error}}};function dy(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 uy{get description(){return this._def.description}_getType(e){return Kg(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Kg(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Qg,ctx:{common:e.parent.common,data:e.data,parsedType:Kg(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:Kg(e)},s=this._parseSync({data:e,path:r.path,parent:r});return cy(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Kg(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return sy(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=>sy(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:Kg(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(ny(s)?s:Promise.resolve(s));return cy(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:Hg.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 uv({schema:this,typeName:wv.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 lv.create(this,this._def)}nullable(){return hv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wy.create(this)}promise(){return dv.create(this,this._def)}or(e){return Qy.create([this,e],this._def)}and(e){return Xy.create(this,e,this._def)}transform(e){return new uv({...dy(this._def),schema:this,typeName:wv.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new pv({...dy(this._def),innerType:this,defaultValue:t,typeName:wv.ZodDefault})}brand(){return new gv({typeName:wv.ZodBranded,type:this,...dy(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new mv({...dy(this._def),innerType:this,catchValue:t,typeName:wv.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return yv.create(this,e)}readonly(){return vv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ly=/^c[^\s-]{8,}$/i,hy=/^[0-9a-z]+$/,py=/^[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,yy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vy=/^[-+]?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)?)??$/,by=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Iy;const 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])$/,Cy=/^(?:(?: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])$/,Sy=/^(([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]))$/,Ty=/^(([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])$/,_y=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ry=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ay="((\\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])))",My=new RegExp(`^${Ay}$`);function Ey(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 Uy(e){return new RegExp(`^${Ey(e)}$`)}function ky(e){let t=`${Ay}T${Ey(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 Ny(e,t){return!("v4"!==t&&t||!wy.test(e))||!("v6"!==t&&t||!Sy.test(e))}function Oy(e,t){if(!yy.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 xy(e,t){return!("v4"!==t&&t||!Cy.test(e))||!("v6"!==t&&t||!Ty.test(e))}class Ly extends uy{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==zg.string){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.string,received:t.parsedType}),Yg}const t=new Qg;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.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),Zg(r,{code:Hg.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?Zg(r,{code:Hg.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&Zg(r,{code:Hg.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)by.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"email",code:Hg.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)Iy||(Iy=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Iy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"emoji",code:Hg.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)fy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"uuid",code:Hg.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)gy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"nanoid",code:Hg.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)ly.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"cuid",code:Hg.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)hy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"cuid2",code:Hg.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)py.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"ulid",code:Hg.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Zg(r,{validation:"url",code:Hg.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),Zg(r,{validation:"regex",code:Hg.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),Zg(r,{code:Hg.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),Zg(r,{code:Hg.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),Zg(r,{code:Hg.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){ky(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){My.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){Uy(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?vy.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"duration",code:Hg.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?Ny(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"ip",code:Hg.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?Oy(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"jwt",code:Hg.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?xy(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"cidr",code:Hg.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?_y.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"base64",code:Hg.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Ry.test(e.data)||(r=this._getOrReturnCtx(e,r),Zg(r,{validation:"base64url",code:Hg.invalid_string,message:s.message}),t.dirty()):Gg.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Hg.invalid_string,...oy.errToObj(r)})}_addCheck(e){return new Ly({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...oy.errToObj(e)})}url(e){return this._addCheck({kind:"url",...oy.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...oy.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...oy.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...oy.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...oy.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...oy.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...oy.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...oy.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...oy.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...oy.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...oy.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...oy.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,...oy.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,...oy.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...oy.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...oy.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...oy.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...oy.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...oy.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...oy.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...oy.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...oy.errToObj(t)})}nonempty(e){return this.min(1,oy.errToObj(e))}trim(){return new Ly({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ly({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ly({...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 Py(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}Ly.create=e=>new Ly({checks:[],typeName:wv.ZodString,coerce:e?.coerce??!1,...dy(e)});class Dy extends uy{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)!==zg.number){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.number,received:t.parsedType}),Yg}let t;const r=new Qg;for(const s of this._def.checks)if("int"===s.kind)Gg.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Zg(t,{code:Hg.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),Zg(t,{code:Hg.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),Zg(t,{code:Hg.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Py(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),Zg(t,{code:Hg.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Zg(t,{code:Hg.not_finite,message:s.message}),r.dirty()):Gg.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,oy.toString(t))}gt(e,t){return this.setLimit("min",e,!1,oy.toString(t))}lte(e,t){return this.setLimit("max",e,!0,oy.toString(t))}lt(e,t){return this.setLimit("max",e,!1,oy.toString(t))}setLimit(e,t,r,s){return new Dy({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:oy.toString(s)}]})}_addCheck(e){return new Dy({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:oy.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:oy.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:oy.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:oy.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:oy.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:oy.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:oy.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:oy.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:oy.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&&Gg.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)}}Dy.create=e=>new Dy({checks:[],typeName:wv.ZodNumber,coerce:e?.coerce||!1,...dy(e)});class $y extends uy{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)!==zg.bigint)return this._getInvalidInput(e);let t;const r=new Qg;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),Zg(t,{code:Hg.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),Zg(t,{code:Hg.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),Zg(t,{code:Hg.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Gg.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.bigint,received:t.parsedType}),Yg}gte(e,t){return this.setLimit("min",e,!0,oy.toString(t))}gt(e,t){return this.setLimit("min",e,!1,oy.toString(t))}lte(e,t){return this.setLimit("max",e,!0,oy.toString(t))}lt(e,t){return this.setLimit("max",e,!1,oy.toString(t))}setLimit(e,t,r,s){return new $y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:oy.toString(s)}]})}_addCheck(e){return new $y({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:oy.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:oy.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:oy.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:oy.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:oy.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}}$y.create=e=>new $y({checks:[],typeName:wv.ZodBigInt,coerce:e?.coerce??!1,...dy(e)});class qy extends uy{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==zg.boolean){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.boolean,received:t.parsedType}),Yg}return ey(e.data)}}qy.create=e=>new qy({typeName:wv.ZodBoolean,coerce:e?.coerce||!1,...dy(e)});class By extends uy{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==zg.date){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.date,received:t.parsedType}),Yg}if(Number.isNaN(e.data.getTime())){return Zg(this._getOrReturnCtx(e),{code:Hg.invalid_date}),Yg}const t=new Qg;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),Zg(r,{code:Hg.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),Zg(r,{code:Hg.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):Gg.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new By({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:oy.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:oy.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}}By.create=e=>new By({checks:[],coerce:e?.coerce||!1,typeName:wv.ZodDate,...dy(e)});class Gy extends uy{_parse(e){if(this._getType(e)!==zg.symbol){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.symbol,received:t.parsedType}),Yg}return ey(e.data)}}Gy.create=e=>new Gy({typeName:wv.ZodSymbol,...dy(e)});class Fy extends uy{_parse(e){if(this._getType(e)!==zg.undefined){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.undefined,received:t.parsedType}),Yg}return ey(e.data)}}Fy.create=e=>new Fy({typeName:wv.ZodUndefined,...dy(e)});class jy extends uy{_parse(e){if(this._getType(e)!==zg.null){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.null,received:t.parsedType}),Yg}return ey(e.data)}}jy.create=e=>new jy({typeName:wv.ZodNull,...dy(e)});class zy extends uy{constructor(){super(...arguments),this._any=!0}_parse(e){return ey(e.data)}}zy.create=e=>new zy({typeName:wv.ZodAny,...dy(e)});class Ky extends uy{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ey(e.data)}}Ky.create=e=>new Ky({typeName:wv.ZodUnknown,...dy(e)});class Hy extends uy{_parse(e){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.never,received:t.parsedType}),Yg}}Hy.create=e=>new Hy({typeName:wv.ZodNever,...dy(e)});class Vy extends uy{_parse(e){if(this._getType(e)!==zg.undefined){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.void,received:t.parsedType}),Yg}return ey(e.data)}}Vy.create=e=>new Vy({typeName:wv.ZodVoid,...dy(e)});class Wy extends uy{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==zg.array)return Zg(t,{code:Hg.invalid_type,expected:zg.array,received:t.parsedType}),Yg;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(Zg(t,{code:e?Hg.too_big:Hg.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&&(Zg(t,{code:Hg.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&&(Zg(t,{code:Hg.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 ay(t,e,t.path,r)))).then(e=>Qg.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new ay(t,e,t.path,r)));return Qg.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Wy({...this._def,minLength:{value:e,message:oy.toString(t)}})}max(e,t){return new Wy({...this._def,maxLength:{value:e,message:oy.toString(t)}})}length(e,t){return new Wy({...this._def,exactLength:{value:e,message:oy.toString(t)}})}nonempty(e){return this.min(1,e)}}function Jy(e){if(e instanceof Zy){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=lv.create(Jy(s))}return new Zy({...e._def,shape:()=>t})}return e instanceof Wy?new Wy({...e._def,type:Jy(e.element)}):e instanceof lv?lv.create(Jy(e.unwrap())):e instanceof hv?hv.create(Jy(e.unwrap())):e instanceof ev?ev.create(e.items.map(e=>Jy(e))):e}Wy.create=(e,t)=>new Wy({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wv.ZodArray,...dy(t)});class Zy extends uy{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=Gg.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==zg.object){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.object,received:t.parsedType}),Yg}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),o=[];if(!(this._def.catchall instanceof Hy&&"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 ay(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof Hy){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&&(Zg(r,{code:Hg.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 ay(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=>Qg.mergeObjectSync(t,e)):Qg.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return oy.errToObj,new Zy({...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:oy.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Zy({...this._def,unknownKeys:"strip"})}passthrough(){return new Zy({...this._def,unknownKeys:"passthrough"})}extend(e){return new Zy({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Zy({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:wv.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Zy({...this._def,catchall:e})}pick(e){const t={};for(const r of Gg.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Zy({...this._def,shape:()=>t})}omit(e){const t={};for(const r of Gg.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Zy({...this._def,shape:()=>t})}deepPartial(){return Jy(this)}partial(e){const t={};for(const r of Gg.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new Zy({...this._def,shape:()=>t})}required(e){const t={};for(const r of Gg.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof lv;)e=e._def.innerType;t[r]=e}return new Zy({...this._def,shape:()=>t})}keyof(){return iv(Gg.objectKeys(this.shape))}}Zy.create=(e,t)=>new Zy({shape:()=>e,unknownKeys:"strip",catchall:Hy.create(),typeName:wv.ZodObject,...dy(t)}),Zy.strictCreate=(e,t)=>new Zy({shape:()=>e,unknownKeys:"strict",catchall:Hy.create(),typeName:wv.ZodObject,...dy(t)}),Zy.lazycreate=(e,t)=>new Zy({shape:e,unknownKeys:"strip",catchall:Hy.create(),typeName:wv.ZodObject,...dy(t)});class Qy extends uy{_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 Vg(e.ctx.common.issues));return Zg(t,{code:Hg.invalid_union,unionErrors:r}),Yg});{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 Vg(e));return Zg(t,{code:Hg.invalid_union,unionErrors:n}),Yg}}get options(){return this._def.options}}function Yy(e,t){const r=Kg(e),s=Kg(t);if(e===t)return{valid:!0,data:e};if(r===zg.object&&s===zg.object){const r=Gg.objectKeys(t),s=Gg.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const o of s){const r=Yy(e[o],t[o]);if(!r.valid)return{valid:!1};n[o]=r.data}return{valid:!0,data:n}}if(r===zg.array&&s===zg.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=Yy(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===zg.date&&s===zg.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Qy.create=(e,t)=>new Qy({options:e,typeName:wv.ZodUnion,...dy(t)});class Xy extends uy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(ty(e)||ty(s))return Yg;const n=Yy(e.value,s.value);return n.valid?((ry(e)||ry(s))&&t.dirty(),{status:t.value,value:n.data}):(Zg(r,{code:Hg.invalid_intersection_types}),Yg)};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}))}}Xy.create=(e,t,r)=>new Xy({left:e,right:t,typeName:wv.ZodIntersection,...dy(r)});class ev extends uy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==zg.array)return Zg(r,{code:Hg.invalid_type,expected:zg.array,received:r.parsedType}),Yg;if(r.data.length<this._def.items.length)return Zg(r,{code:Hg.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Yg;!this._def.rest&&r.data.length>this._def.items.length&&(Zg(r,{code:Hg.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 ay(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>Qg.mergeArray(t,e)):Qg.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ev({...this._def,rest:e})}}ev.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ev({items:e,typeName:wv.ZodTuple,rest:null,...dy(t)})};class tv extends uy{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!==zg.object)return Zg(r,{code:Hg.invalid_type,expected:zg.object,received:r.parsedType}),Yg;const s=[],n=this._def.keyType,o=this._def.valueType;for(const i in r.data)s.push({key:n._parse(new ay(r,i,r.path,i)),value:o._parse(new ay(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?Qg.mergeObjectAsync(t,s):Qg.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new tv(t instanceof uy?{keyType:e,valueType:t,typeName:wv.ZodRecord,...dy(r)}:{keyType:Ly.create(),valueType:e,typeName:wv.ZodRecord,...dy(t)})}}class rv extends uy{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!==zg.map)return Zg(r,{code:Hg.invalid_type,expected:zg.map,received:r.parsedType}),Yg;const s=this._def.keyType,n=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:s._parse(new ay(r,e,r.path,[o,"key"])),value:n._parse(new ay(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 Yg;"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 Yg;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}rv.create=(e,t,r)=>new rv({valueType:t,keyType:e,typeName:wv.ZodMap,...dy(r)});class sv extends uy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==zg.set)return Zg(r,{code:Hg.invalid_type,expected:zg.set,received:r.parsedType}),Yg;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(Zg(r,{code:Hg.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&&(Zg(r,{code:Hg.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 Yg;"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 ay(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>o(e)):o(i)}min(e,t){return new sv({...this._def,minSize:{value:e,message:oy.toString(t)}})}max(e,t){return new sv({...this._def,maxSize:{value:e,message:oy.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}sv.create=(e,t)=>new sv({valueType:e,minSize:null,maxSize:null,typeName:wv.ZodSet,...dy(t)});class nv extends uy{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})}}nv.create=(e,t)=>new nv({getter:e,typeName:wv.ZodLazy,...dy(t)});class ov extends uy{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Zg(t,{received:t.data,code:Hg.invalid_literal,expected:this._def.value}),Yg}return{status:"valid",value:e.data}}get value(){return this._def.value}}function iv(e,t){return new av({values:e,typeName:wv.ZodEnum,...dy(t)})}ov.create=(e,t)=>new ov({value:e,typeName:wv.ZodLiteral,...dy(t)});class av extends uy{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return Zg(t,{expected:Gg.joinValues(r),received:t.parsedType,code:Hg.invalid_type}),Yg}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 Zg(t,{received:t.data,code:Hg.invalid_enum_value,options:r}),Yg}return ey(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 av.create(e,{...this._def,...t})}exclude(e,t=this._def){return av.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}av.create=iv;class cv extends uy{_parse(e){const t=Gg.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==zg.string&&r.parsedType!==zg.number){const e=Gg.objectValues(t);return Zg(r,{expected:Gg.joinValues(e),received:r.parsedType,code:Hg.invalid_type}),Yg}if(this._cache||(this._cache=new Set(Gg.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Gg.objectValues(t);return Zg(r,{received:r.data,code:Hg.invalid_enum_value,options:e}),Yg}return ey(e.data)}get enum(){return this._def.values}}cv.create=(e,t)=>new cv({values:e,typeName:wv.ZodNativeEnum,...dy(t)});class dv extends uy{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==zg.promise&&!1===t.common.async)return Zg(t,{code:Hg.invalid_type,expected:zg.promise,received:t.parsedType}),Yg;const r=t.parsedType===zg.promise?t.data:Promise.resolve(t.data);return ey(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}dv.create=(e,t)=>new dv({type:e,typeName:wv.ZodPromise,...dy(t)});class uv extends uy{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wv.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=>{Zg(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 Yg;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?Yg:"dirty"===s.status||"dirty"===t.value?Xg(s.value):s});{if("aborted"===t.value)return Yg;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?Yg:"dirty"===s.status||"dirty"===t.value?Xg(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?Yg:("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?Yg:("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(!sy(e))return Yg;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=>sy(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):Yg)}Gg.assertNever(s)}}uv.create=(e,t,r)=>new uv({schema:e,typeName:wv.ZodEffects,effect:t,...dy(r)}),uv.createWithPreprocess=(e,t,r)=>new uv({schema:t,effect:{type:"preprocess",transform:e},typeName:wv.ZodEffects,...dy(r)});class lv extends uy{_parse(e){return this._getType(e)===zg.undefined?ey(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}lv.create=(e,t)=>new lv({innerType:e,typeName:wv.ZodOptional,...dy(t)});class hv extends uy{_parse(e){return this._getType(e)===zg.null?ey(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}hv.create=(e,t)=>new hv({innerType:e,typeName:wv.ZodNullable,...dy(t)});class pv extends uy{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===zg.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}pv.create=(e,t)=>new pv({innerType:e,typeName:wv.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...dy(t)});class mv extends uy{_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 Vg(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Vg(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}mv.create=(e,t)=>new mv({innerType:e,typeName:wv.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...dy(t)});class fv extends uy{_parse(e){if(this._getType(e)!==zg.nan){const t=this._getOrReturnCtx(e);return Zg(t,{code:Hg.invalid_type,expected:zg.nan,received:t.parsedType}),Yg}return{status:"valid",value:e.data}}}fv.create=e=>new fv({typeName:wv.ZodNaN,...dy(e)});class gv extends uy{_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 yv extends uy{_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?Yg:"dirty"===e.status?(t.dirty(),Xg(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?Yg:"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 yv({in:e,out:t,typeName:wv.ZodPipeline})}}class vv extends uy{_parse(e){const t=this._def.innerType._parse(e),r=e=>(sy(e)&&(e.value=Object.freeze(e.value)),e);return ny(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function bv(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Iv(e,t={},r){return e?zy.create().superRefine((s,n)=>{const o=e(s);if(o instanceof Promise)return o.then(e=>{if(!e){const e=bv(t,s),o=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:o})}});if(!o){const e=bv(t,s),o=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:o})}}):zy.create()}var wv,Cv;vv.create=(e,t)=>new vv({innerType:e,typeName:wv.ZodReadonly,...dy(t)}),(Cv=wv||(wv={})).ZodString="ZodString",Cv.ZodNumber="ZodNumber",Cv.ZodNaN="ZodNaN",Cv.ZodBigInt="ZodBigInt",Cv.ZodBoolean="ZodBoolean",Cv.ZodDate="ZodDate",Cv.ZodSymbol="ZodSymbol",Cv.ZodUndefined="ZodUndefined",Cv.ZodNull="ZodNull",Cv.ZodAny="ZodAny",Cv.ZodUnknown="ZodUnknown",Cv.ZodNever="ZodNever",Cv.ZodVoid="ZodVoid",Cv.ZodArray="ZodArray",Cv.ZodObject="ZodObject",Cv.ZodUnion="ZodUnion",Cv.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Cv.ZodIntersection="ZodIntersection",Cv.ZodTuple="ZodTuple",Cv.ZodRecord="ZodRecord",Cv.ZodMap="ZodMap",Cv.ZodSet="ZodSet",Cv.ZodFunction="ZodFunction",Cv.ZodLazy="ZodLazy",Cv.ZodLiteral="ZodLiteral",Cv.ZodEnum="ZodEnum",Cv.ZodEffects="ZodEffects",Cv.ZodNativeEnum="ZodNativeEnum",Cv.ZodOptional="ZodOptional",Cv.ZodNullable="ZodNullable",Cv.ZodDefault="ZodDefault",Cv.ZodCatch="ZodCatch",Cv.ZodPromise="ZodPromise",Cv.ZodBranded="ZodBranded",Cv.ZodPipeline="ZodPipeline",Cv.ZodReadonly="ZodReadonly";const Sv=Ly.create,Tv=Dy.create,_v=qy.create;zy.create;const Rv=Ky.create,Av=Hy.create,Mv=Wy.create,Ev=Zy.create,Uv=Qy.create;Xy.create,ev.create;const kv=tv.create,Nv=av.create;dv.create,lv.create,hv.create;class Ov{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof Vg){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 xv=e=>Sv().regex(/^https?:\/\/\S+$/i,e),Lv=e=>Sv().regex(/^wss?:\/\/\S+$/i,e),Pv=Ev({appKey:Sv().min(1,"appKey is required"),enableUserInfoSync:_v().optional(),enableSyncData:Mv(Nv(["conversation","contact","group"])).optional(),enableDeliveryReceipt:_v().optional(),deleteConversationOnGroupDestroyed:_v().optional(),syncConversationListConfig:Ev({includeEmpty:_v().optional()}).strict().optional(),useCustomAttachmentUpload:_v().optional(),useFixedDeviceId:_v().optional(),deviceId:Sv().min(1,"deviceId is required").optional(),serviceConfig:Ev({dnsConfigUrls:Mv(xv("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:Ev({restApiUrl:xv("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:Lv("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:xv("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:Lv("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:_v().optional(),customDeviceName:Sv().min(1,"customDeviceName is required").optional(),customOSPlatform:Tv().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:Sv().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Sv().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:Mv(Rv()).optional(),platformAdapterOptions:Ev({prefer:Nv(["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:Iv(e=>"object"==typeof e&&null!==e).optional(),overrides:Iv(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{"enableMd5Check"in e&&t.addIssue({code:Hg.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:Hg.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:Hg.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:Hg.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:Hg.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:Hg.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:Hg.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:Hg.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),s&&(s?.restApiUrl||t.addIssue({code:Hg.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),s?.wsUrl||t.addIssue({code:Hg.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),Dv=Ev({userId:Sv().min(1,"userId is required"),token:Sv().min(1,"token is required")}),$v=Sv().trim().min(1,"token is required"),qv=Ev({channelName:Sv().trim().min(1,"channelName is required").optional()}).optional(),Bv=Mv(Tv({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))),Gv=Ev({protocol:Sv(),domain:Sv().optional(),ip:Sv().optional(),port:Uv([Sv(),Tv()]).optional()}).passthrough(),Fv=Ev({rest:Ev({hosts:Mv(Gv).nonempty()}),"msync-wx":Ev({hosts:Mv(Gv).nonempty()}),"sync-ws":Ev({hosts:Mv(Gv).nonempty()}).optional(),enableReportLogs:Nv(["true","false"]).optional(),reportInterval:Tv().positive().finite().optional(),enableDataReport:Nv(["true","false"]).optional(),enableMd5Check:Nv(["true","false"]).optional(),uploadinparts_enable:Nv(["true","false"]).optional()}).passthrough(),jv=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],zv=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],Kv=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function Hv(e){return"object"==typeof e&&null!==e}function Vv(e){return Array.isArray(e)?{hosts:e}:function(e){return Hv(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Wv(e,t,r){for(const s of t){const t=Vv(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=Vv(n);if(e)return{key:s,section:e}}}function Jv(e){if(!Hv(e))return Ov.validateOrThrow(Fv,e);const t=Vv(e.rest),r=Wv(e,zv,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s=Wv(e,Kv,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&&!Vv(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}),Ov.validateOrThrow(Fv,n)}function Zv(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 Qv(e,t){return"https"===e?"https":"http"===e?"http":t}function Yv(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 Xv(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 tb(e,t,r){const s=new qg(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}?${new URLSearchParams({app_key:t,_v:String(Date.now())}).toString()}`}return Jv(await s.get(n))}function rb(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,Qv(e.protocol,t))).filter(e=>"string"==typeof e&&e.length>0):[]}async function sb(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:jv;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 tb(i,e.appKey,e.requestAdapter),s=eb(Xv(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=Xv(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=>Zv(e,Qv(e.protocol,r))),d=Zv(n,Qv(n.protocol,r)),u=rb(t,r);return{websocketUrl:d,websocketUrls:c,syncWebsocketUrls:u,baseUrl:i,restBaseUrl:Yv(a,Qv(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 nb=e=>new Zr(e,{code:ot,details:{reason:"invalid_rest_response"}}),ob=e=>{if(!pl(e))throw nb("Invalid REST response");return pl(e.data)?e.data:e},ib=(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}}},ab=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},cb=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},db=async(e,t)=>{const r=await e.get((e=>`${cb(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=ob(e),r=ib(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw nb("Invalid token expires response");return r})(r)},ub=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=new URLSearchParams({channelName:t?.channelName??"*"});return`${cb(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=ob(e);return{appId:ab(t,["app_id","appId"])??"",rtcToken:ab(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:ab(t,["channel_name","channelName"])??"",rtcUid:ib(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:ib(t,["expires_in","expire","expireAt"])??0}})(s)},lb=async(e,t,r)=>{const s=await e.post((e=>`${cb(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=ob(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)},hb=async(e,t)=>{const r=await e.get((e=>`${cb(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=pl(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!pl(n))continue;const e=ab(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},pb=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},mb={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:{}},fb=e=>({userId:e}),gb=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),yb=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 i of n)s.set(i.userId,gb(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,yb(t))}for(const i of r)s.has(i)||s.set(i,fb(i));return s};class bb{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 Ib{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 wb=0,Cb=1,Sb=2,Tb=3,_b=4,Rb=5,Ab=0,Mb=0,Eb=1,Ub=1001,kb=1002,Nb=1003,Ob=1004,xb=1005,Lb=1101,Pb=pb(mb,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Db=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=$u(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new Nf,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 Ib({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new bb({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)},[B]:e=>{this.handleMultiDeviceContactEvent(e)},[G]: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=Ov.validateOrThrow(Pv,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=Ov.validateOrThrow(Dv,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??$u(this.config.platformAdapterOptions);var c;this.platformAdapter=a,c={requestAdapter:a.request,onDiagnostic:(e,t)=>{To(e,t)}},Ep?.reset(),Ep=new Mp(c);const d=(e=>Ep?.startSession(e))({appKey:this.config.appKey,uid:o.userId,sdkVersion:"5.0.0",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=>{kp(e)}).catch(()=>{kp("unknown")});const l=Np({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 sb({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}),Up(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}),Up(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}),Up(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,Up(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),Op(),e}this.core=new Nm({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=>{Ep?.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),Op(),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 Op();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(),Op()}}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=Ov.validateOrThrow($v,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 qg(n.restBaseUrl,{errorMap:Pb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});o.setAuthToken(t),To("Renew token started",{userId:r.userId});const i=await db(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=Ov.validateOrThrow(qv,e),r=this.getRestContext(),s=new qg(r.restBaseUrl,{errorMap:Pb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),To("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),ub(s,r,t)}async getUserIdsWithRTCUids(e){const t=Ov.validateOrThrow(Bv,e),r=this.getRestContext(),s=new qg(r.restBaseUrl,{errorMap:Pb,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),To("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),lb(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new qg(e.restBaseUrl,{errorMap:Pb,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}),hb(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 Og({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:Yl(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 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=Jl(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=>{Vl.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};Wl(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 kf({appKey:this.config.appKey,userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode}),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(vg),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 Ag(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 Bg(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 sb({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=new URL(e);return""!==r.pathname&&"/"!==r.pathname||(r.pathname="/ws"),r.searchParams.set("token",t),r.toString()}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:Tb,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??jv,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)}};Db.instance=null;let $b=Db;const qb=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Bb=(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()},Gb=e=>`mark_${String(e)}`,Fb=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw qb(t,`${t} must be one of singleChat, groupChat, chatRoom`)},jb=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",zb=e=>"string"==typeof e&&e.length>0?e:void 0,Kb=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}},Hb=e=>pl(e)?e:void 0,Vb=(e,t)=>{const r=Hb(e);if(!r)return;const s=(e=>"string"==typeof e?ml(e,{}):Hb(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],o=Hb(n[0])??Hb(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:zb(t.msg)??zb(t.content)??""};if("custom"===e){const e=Hb(t.customExts)??Hb(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:zb(t.customEvent)??zb(t.event)??"",params:r}}if("cmd"===e)return{action:zb(t.action)??""};if("image"===e){const e=zb(t.url)??zb(t.remotePath)??"";return{localUrl:"",filename:zb(t.filename)??zb(t.displayName),filetype:zb(t.filetype)??"application/octet-stream",width:Kb(t.width),height:Kb(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:zb(t.bigImageUrl),thumbnailUrl:zb(t.thumbnailUrl)??zb(t.thumbnailRemotePath),secret:zb(t.secret)??zb(t.secretKey),fileLength:Kb(t.fileLength)}}return"file"===e?{url:zb(t.url)??zb(t.remotePath),filename:zb(t.filename)??zb(t.displayName),filetype:zb(t.filetype)??"application/octet-stream",fileSize:Kb(t.fileSize),fileLength:Kb(t.fileLength),secret:zb(t.secret)??zb(t.secretKey)}:"voice"===e?{url:zb(t.url)??zb(t.remotePath),filename:zb(t.filename)??zb(t.displayName),filetype:zb(t.filetype)??"application/octet-stream",duration:Kb(t.duration)??0,fileLength:Kb(t.fileLength),secret:zb(t.secret)??zb(t.secretKey)}:"video"===e?{url:zb(t.url)??zb(t.remotePath),filename:zb(t.filename)??zb(t.displayName),filetype:zb(t.filetype)??"application/octet-stream",duration:Kb(t.duration)??0,width:Kb(t.width),height:Kb(t.height),fileLength:Kb(t.fileLength),secret:zb(t.secret)??zb(t.secretKey),thumbnailUrl:zb(t.thumbnailUrl)??zb(t.thumbnailRemotePath)}:"location"===e?{latitude:Kb(t.latitude)??0,longitude:Kb(t.longitude)??0,address:zb(t.address),buildingName:zb(t.buildingName)}:null})(i,o);if(!a)return;const c=zb(s.from)??zb(r.from)??"",d=zb(s.to)??t.conversationId,u=Hb(s.sender),l={userId:zb(u?.userId)??c,nickname:zb(u?.nickname),avatarUrl:zb(u?.avatarUrl)},h=Hb(s.ext)??{},p=(e=>{const t=Hb(e);if(!t)return;const r=zb(t.operatorId)??zb(t.operator),s=Kb(t.operationCount)??Kb(t.count),n=Kb(t.operationTime)??Kb(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??Hb(s.meta)?.edit_msg);return{msgServerId:zb(r.id)??t.messageId,msgLocalId:zb(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:i,sendStatus:"sent",ext:h,timestamp:Kb(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},Wb=e=>`${e.conversationType}:${e.conversationId}`,Jb=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},Zb=async(e,t,r,s)=>{const n=Jb(t),o=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw qb("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!pl(e))throw qb(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:Bb(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:Fb(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:Bb(t.conversationId,"params.conversationId"),conversationType:Fb(t.conversationType,"params.conversationType")}]})(r),i=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw qb(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:Gb(i),targets:o.map(e=>({to:e.conversationId,type:jb(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!pl(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(Wb({conversationId:r,conversationType:s}))}),t})((pl(a)&&pl(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of o){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(Wb(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:i,operation:s?"addMark":"removeMark"}},Qb=async(e,t,r,s)=>{const n=Jb(t),o=Bb(r.conversationId,"params.conversationId"),i=Fb(r.conversationType,"params.conversationType"),a=Bb(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:jb(i),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:o,conversationType:i,messageId:a,operation:s?"pin":"unpin"}},Yb=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Xb=(e,t)=>`${e}\0${t}`,eI=(e,t,r)=>{const s={userId:e};for(const n of Yb){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},tI=e=>eI(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),rI=(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(Xb(n.groupId,n.user.userId),t.namecard)}return s},sI=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}),[]}},nI=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})}}))},oI=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=Xb(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,tI(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),o=new Set(n),i=rI(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=Xb(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([sI(n,e.fetchUserInfos),nI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=rI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=Xb(h.groupId,e),r=eI(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))}},iI=async e=>{const t=await oI({...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(Xb(e.groupId.trim(),n));o&&r.set(n,o)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},aI=Nv(["singleChat","groupChat","chatRoom"]),cI=kv(Rv()).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"),dI=Ev({path:Sv().min(1,"data.path is required"),size:Tv().optional(),name:Sv().optional(),type:Sv().optional()}),uI=Ev({uri:Sv().min(1,"data.uri is required"),size:Tv().optional(),name:Sv().optional(),type:Sv().optional()}),lI=Uv(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>Iv(t=>t instanceof e,t))(File):Av(),dI,uI]),hI=Ev({conversationId:Sv().min(1,"conversationId is required"),conversationType:aI,ext:cI.optional(),timestamp:Tv().int().positive("timestamp must be a positive integer").optional(),receiverList:Mv(Sv().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:_v().optional(),webhookEnv:Sv().optional(),priority:Nv(["high","normal","low"]).optional(),needReadReceipt:_v().optional(),isChatThread:_v().optional()}),pI=Ev({type:Sv().min(1,"messageList.type is required"),sender:Ev({userId:Sv().min(1,"messageList.sender.userId is required"),nickname:Sv().optional(),avatarUrl:Sv().optional()}),conversationId:Sv().min(1,"messageList.conversationId is required"),conversationType:aI,timestamp:Tv().int().positive("messageList.timestamp must be positive"),body:kv(Rv()),combineLevel:Tv().int().min(0).max(10).optional()}).passthrough(),mI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:Hg.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:Hg.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:Hg.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),fI=mI(hI.extend({content:Sv().min(1,"content is required"),targetLanguages:Mv(Sv().min(1)).optional()})),gI=mI(hI.extend({originalUrl:Sv().min(1,"originalUrl is required").optional(),filename:Sv().min(1,"filename is required").optional(),filetype:Sv().min(1,"filetype is required").optional(),width:Tv().positive("width must be positive").optional(),height:Tv().positive("height must be positive").optional(),isGif:_v().optional(),isOriginalImage:_v().optional(),fileLength:Tv().positive("fileLength must be positive").optional(),data:lI.optional(),thumbnailUrl:Sv().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),yI=mI(hI.extend({originalUrl:Sv().min(1,"originalUrl is required").optional(),filename:Sv().min(1,"filename is required").optional(),filetype:Sv().min(1,"filetype is required").optional(),fileSize:Tv().positive("fileSize must be positive").optional(),fileLength:Tv().positive("fileLength must be positive").optional(),data:lI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),vI=mI(hI.extend({originalUrl:Sv().min(1,"originalUrl is required").optional(),filename:Sv().min(1,"filename is required").optional(),filetype:Sv().min(1,"filetype is required").optional(),duration:Tv().positive("duration must be positive"),fileLength:Tv().positive("fileLength must be positive").optional(),data:lI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),bI=mI(hI.extend({originalUrl:Sv().min(1,"originalUrl is required").optional(),filename:Sv().min(1,"filename is required").optional(),filetype:Sv().min(1,"filetype is required").optional(),duration:Tv().positive("duration must be positive"),width:Tv().positive("width must be positive").optional(),height:Tv().positive("height must be positive").optional(),fileLength:Tv().positive("fileLength must be positive").optional(),thumbnailUrl:Sv().min(1).optional(),data:lI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),II=mI(hI.extend({latitude:Tv(),longitude:Tv(),address:Sv().min(1).optional(),buildingName:Sv().min(1).optional()})),wI=mI(hI.extend({action:Sv().min(1,"action is required")})),CI=mI(hI.extend({event:Sv().min(1,"event is required"),params:kv(Sv()).optional()})),SI=mI(hI.extend({title:Sv().min(1,"title is required"),summary:Sv().min(1,"summary is required"),compatibleText:Sv().min(1).optional(),messageList:Mv(pI).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),TI=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=()=>Dp(),RI=(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=Pp(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},AI=e=>!!e.isGif||(e.isOriginalImage??!1),MI=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??Dp(),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}),EI=(e,t)=>{const r=Ov.validateOrThrow(SI,e),s=r.messageList,n=TI(t);rm(s);const o=sm(s);nm(o);const i={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:o},a=MI(r,n,"combine",i);return((e,t)=>{t&&Xl.set(e,t)})(a,r.compatibleText),a},UI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},kI=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},NI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),OI=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})}},xI=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",LI=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},PI=e=>({userId:e}),DI=(e,t)=>{if(!NI(e)||!NI(e.data))throw Lg({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},$I=(e,t)=>{if(!NI(e)||!Array.isArray(e.data))throw Lg({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},qI=(e,t)=>Array.isArray(e)?e:$I(e,t),BI={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},GI={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},FI={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},jI=(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)},zI=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},KI=(e,t,r)=>{const s=xI(r.contentType??r.type),n=GI[s];if(!n)return null;const o=NI(r.content)?r.content:{},i=((e,t)=>{const r=xI(t.conversationType);if("groupchat"===r||"chatroom"===r)return xI(t.receiverId);const s=xI(t.senderId);return s===e?xI(t.receiverId):s})(t,r),a=FI[xI(r.conversationType)]??"singleChat",c={msgServerId:xI(r.messageId),msgLocalId:xI(r.messageId),from:xI(r.senderId),to:xI(r.receiverId),conversationId:i,conversationType:a,type:n,ext:NI(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(xI(r.sentTime)).getTime(),sender:{userId:xI(r.senderId)},highlight:zI(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=xI(o.remotePath??o.url),l=xI(o.secret??o.secretKey);switch(n){case"txt":d={type:"txt",content:xI(o.message??r.text)};break;case"img":{const t=jI(e,u,l);d={type:"img",url:t,thumb:o.thumb?jI(e,xI(o.thumb),xI(o.thumb_secret??o.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(o.width??(NI(o.size)?o.size.width:0))||0,height:Number(o.height??(NI(o.size)?o.size.height:0))||0,fileLength:Number(o.file_length??o.fileLength??0)};break}case"video":d={type:"video",url:jI(e,u,l),thumb:o.thumb||o.thumbnailRemotePath?jI(e,xI(o.thumb??o.thumbnailRemotePath),xI(o.thumb_secret??o.thumbnailSecretKey)):"",secret:l,filename:xI(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:jI(e,u,l),secret:l,filename:xI(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:xI(o.addr??o.address),buildingName:xI(o.buildingName)};break;case"custom":d={type:"custom",customEvent:xI(o.customEvent),customExts:NI(o.customExts)?o.customExts:{}};break;default:return null}return{...c,body:d}},HI=async(e,t,r)=>{const s=`${UI(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=>BI[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=NI(o)?o:{},a=NI(i.data)?i.data:i,c=NI(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=NI(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(!NI(g))continue;const e=KI(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:h,totalPages:p,isLast:m}},VI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/api/sdk/v1/${t}/${r}`},WI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),JI=e=>WI(e)&&"string"==typeof e.path&&e.path.trim().length>0,ZI=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||JI(e),QI=e=>{if(!WI(e))return;return{data:WI(e.data)?e.data:void 0,error:WI(e.error)?e.error:void 0}},YI=(e,t)=>{const r=QI(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},XI=(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||WI(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))),tw=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},rw=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof Hr&&WI(e.details)?e.details:void 0,r=QI(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 XI("File upload failed",$r,{cause:e.details});if(e instanceof Hr&&!t)return e;if(t)switch(t){case"4041001":return XI("File not found",Or,{serviceCode:t,serviceMessage:r});case"4001002":return XI("Invalid file",Ur,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return XI("File upload failed",$r,{serviceCode:t,serviceMessage:r});case"4001003":return XI("Voice duration exceeds 60 seconds",kr,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return XI("Voice-to-text service is not enabled",$t,{serviceCode:t,serviceMessage:r});case"4031002":return XI("Beta service usage limit exceeded",Gr,{serviceCode:t,serviceMessage:r});case"4001001":return"string"==typeof(s=r)&&s.toLowerCase().includes("uploaded file exceeds")?XI("File too large",xr,{serviceCode:t,serviceMessage:r}):XI(r||"Missing or invalid request parameter",nt,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return XI("Voice-to-text failed",Nr,{serviceCode:t,serviceMessage:r});case"4011001":return XI(r||"Unauthorized or invalid token",dt,{serviceCode:t,serviceMessage:r},"auth");default:return XI(r||(e instanceof Error?e.message:"Voice-to-text failed"),Nr,{serviceCode:t,serviceMessage:r})}var s;return e instanceof Hr?XI(e.message,e.code,e.details):XI(e instanceof Error?e.message:"Voice-to-text failed",Nr)},sw=(e,t)=>{if(!WI(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 XI("Invalid file",Ur,{path:"voiceMessageBody"},"validation");var r;if(ew(t))throw XI("Invalid file",Ur,{path:"voiceParams"},"validation");if(!e.url)throw XI("File not found",Or,{path:"voiceMessageBody.url"});if(!tw(e.url))throw XI("Invalid file",Ur,{path:"voiceMessageBody.url"},"validation");return e},nw=(e,t)=>{if(ew(t))throw XI("Invalid file",Ur,{path:"voiceParams"},"validation");if(!ZI(e))throw XI("Invalid file",Ur,{path:"file"},"validation");return e},ow=async(e,t,r,s)=>{const n=sw(r,s),o=tw(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(`${VI(t)}/speech/transcriptions`,{data:{fileId:o,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:YI(r,"voiceMessageToText")}}catch(i){throw rw(i)}},iw=Ev({keywordList:Mv(Sv()).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:Nv(["or","and"]).optional(),conversationId:Sv().min(1).optional(),conversationType:Nv(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:Mv(Nv(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Tv().optional(),endTime:Tv().optional(),searchScope:Nv(["none","with","only"]).optional(),direction:Nv(["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"}),aw=Ev({option:iw,pageNum:Tv().int().min(1).default(1),pageSize:Tv().int().min(1).max(100).default(20)}),cw=pb(mb,{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"]}}}}}),dw=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=Ov.validateOrThrow(fI,e),s=TI(t),n=_I(),o={content:r.content};return r.targetLanguages&&(o.targetLanguages=r.targetLanguages),MI(r,s,"text",o,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=Ov.validateOrThrow(gI,e),n=TI(t),o=_I(),i=s.data?RI(void 0,s.data):"",a=s.originalUrl?no(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&Lp.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:AI({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),MI(s,n,"image",d,o)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(yI,e),s=TI(t),n=_I(),o=RI(r.originalUrl,r.data);r.data&&Lp.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),MI(r,s,"file",i,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(vI,e),s=TI(t),n=_I(),o=RI(r.originalUrl,r.data);r.data&&Lp.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),MI(r,s,"voice",i,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(bI,e),s=TI(t),n=_I(),o=RI(r.originalUrl,r.data);r.data&&Lp.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),MI(r,s,"video",i,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(II,e),s=TI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),MI(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(wI,e),s=TI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),MI(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=Ov.validateOrThrow(CI,e),s=TI(t),n={event:r.event};return r.params&&(n.params=r.params),MI(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return EI(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(vg);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=Jb(t),n=Bb(r.conversationId,"params.conversationId"),o=Fb(r.conversationType,"params.conversationType"),i=r.deleteRoamingMessages??!1;if("boolean"!=typeof i)throw qb("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":jb(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=Jb(t),n=Bb(r.conversationId,"params.conversationId"),o=Fb(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw qb("params.pinned","params.pinned must be a boolean");const i="groupChat"===o?"groupChat":jb(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=pl(a)&&pl(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)=>Zb(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)=>Zb(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=Jb(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)=>Qb(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>Qb(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=Jb(t),n=Bb(r.conversationId,"params.conversationId"),o=Fb(r.conversationType,"params.conversationType"),i=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(jb(o))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=pl(i)&&pl(i.data)?i.data:{};return{items:(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!pl(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:pl(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=Vb(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=`${UI(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=DI(o,"getHistoryMessages"),a=Array.isArray(i.msgs)?i.msgs:[],c=[];for(const d of a){if(!NI(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(kI(d.msg));e&&c.push(e)}return{items:c,cursor:LI(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=Ov.validateOrThrow(aw,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>HI(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?`${UI(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${o}`:`${UI(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=new URLSearchParams;s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${UI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,o=await e.get(n,{operation:"getGroupMessageReadUsers"}),i=DI(o,"getGroupMessageReadUsers"),a=NI(i.group_ack)?i.group_ack:i,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>NI(e)&&"string"==typeof e.username?{userId:e.username,user:PI(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:LI(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=`${UI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return $I(n,"getGroupMessageReadReceipts").map(e=>NI(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(`${UI(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=`${UI(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=new URLSearchParams,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(`${UI(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return $I(o,"getReactionList").map(e=>{if(!NI(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>NI(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=new URLSearchParams;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(`${UI(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),o=DI(n,"getReactionDetail"),i=Array.isArray(o.reactionUserList)?o.reactionUserList.map(e=>NI(e)&&"string"==typeof e.userId?{userId:e.userId,user:PI(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:PI(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:LI(o.cursor),hasMore:LI(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 OI(()=>e.get(`${UI(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return qI(r,"getSupportedTranslationLanguages").map(e=>NI(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 OI(()=>e.post(`${UI(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=qI(s,"translateMessage"),o=NI(n[0])?n[0]:null;if(!o)throw Lg({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const i=Array.isArray(o.translations)?o.translations:[],a=NI(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=>NI(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){sw(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>ow(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){nw(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=nw(r,s),o=Fn({file:n,fallbackName:JI(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${VI(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[rl]:tl()},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:YI(n,"voiceFileToText")}}catch(i){if(i instanceof Hr)throw rw(i);throw rw(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 qg(e.restBaseUrl,{errorMap:cw,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 iI({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)}};dw.key="chatManager";let uw=dw;class lw{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 hw=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),pw=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),mw=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw hw(t);return e.trim()},fw=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw pw(t,`${t} must be a string`);return e},gw=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw pw(t,`${t} must be an integer between 1 and 50`);return e},yw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},vw=e=>pl(e)?e:null,bw=e=>{const t=vw(e);return t?.data??e},Iw=e=>{const t=vw(e);if(Array.isArray(t?.entities))return t.entities;const r=bw(e);if(Array.isArray(r))return r;const s=vw(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},ww=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)??""},Cw=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,o="string"==typeof n?ml(n,{}):vw(n)??{},i=Array.isArray(o.bodies)?o.bodies:[],a=vw(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}},Sw=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:Cw(t.lastMessage??t.last_message)}:null},Tw=e=>({items:Iw(e).map(e=>Sw(e)).filter(e=>null!==e),cursor:ww(e)}),_w=async(e,t,r)=>{const s=yw(t),n=mw(r,"chatThreadId");return(e=>{const t=bw(e),r=Array.isArray(t)?t[0]:t,s=Sw(r);if(!s)throw pw("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},Rw=async(e,t,r)=>{const s=yw(t),n=mw(r.chatThreadId,"params.chatThreadId"),o=gw(r.pageSize,"params.pageSize"),i=fw(r.cursor,"params.cursor"),a=new URLSearchParams({limit:String(o),cursor:i}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:Iw(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:ww(d)};var d},Aw=async(e,t,r)=>{const s=yw(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw hw("params.chatThreadIds");if(r.chatThreadIds.length>20)throw pw("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>mw(e,`params.chatThreadIds[${t}]`)),o=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:Iw(o).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:Cw(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},Mw=pb(mb,{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"]}}}}}),Ew=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 lw(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=yw(t),n=mw(r.parentId,"params.parentId"),o=mw(r.name,"params.name"),i=mw(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=vw(bw(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw pw("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=yw(t),n=mw(r.parentId,"params.parentId"),o=gw(r.pageSize,"params.pageSize"),i=fw(r.cursor,"params.cursor"),a=new URLSearchParams({limit:String(o),cursor:i}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return Tw(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=yw(t),n=gw(r.pageSize,"params.pageSize"),o=fw(r.cursor,"params.cursor"),i=new URLSearchParams({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 Tw(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=yw(t),n=mw(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=yw(t),n=mw(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=yw(t),n=mw(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=yw(t),n=mw(r.chatThreadId,"params.chatThreadId"),o=mw(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 Rw(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=yw(t),n=mw(r.chatThreadId,"params.chatThreadId"),o=mw(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 Aw(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 qg(e.restBaseUrl,{errorMap:Mw,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}}};Ew.key="chatThreadManager";let Uw=Ew;class kw{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 Nw=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Ow=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},xw=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Lw=e=>({userId:e}),Pw=(e,t,r)=>{const s={userId:r};for(const n of Nw){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Dw=async(e,t)=>{const r=Ow(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,xw(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,Lw(i));return s},$w=e=>pl(e)?e:null,qw=e=>"string"==typeof e?e:void 0,Bw=e=>{const t=qw(e)?.trim();return t||void 0},Gw=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}},Fw=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},jw=e=>{const t=$w(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},zw=e=>{const t=$w(e);return t?$w(t.data)?t.data:t:null},Kw=(e,t)=>{const r=$w(e),s=r&&$w(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Gw(n[0])},Hw=e=>Bw(e.chatRoomId)??Bw(e.chatroomid)??Bw(e.id)??"",Vw=e=>qw(e.name)??qw(e.title)??qw(e.groupname)??"",Ww=e=>Lw(e),Jw=(e,t)=>{const r=$w(e);if(!r)return null;const s=Hw(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)})(Bw(r.owner)):Bw(r.owner);return{chatRoomId:s,name:Vw(r),owner:n?Ww(n):void 0,memberCount:Gw(r.memberCount)??Gw(r.affiliations_count),disabled:Fw(r.disabled)}},Zw=(e,t)=>{const r=(e=>{const t=$w(e);return t?Gw(t.count):void 0})(e),s=jw(e).map(e=>Jw(e,t)).filter(e=>null!==e),n=Kw(e,"pagenum"),o=Kw(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}},Qw=(e,t)=>{const r=jw(e),s=$w(r[0])??zw(e)??{},n=Jw(s)??{chatRoomId:Hw(s),name:Vw(s)},o=((e,t)=>{if(!t)return;if(Bw(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const s of r){const e=$w(s);if(e){if(Bw(e.owner)===t)return"owner";if(Bw(e.admin)===t)return"admin";if(Bw(e.member)===t)return"member"}}})(s,t),i=Gw(s.muteExpireAt)??Gw(s.mute_expire)??Gw(s.expire),a=Fw(s.inAllowlist)??Fw(s.white)??Fw(s.in_whitelist),c=Fw(s.muted);return{...n,description:qw(s.description),maxMembers:Gw(s.maxMembers)??Gw(s.maxusers)??Gw(s.max_users),createdAt:Gw(s.createdAt)??Gw(s.created),ext:qw(s.ext)??qw(s.custom),announcement:qw(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}},Yw=e=>jw(e).map(e=>Bw(e)).filter(e=>Boolean(e)).map(e=>Ww(e)),Xw=(e,t)=>{const r=zw(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=$w(r.errorKeys)??{},o={};for(const[i,a]of Object.entries(n))"string"==typeof a&&(o[i]={code:tC(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:o}},eC=e=>{const t=$w(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],o=[];return s.forEach(e=>{const t=$w(e),r=(e=>{const t=$w(e);if(!t)return null;const r=Bw(t.user),s=Bw(t.chatRoomId)??Bw(t.chatroomid)??Bw(t.id),n=qw(t.action),o=Fw(t.result);return r&&s&&void 0!==n&&void 0!==o?{chatRoomId:s,user:Ww(r),action:n,reason:qw(t.reason),...o?{}:{reason:qw(t.reason)??"failed"}}:null})(e);if(!r||!t)return;Fw(t.result)?n.push(r):o.push(r)}),{succeeded:n,failed:o}},tC=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?Gr:e.includes("is not part of you")?Ir:e.includes("is not Legal")||e.includes("is not exist")?nt:fr,rC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},sC=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),nC=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),oC=(e,t)=>`/${e.orgName}/${e.appName}${t}`,iC=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw nC(t,`${t} must be a string`);return e}},aC=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw nC(t,`${t} must be a number`);return e}},cC=(e,t)=>{const r=new URLSearchParams;"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}`:""},dC=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw sC(t);return e.trim()},uC=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw sC(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw nC(`${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 sC(t);return r},lC=(e,t)=>uC(e,t),hC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o={},i=iC(r.name,"params.name"),a=iC(r.description,"params.description"),c=aC(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 sC("params");const d=oC(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=zw(e)??{};return{nameUpdated:Fw(t.groupname),descriptionUpdated:Fw(t.description),maxMembersUpdated:Fw(t.maxusers)}})(await e.put(d,o,{operation:"updateChatRoomInfo"}))},pC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=new URLSearchParams;"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 jw(e)){const e=$w(n);if(!e)continue;const r=Bw(e.owner),s=Bw(e.admin),o=Bw(e.member),i=r??s??o;i&&t.push({user:Ww(i),role:r?"owner":s?"admin":"member",joinedAt:Gw(e.joinedAt)??Gw(e.joined_time)})}const r=$w(e),s=r?Bw(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(o,{operation:"getChatRoomMemberList"}))},mC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/admin`),i=await e.get(o,{operation:"getChatRoomAdminList"});return Yw(i)},fC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=new URLSearchParams;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=oC(s,`/chatrooms/${encodeURIComponent(n)}/mute?${o.toString()}`);return(e=>{const t=jw(e);if(t.every(e=>"string"==typeof e))return Yw(e).map(e=>({user:e}));const r=[];for(const s of t){const e=$w(s);if(!e)continue;const t=Bw(e.user)??Bw(e.member)??Bw(e.owner)??Bw(e.admin);t&&r.push({user:Ww(t),muteExpire:Gw(e.muteExpire)??Gw(e.expire)??Gw(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(i,{operation:"getChatRoomMuteList"}))},gC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=zw(e)??{};return{muted:Fw(t.muted)??Fw(t.value)??Boolean(t.data),muteExpireAt:Gw(t.muteExpireAt)??Gw(t.expire)??Gw(t.mute_expire)}})(await e.get(o,{operation:"isCurrentUserMutedInChatRoom"}))},yC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=cC(r),i=o?"&":"",a=oC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${i}${o.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return Yw(c).map(e=>({user:e}))},vC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),i=await e.get(o,{operation:"getChatRoomAllowlist"});return Yw(i).map(e=>({user:e}))},bC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=zw(e)??{};return Fw(t.value)??Fw(t.white)??!1})(await e.get(o,{operation:"checkIfInChatRoomAllowList"}))},IC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=zw(e)??{};return{announcement:qw(t.announcement)??""}})(await e.get(o,{operation:"getChatRoomAnnouncement"}))},wC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=zw(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(o,{keys:r.keys?lC(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},CC=async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw nC(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw sC(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw nC(t,`${t} contains invalid key`);if("string"!=typeof r)throw nC(`${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=oC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:o,autoDelete:i?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return Xw(u,n)},SC={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},TC=(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 TC(`${t} must be a string`,t,"invalid_format");return e},RC=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw TC(`${t} must be a string, number, or boolean`,t,"invalid_format")},AC=(e,t="attribute")=>{const r=SC[e];if(!r)throw TC(`${t} is invalid`,t,"invalid_format");return r},MC=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw TC(`${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 TC(`${t} is required`,t,"required");return r},EC=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw TC(`${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 SC))throw TC(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw TC(`${t} is required`,t,"required");return r},UC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/get`},kC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},NC=e=>({targets:MC(e)}),OC=e=>!!pl(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),xC=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!pl(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},LC=(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},PC=(e,t)=>{const r=(e=>{const t=new Map,r=pl(e)?e:null;if(r?.data&&pl(r.data))for(const[s,n]of Object.entries(r.data))OC(n)&&t.set(s,n);return xC(r?.entities,t),xC(r?.data&&pl(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=pl(e)?e:null;if(!r?.lastModified||!pl(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:LC(o,e),lastModified:s.get(o)})}return n},DC=(e,t)=>PC(e,t).map(e=>e.profile),$C=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,_C(r,s)]):e.push([t,String(RC(r,s))]))},qC=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),BC={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},GC=pb(mb,{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}}}}}),FC=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=BC[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=BC[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=rC(t),n=oC(s,`/chatrooms${cC(r)}`),o=await e.get(n,{operation:"getChatRoomList"});return Zw(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 kw(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true`),i=await e.get(o,{operation:"getChatRoomInfo"});return Qw(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 hC(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=dC(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=dC(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 pC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(s,`/chatrooms/${encodeURIComponent(n)}/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{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 mC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=dC(r.userId,"params.userId"),i=oC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=dC(r.userId,"params.userId"),i=oC(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 fC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=aC(r.duration,"params.duration"),a=oC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=oC(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 gC(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await yC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=1===o.length,a=oC(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 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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(i,{usernames:o},{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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=uC(r.userIds,"params.userIds"),i=oC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${o.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(i,{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 bC(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return IC(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=iC(r.announcement,"params.announcement");if(void 0===o)throw sC("params.announcement");const i=oC(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 wC(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await CC(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=rC(t),n=dC(r.chatRoomId,"params.chatRoomId"),o=lC(r.keys,"params.keys"),{isForced:i=!1}=r,a=i?"/forced":"",c=oC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:o},operation:"removeChatRoomAttributes"});return Xw(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 qg(e.restBaseUrl,{errorMap:GC,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 Dw(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=Ow(e),s=await Dw(r,t);return r.map(e=>Pw(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=NC(e),s=await this.getRestClient(t).request(UC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return DC(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 Pw(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>Pw(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:Pw(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:Pw(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:Pw(e.owner,t.get(e.owner.userId),e.owner.userId)}}};FC.key="chatRoomManager";let jC=FC;const zC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},KC=e=>pl(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):[],HC=(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&&pl(e),s},VC=async(e,t)=>{const r=zC(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return KC(n).map(e=>({userId:e}))},WC=async(e,t,r)=>{const s=zC(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:KC(o).map(e=>({userId:e})),failed:[]}},JC={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 ZC=!1,QC=null;const YC=()=>QC||(ZC||(kc.util.Long=ci,kc.configure(),ZC=!0),id(),QC=kc.Root.fromJSON(JC),od(QC),QC),XC=e=>"number"==typeof e?e:ci.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:XC(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:XC(t.protocolVersion)}};class tS{encodeRequest(e){const t=YC().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=Ab){const t=YC().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Sb,status:e})).finish()}decode(e){const t=YC(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case Cb:return{type:Cb};case Sb:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Sb,status:XC(r.status)}}case _b:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:_b,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:XC(t.createdAt),updatedAt:XC(t.updatedAt),metadataUpdatedAt:XC(t.metadataUpdatedAt)}})(e)):[],cursor:XC(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:XC(r.responseType)||Mb}}case Rb:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:Rb,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:wb}}}}class rS{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===Eb?"incremental":"full",version:this.version,pages:this.pages}}}const sS=e=>e.type===_b,nS=e=>"message"in e&&"code"in e;class oS{constructor(e){this.codec=new tS,this.sharedSession=e}async sync(e){const t=new rS(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:sS(t)||nS(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===Cb)return void(await r.send(this.codec.encodePong()));if(sS(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(nS(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 kb:return new Jr(e.message,{code:dt,details:r(!1)});case Nb:return new Hr(e.message,Gr,{details:r(!0)});case Ub:return new Hr(e.message,nt,{details:r(!1)});case Ob:return new Hr(e.message,ot,{details:r(!1)});case xb:return new Hr(e.message,fr,{details:r(!0)});case Lb: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 iS=e=>e.versionState.version?"incremental":"full",aS=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?iS(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}},cS=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{}}},dS=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},uS=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),lS=e=>{To("Contact sync duration",e)};class hS{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=aS({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void lS({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(dS(s)){const r=aS({metadataFailed:!0,state:e}),n=s instanceof Hr?s:new Hr("Contact metadata request failed",wr,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:uS("metadata",n.code,n.message,!1)}),void lS({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=aS({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:uS("metadata",wr,s instanceof Error?s.message:String(s),!0)}),void lS({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 oS(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=cS(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(),lS({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:uS(i,n.code,n.message,!0)}),lS({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 pS={items:[],loaded:!1,source:"server"},mS=pb(mb,{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:{}}}}),fS=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=pS,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=pS,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=zC(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=zC(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=zC(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=zC(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=zC(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 VC(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=HC(e,"params.userIds"),s=this.getRestClient(t);So("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await WC(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=HC(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=zC(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 qg(e.restBaseUrl,{errorMap:mS,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=pS)}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 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 To("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=NC(e),s=await this.getRestClient(t).request(UC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return DC(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 hS(e)}};fS.key="contactManager";let gS=fS;class yS{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)}},bS=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),IS=(e,t)=>new Zr(t,{code:ot,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),wS=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw bS(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw IS(`${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 bS(t);return r},CS=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw bS(t);return e.trim()},SS=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw IS(t,`${t} must be a string`);return e}},TS=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw IS(t,`${t} must be a boolean`);return e}},_S=(e,t)=>`/${e.orgName}/${e.appName}${t}`,RS=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),AS=e=>{const t=new URLSearchParams;"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}`:""},MS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Rl(e),r=wl(t[0]),s=Al(e)??r;return{groupId:s&&Ul(s)||r&&Ul(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?wS(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"}))},ES=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o=_S(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),i=await e.get(o,{operation:"getGroupInfo"});return Nl(i)},US=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o={},i=SS(r.name,"params.name"),a=SS(r.description,"params.description"),c=SS(r.avatar,"params.avatar"),d=SS(r.ext,"params.ext"),u=TS(r.public,"params.public"),l=TS(r.joinApprovalRequired,"params.joinApprovalRequired"),h=TS(r.allowInvites,"params.allowInvites"),p=TS(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw IS(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 bS("params");const f=_S(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,o,{operation:"updateGroupInfo"})},kS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/users${(e=>{const t=new URLSearchParams;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 Rl(e)){const e=wl(o);if(!e)continue;const r=Sl(e.owner),s=Sl(e.admin),n=Sl(e.member),i=r??s??n;if(!i)continue;const a=Tl(e.joinedAt)??Tl(e.joined_time);t.push({user:Ol(i),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=Ml(e,"pagenum"),s=Ml(e,"pagesize"),n=El(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},NS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/admin`),o=await e.get(n,{operation:"getGroupAdminList"});return xl(o)},OS=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o=AS(r),i=o?"&":"",a=_S(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${i}${o.replace("?","")}`);return(e=>{const t=[];for(const r of Rl(e)){const e=Sl(r);if(e){t.push({user:Ol(e)});continue}const s=wl(r);if(!s)continue;const n=Sl(s.user);if(!n)continue;const o=Tl(s.expire);t.push({user:Ol(n),...void 0===o?{}:{muteExpire:o}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},xS=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o=AS(r),i=o?"&":"",a=_S(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${i}${o.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return xl(c).map(e=>({user:e}))},LS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/white/users`),o=await e.get(n,{operation:"getGroupAllowlist"});return xl(o).map(e=>({user:e}))},PS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=Al(e)??{};return{announcement:Cl(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},DS=async(e,t,r)=>{const s=vS(t),n=new URLSearchParams;n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const o=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=Ml(e,"pagenum"),r=Ml(e,"pagesize"),s=El(e,r);return{items:Rl(e).map(e=>Ll(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(o,{operation:"getGroupSharedFileList"}))},$S=(e,t)=>{const r=vS(e);return _S(r,`/chatgroups/${encodeURIComponent(CS(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(CS(t.fileId,"params.fileId"))}`)},qS=async(e,t,r)=>{const s=vS(t),n=CS(r.groupId,"params.groupId"),o=CS(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(!RS.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"})},BS=async(e,t,r)=>{const s=vS(t),n=_S(s,`/sdk/metadata/chatgroup/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/get`);return(e=>{const t=Al(e)??{},r=wl(t.data)??t,s={};for(const[n,o]of Object.entries(r)){const e=wl(o);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:wS(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},GS=e=>{const t=pl(e)?e:{},r=t.data,s=pl(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return FS(n);const o=pl(r)?r:t,i=pl(o.namecards)?o.namecards:o,a={};for(const[c,d]of Object.entries(i)){if("string"==typeof d){a[c]={namecard:d};continue}if(!pl(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:jS(d)})}return a},FS=e=>{const t={};return e.forEach(e=>{if(!pl(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:jS(e)})}),t},jS=e=>wh("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),zS=e=>{if(pl(e))return wh("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 KS{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 HS=e=>({...e}),VS=e=>({...e,owner:e.owner?{...e.owner}:void 0});class WS{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=HS({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=VS({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=HS(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?HS(this.summarySnapshot):this.detailSnapshot?HS(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?VS(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 JS{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 ZS{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new JS,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 WS(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 QS=0,YS=5,XS=12,eT=13,tT=0,rT=1,sT=2,nT=0,oT=1,iT=2,aT=3,cT=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===tT?"owner":s===rT?"admin":s===sT?"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===nT?"DEFAULT":r===oT?"ALL":r===iT?"AT":r===aT?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},dT=e=>e.updatedAt??0,uT=(e,t)=>{if(!e)return!0;return dT(t)>=dT(e)},lT={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 hT=null,pT=!1;const mT=()=>hT||(pT||(kc.util.Long=ci,kc.configure(),pT=!0),id(),hT=kc.Root.fromJSON(lT),od(hT),hT),fT=e=>mT().lookupType(e),gT=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(ci.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}},yT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:gT(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:gT(t.protocol_version)??gT(t.protocolVersion)??0}};class vT{constructor(){this.requestType=fT("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=fT("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=fT("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:QS}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=gT(t.type);return r!==XS?null:{type:r,header:yT(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:gT(t.last_sync_time)??gT(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=gT(t.type);return r!==eT?null:{type:r,header:yT(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:gT(t.members_count)??gT(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:gT(t.role),mute_expiration:gT(t.mute_expiration)??gT(t.muteExpiration),remind_type:gT(t.remind_type)??gT(t.remindType),create_at:gT(t.create_at)??gT(t.createAt),update_at:gT(t.update_at)??gT(t.updateAt),joined_timestamp:gT(t.joined_timestamp)??gT(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:gT(t.last_sync_finished_ts)??gT(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=gT(t.type);return r!==YS?null:{type:r,header:yT(t.header),code:gT(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class bT{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 IT=e=>e.type===eT,wT=e=>e.type===YS;class CT{constructor(e){this.codec=new vT,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new bT(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:IT(t)||wT(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(IT(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(wT(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,Gr,{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 ST{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 CT(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),o=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=cT(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);uT(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=af;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:of,serverLimit:af,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:XS,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const TT=pb(mb,{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 ZS,this.groupEventSync=new KS(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 MS(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 yS(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 ES(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=wS(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(pl(i)&&Array.isArray(i.data)?i.data:[]).map(e=>Nl({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 US(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:wS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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 kS(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=wS(r.userIds,"params.userIds"),o=_S(s,`/chatgroups/${encodeURIComponent(CS(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 NS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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 OS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:wS(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=wS(r.userIds,"params.userIds"),o=_S(s,`/chatgroups/${encodeURIComponent(CS(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=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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 xS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:wS(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=wS(r.userIds,"params.userIds"),o=_S(s,`/chatgroups/${encodeURIComponent(CS(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 LS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:wS(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=wS(r.userIds,"params.userIds"),o=_S(s,`/chatgroups/${encodeURIComponent(CS(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=vS(t),n=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),o=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof o?o:pl(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=vS(t),n=_S(s,`/sdk/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),o=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof o?o:pl(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 PS(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=_S(s,`/chatgroups/${encodeURIComponent(CS(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 DS(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=$S(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=Fn({file:e.file}),n=Np({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}`,[rl]:tl()},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===Br&&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=_S(s,`/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(CS(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}${$S(s,e)}`;t=Np({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}:{},[rl]:tl()},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 qS(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return BS(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=_S(s,`/sdk/chatgroups/${encodeURIComponent(CS(r.groupId,"params.groupId"))}/nameCard/batch/get`),o=await e.post(n,{members:wS(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:GS(o),responseTimestamp:zS(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 qg(e.restBaseUrl,{errorMap:TT,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 ZS),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new KS(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 ES(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=wh("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!pl(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(pl(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];pl(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;pl(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 Il(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 bl(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>bl(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:bl(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 ES(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=NC(e),s=await this.getRestClient(t).request(UC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return DC(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(Xb(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await iI({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 oI({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 ST(e)}};_T.key="groupManager";let RT=_T;const AT=pb(mb,{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}}}}}),MT=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 qg(e.restBaseUrl,{errorMap:AT,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}})}};MT.key="presenceManager";let ET=MT;const UT=pb(mb,{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}}}}}),kT=["singleChat","groupChat"],NT=["ALL","AT","NONE","DEFAULT"],OT=["ALL","AT","NONE"],xT=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),LT=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=wg({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 qg(e.restBaseUrl,{errorMap:UT,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||!kT.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(!xT(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(!OT.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(!xT(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(!xT(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(xT(e.data)){const r=e.data[t];if(xT(r))return r}const r=e[t];return xT(r)?r:{}}resolveSilentModeRuleSource(e){if(!xT(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return xT(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":NT.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(xT(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}})}};LT.key="pushManager";let PT=LT;const DT=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},$T=(e,t="params.userIds")=>MC(e,t),qT=e=>{const t=$T(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",Gr);return{usernames:t}},BT=(e,t)=>{const r=(e=>$T(e))(t);return`${DT(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},GT=(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}},FT=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],jT=pb(mb,{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}}}}}),zT=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=GT(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=NC(MC(e.userIds,"params.userIds")),n=UC(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=MC(e.userIds,"params.userIds"),o=EC(e.attributes,"params.attributes"),{targets:MC(n),properties:EC(o).map(e=>AC(e,"params.attributes"))});var n,o;const i=UC(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=>DT(e))(t),n=qT(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=BT(t,e.userIds);So("UserInfoManager unsubscribeUsersInfo",{userIds:MC(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=>DT(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($C(t,"nickname",e.nickname,"params.nickname"),$C(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),$C(t,"mail",e.mail,"params.mail"),$C(t,"phone",e.phone,"params.phone"),$C(t,"gender",e.gender,"params.gender"),$C(t,"sign",e.sign,"params.sign"),$C(t,"birth",e.birth,"params.birth"),$C(t,"ext",e.ext,"params.ext"),0===t.length)throw TC("params must include at least one updatable field","params","required");return qC(t)})(e),n=kC(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=AC(e,"attribute"),s=RC(t,"value");if("gender"!==r&&"string"!=typeof s)throw TC("value must be a string","value","invalid_format");return qC([[r,String(s)]])})(e,t),o=kC(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 qg(e.restBaseUrl,{errorMap:jT,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 PC(e,t)}normalizeUpdateEnvelope(e,t,r){const s=pl(e)?e:null,n=(s&&pl(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!!pl(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 FT)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return FT.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=wh(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)}};zT.key="userInfoManager";let KT=zT;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=kf,e.ChatClient=$b,e.ChatManager=uw,e.ChatRoom=kw,e.ChatRoomManager=jC,e.ChatThread=lw,e.ChatThreadManager=Uw,e.ConnectionError=Wr,e.ContactManager=gS,e.Group=yS,e.GroupManager=RT,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.MessageReceiveError=Yr,e.MessageSendError=Qr,e.NetworkError=Vr,e.PresenceManager=ET,e.PushManager=PT,e.RUNTIME_PLATFORMS=Eo,e.RestBusinessError=ts,e.RestTransportError=es,e.SDKError=Hr,e.StorageError=Xr,e.StreamMessageStatus=rt,e.UploadError=rs,e.UserInfoManager=KT,e.ValidationError=Zr,e.createPlatformAdapter=$u,e.detectRuntimePlatform=(e,t)=>si(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}({});
|